instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getOperationType() {
return operationType; } public void setOperationType(String operationType) { this.operationType = operationType; } public String getAssignerId() { return assignerId; } public void setAssignerId(String assignerId) { this.assignerId = assignerId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIdentityLinkLogEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public Result<Boolean> insert(@RequestBody User user) { // 参数验证 if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.insertUser(user) > 0); } // 修改一条记录 @RequestMapping(value = "/users", method = RequestMethod.PUT) @ResponseBody public Result<Boolean> update(@RequestBody User tempUser) { //参数验证 if (tempUser.getId() == null || tempUser.getId() < 1 || StringUtils.isEmpty(tempUser.getName()) || StringUtils.isEmpty(tempUser.getPassword())) { return ResultGenerator.genFailResult("缺少参数"); } //实体验证,不存在则不继续修改操作 User user = userDao.getUserById(tempUser.getId()); if (user == null) { return ResultGenerator.genFailResult("参数异常"); } user.setName(tempUser.getName());
user.setPassword(tempUser.getPassword()); return ResultGenerator.genSuccessResult(userDao.updUser(user) > 0); } // 删除一条记录 @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE) @ResponseBody public Result<Boolean> delete(@PathVariable("id") Integer id) { if (id == null || id < 1) { return ResultGenerator.genFailResult("缺少参数"); } return ResultGenerator.genSuccessResult(userDao.delUser(id) > 0); } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-RESTful-api\src\main\java\cn\lanqiao\springboot3\controller\ApiController.java
2
请完成以下Java代码
public List<String> getEmail() { if (email == null) { email = new ArrayList<String>(); } return this.email; } /** * Gets the value of the url property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the url property. * * <p> * For example, to add a new item, do as follows:
* <pre> * getUrl().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getUrl() { if (url == null) { url = new ArrayList<String>(); } return this.url; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\OnlineAddressType.java
1
请完成以下Java代码
public static JobDefinitionSuspensionStateConfiguration byJobDefinitionId(String jobDefinitionId, boolean includeJobs) { JobDefinitionSuspensionStateConfiguration configuration = new JobDefinitionSuspensionStateConfiguration(); configuration.by = JOB_HANDLER_CFG_JOB_DEFINITION_ID; configuration.jobDefinitionId = jobDefinitionId; configuration.includeJobs = includeJobs; return configuration; } public static JobDefinitionSuspensionStateConfiguration byProcessDefinitionId(String processDefinitionId, boolean includeJobs) { JobDefinitionSuspensionStateConfiguration configuration = new JobDefinitionSuspensionStateConfiguration(); configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_ID; configuration.processDefinitionId = processDefinitionId; configuration.includeJobs = includeJobs; return configuration; } public static JobDefinitionSuspensionStateConfiguration byProcessDefinitionKey(String processDefinitionKey, boolean includeJobs) { JobDefinitionSuspensionStateConfiguration configuration = new JobDefinitionSuspensionStateConfiguration(); configuration.by = JOB_HANDLER_CFG_PROCESS_DEFINITION_KEY; configuration.processDefinitionKey = processDefinitionKey; configuration.includeJobs = includeJobs; return configuration;
} public static JobDefinitionSuspensionStateConfiguration ByProcessDefinitionKeyAndTenantId(String processDefinitionKey, String tenantId, boolean includeProcessInstances) { JobDefinitionSuspensionStateConfiguration configuration = byProcessDefinitionKey(processDefinitionKey, includeProcessInstances); configuration.isTenantIdSet = true; configuration.tenantId = tenantId; return configuration; } } public void onDelete(JobDefinitionSuspensionStateConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerChangeJobDefinitionSuspensionStateJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void run() { while (true) { String url = null; try { url = cacheService.takeQueueTask(); if (url != null) { FileAttribute fileAttribute = fileHandlerService.getFileAttribute(url, null); FileType fileType = fileAttribute.getType(); logger.info("正在处理预览转换任务,url:{},预览类型:{}", url, fileType); if (isNeedConvert(fileType)) { FilePreview filePreview = previewFactory.get(fileAttribute); filePreview.filePreviewHandle(url, new ExtendedModelMap(), fileAttribute); } else { logger.info("预览类型无需处理,url:{},预览类型:{}", url, fileType); } } } catch (Exception e) { try { TimeUnit.SECONDS.sleep(10);
} catch (Exception ex) { Thread.currentThread().interrupt(); logger.error("Failed to sleep after exception", ex); } logger.info("处理预览转换任务异常,url:{}", url, e); } } } public boolean isNeedConvert(FileType fileType) { return fileType.equals(FileType.COMPRESS) || fileType.equals(FileType.OFFICE) || fileType.equals(FileType.CAD); } } }
repos\kkFileView-master\server\src\main\java\cn\keking\service\FileConvertQueueTask.java
2
请完成以下Java代码
public ColumnDefinitions getColumnDefinitions() { return delegate.getColumnDefinitions(); } @NonNull @Override public ExecutionInfo getExecutionInfo() { return delegate.getExecutionInfo(); } @Override public int remaining() { return delegate.remaining(); } @NonNull @Override public Iterable<Row> currentPage() { return delegate.currentPage(); } @Override public boolean hasMorePages() { return delegate.hasMorePages(); } @NonNull @Override public CompletionStage<AsyncResultSet> fetchNextPage() throws IllegalStateException { return delegate.fetchNextPage(); } @Override public boolean wasApplied() { return delegate.wasApplied(); } public ListenableFuture<List<Row>> allRows(Executor executor) { List<Row> allRows = new ArrayList<>(); SettableFuture<List<Row>> resultFuture = SettableFuture.create(); this.processRows(originalStatement, delegate, allRows, resultFuture, executor); return resultFuture; } private void processRows(Statement statement,
AsyncResultSet resultSet, List<Row> allRows, SettableFuture<List<Row>> resultFuture, Executor executor) { allRows.addAll(loadRows(resultSet)); if (resultSet.hasMorePages()) { ByteBuffer nextPagingState = resultSet.getExecutionInfo().getPagingState(); Statement<?> nextStatement = statement.setPagingState(nextPagingState); TbResultSetFuture resultSetFuture = executeAsyncFunction.apply(nextStatement); Futures.addCallback(resultSetFuture, new FutureCallback<TbResultSet>() { @Override public void onSuccess(@Nullable TbResultSet result) { processRows(nextStatement, result, allRows, resultFuture, executor); } @Override public void onFailure(Throwable t) { resultFuture.setException(t); } }, executor != null ? executor : MoreExecutors.directExecutor() ); } else { resultFuture.set(allRows); } } List<Row> loadRows(AsyncResultSet resultSet) { return Lists.newArrayList(resultSet.currentPage()); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSet.java
1
请完成以下Java代码
private byte[] loadArchiveData(@NonNull final I_AD_Archive archiveRecord) { byte[] data = archiveBL.getBinaryData(archiveRecord); if (data == null || data.length == 0) { logger.info("AD_Archive {} does not contain any data. Skip", archiveRecord); data = null; } return data; } @NonNull private PrintingSegment createPrintingSegmentForQueueItem( @NonNull final I_C_Printing_Queue printingQueue) { final int trayRepoId = printingQueue.getAD_PrinterHW_MediaTray_ID(); final HardwarePrinterId printerId = HardwarePrinterId.ofRepoId(printingQueue.getAD_PrinterHW_ID()); final HardwareTrayId trayId = HardwareTrayId.ofRepoIdOrNull(printerId, trayRepoId); final HardwarePrinter hardwarePrinter = hardwarePrinterRepository.getById(printerId); return PrintingSegment.builder() .printer(hardwarePrinter) .trayId(trayId) .routingType(I_AD_PrinterRouting.ROUTINGTYPE_PageRange) .copies(printingQueue.getCopies()) .build(); } private PrintingSegment createPrintingSegment( @NonNull final I_AD_PrinterRouting printerRouting, @Nullable final UserId userToPrintId, @Nullable final String hostKey, final int copies) { final I_AD_Printer_Matching printerMatchingRecord = printingDAO.retrievePrinterMatchingOrNull(hostKey/*hostKey*/, userToPrintId, printerRouting.getAD_Printer()); if (printerMatchingRecord == null) {
logger.debug("Found no AD_Printer_Matching record for AD_PrinterRouting_ID={}, AD_User_PrinterMatchingConfig_ID={} and hostKey={}; -> creating no PrintingSegment for routing", printerRouting, UserId.toRepoId(userToPrintId), hostKey); return null; } final I_AD_PrinterTray_Matching trayMatchingRecord = printingDAO.retrievePrinterTrayMatching(printerMatchingRecord, printerRouting, false); final int trayRepoId = trayMatchingRecord == null ? -1 : trayMatchingRecord.getAD_PrinterHW_MediaTray_ID(); final HardwarePrinterId printerId = HardwarePrinterId.ofRepoId(printerMatchingRecord.getAD_PrinterHW_ID()); final HardwareTrayId trayId = HardwareTrayId.ofRepoIdOrNull(printerId, trayRepoId); final HardwarePrinter hardwarePrinter = hardwarePrinterRepository.getById(printerId); return PrintingSegment.builder() .printerRoutingId(PrinterRoutingId.ofRepoId(printerRouting.getAD_PrinterRouting_ID())) .initialPageFrom(printerRouting.getPageFrom()) .initialPageTo(printerRouting.getPageTo()) .lastPages(printerRouting.getLastPages()) .routingType(printerRouting.getRoutingType()) .printer(hardwarePrinter) .trayId(trayId) .copies(CoalesceUtil.firstGreaterThanZero(copies, 1)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingDataFactory.java
1
请完成以下Java代码
public class X_MD_Candidate_QtyDetails extends org.compiere.model.PO implements I_MD_Candidate_QtyDetails, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1818023286L; /** Standard Constructor */ public X_MD_Candidate_QtyDetails (final Properties ctx, final int MD_Candidate_QtyDetails_ID, @Nullable final String trxName) { super (ctx, MD_Candidate_QtyDetails_ID, trxName); } /** Load Constructor */ public X_MD_Candidate_QtyDetails (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDetail_MD_Candidate_ID (final int Detail_MD_Candidate_ID) { if (Detail_MD_Candidate_ID < 1) set_Value (COLUMNNAME_Detail_MD_Candidate_ID, null); else set_Value (COLUMNNAME_Detail_MD_Candidate_ID, Detail_MD_Candidate_ID); } @Override public int getDetail_MD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_Detail_MD_Candidate_ID); } @Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public void setMD_Candidate_QtyDetails_ID (final int MD_Candidate_QtyDetails_ID) { if (MD_Candidate_QtyDetails_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, MD_Candidate_QtyDetails_ID); }
@Override public int getMD_Candidate_QtyDetails_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID) { if (Stock_MD_Candidate_ID < 1) set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null); else set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID); } @Override public int getStock_MD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
1
请完成以下Java代码
public static boolean isSameDayUsingInstant(Date date1, Date date2) { Instant instant1 = date1.toInstant() .truncatedTo(ChronoUnit.DAYS); Instant instant2 = date2.toInstant() .truncatedTo(ChronoUnit.DAYS); return instant1.equals(instant2); } public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); return fmt.format(date1) .equals(fmt.format(date2)); } public static boolean isSameDayUsingCalendar(Date date1, Date date2) { Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
} public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { return DateUtils.isSameDay(date1, date2); } public static boolean isSameDayUsingJoda(Date date1, Date date2) { org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); return localDate1.equals(localDate2); } public static boolean isSameDayUsingDate4j(Date date1, Date date2) { DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); return dateObject1.isSameDayAs(dateObject2); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\date\comparison\DateComparisonUtils.java
1
请完成以下Java代码
public class ErrorEndEventActivityBehavior extends AbstractBpmnActivityBehavior { protected String errorCode; private ParameterValueProvider errorMessageExpression; public ErrorEndEventActivityBehavior(String errorCode, ParameterValueProvider errorMessage) { this.errorCode = errorCode; this.errorMessageExpression = errorMessage; } public void execute(ActivityExecution execution) throws Exception { String errorMessageValue = errorMessageExpression != null ? (String) errorMessageExpression.getValue(execution) : null; BpmnExceptionHandler.propagateError(errorCode, errorMessageValue, null, execution); }
public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public ParameterValueProvider getErrorMessageExpression() { return errorMessageExpression; } public void setErrorMessageExpression(ParameterValueProvider errorMessage) { this.errorMessageExpression = errorMessage; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ErrorEndEventActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<String> getCaseDefinitionKeys() { return caseDefinitionKeys; } public boolean isExcludeSubtasks() { return excludeSubtasks; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } @Override public List<Task> list() { cachedCandidateGroups = null; return super.list(); } @Override public List<Task> listPage(int firstResult, int maxResults) { cachedCandidateGroups = null; return super.listPage(firstResult, maxResults); } @Override public long count() { cachedCandidateGroups = null; return super.count(); }
public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; } public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java
2
请完成以下Java代码
public Optional<CurrencyCode> getStatementCurrencyCode() { return Optional.ofNullable(accountStatement2.getAcct().getCcy()) .map(CurrencyCode::ofThreeLetterCode); } @Override @NonNull public String getId() { return accountStatement2.getId(); } @Override @NonNull public ImmutableList<IStatementLineWrapper> getStatementLines() { return accountStatement2.getNtry() .stream() .map(this::buildBatchReportEntryWrapper) .collect(ImmutableList.toImmutableList()); } @Override public boolean hasNoBankStatementLines() { return accountStatement2.getNtry().isEmpty(); } @Override @NonNull protected Optional<String> getAccountIBAN() { return Optional.ofNullable(accountStatement2.getAcct().getId().getIBAN()); } @Override @NonNull protected Optional<String> getSwiftCode() { return Optional.ofNullable(accountStatement2.getAcct().getSvcr()) .map(branchAndFinancialInstitutionIdentification4 -> branchAndFinancialInstitutionIdentification4.getFinInstnId().getBIC()) .filter(Check::isNotBlank); } @Override @NonNull protected Optional<String> getAccountNo() { return Optional.ofNullable(accountStatement2.getAcct().getId().getOthr()) .map(GenericAccountIdentification1::getId); } @NonNull private IStatementLineWrapper buildBatchReportEntryWrapper(@NonNull final ReportEntry2 reportEntry) { return BatchReportEntry2Wrapper.builder() .currencyRepository(getCurrencyRepository()) .entry(reportEntry) .build(); } @NonNull private Optional<CashBalance3> findOPBDCashBalance() { return accountStatement2.getBal()
.stream() .filter(AccountStatement2Wrapper::isOPBDCashBalance) .findFirst(); } @NonNull private Optional<CashBalance3> findPRCDCashBalance() { return accountStatement2.getBal() .stream() .filter(AccountStatement2Wrapper::isPRCDCashBalance) .findFirst(); } private static boolean isPRCDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.PRCD.equals(balanceTypeCode); } private static boolean isOPBDCashBalance(@NonNull final CashBalance3 cashBalance) { final BalanceType12Code balanceTypeCode = cashBalance.getTp().getCdOrPrtry().getCd(); return BalanceType12Code.OPBD.equals(balanceTypeCode); } private static boolean isCRDTCashBalance(@NonNull final CashBalance3 cashBalance) { return CRDT.equals(cashBalance.getCdtDbtInd()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\AccountStatement2Wrapper.java
1
请完成以下Java代码
public class StudentMap { private List<StudentEntry> entries = new ArrayList<StudentEntry>(); @XmlElement(nillable = false, name = "entry") public List<StudentEntry> getEntries() { return entries; } @XmlType(name = "StudentEntry") public static class StudentEntry { private Integer id; private Student student; public void setId(Integer id) { this.id = id;
} public Integer getId() { return id; } public void setStudent(Student student) { this.student = student; } public Student getStudent() { return student; } } }
repos\tutorials-master\apache-cxf-modules\cxf-introduction\src\main\java\com\baeldung\cxf\introduction\StudentMap.java
1
请完成以下Spring Boot application配置
server: port: 8888 spring: application: name: gateway-application cloud: # Spring Cloud Gateway 配置项,对应 GatewayProperties 类 gateway: # 路由配置项,对应 RouteDefinition 数组 routes: - id: yudaoyuanma # 路由的编号 uri: http://www.iocoder.cn # 路由到的目标地址 predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组 - Path=/** sentinel: eager: true # 是否饥饿加载。默认为 false 关闭 transport: dashboard: localhost:7070 # 是否饥饿加载。默认为 false 关闭 # # 数据源的配置项 # datasource: # ds1.file: # file: "classpath: sentinel-gw-flow.json" # ruleType: gw-flow # ds2.file: # file: "classpath: sentinel-gw-api-group.json" # ruleType: gw-api-group # Sentinel 对 Spring Cloud Gateway 的专属配置项,对应 SentinelGatewayProperties 类 scg: order: -214748364
8 # 过滤器顺序,默认为 -2147483648 最高优先级 fallback: mode: # fallback 模式,目前有三种:response、redirect、空 # 专属 response 模式 response-status: 429 # 响应状态码,默认为 429 response-body: 你被 block 了... # 响应内容,默认为空 content-type: application/json # 内容类型,默认为 application/json # 专属 redirect 模式 redirect: http://www.baidu.com
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo07-sentinel\src\main\resources\application.yaml
2
请完成以下Java代码
public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightUOM (final @Nullable java.lang.String WeightUOM) { set_Value (COLUMNNAME_WeightUOM, WeightUOM); } @Override public java.lang.String getWeightUOM() { return get_ValueAsString(COLUMNNAME_WeightUOM); } @Override public void setWeight_UOM_ID (final int Weight_UOM_ID) { if (Weight_UOM_ID < 1) set_Value (COLUMNNAME_Weight_UOM_ID, null); else set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID); } @Override public int getWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID); }
@Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } @Override public void setX12DE355 (final @Nullable java.lang.String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } @Override public java.lang.String getX12DE355() { return get_ValueAsString(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Product.java
1
请完成以下Java代码
public int getC_UOM_ID() { return invoiceLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { invoiceLine.setC_UOM_ID(uomId); } @Override public void setQty(@NonNull final BigDecimal qtyInHUsUOM) { invoiceLine.setQtyEntered(qtyInHUsUOM); final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID()); final BigDecimal qtyInvoiced = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qtyInHUsUOM); invoiceLine.setQtyInvoiced(qtyInvoiced); } @Override public BigDecimal getQty() { return invoiceLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { // // Check the invoice line first final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID(); if (invoiceLine_PIItemProductId > 0) { return invoiceLine_PIItemProductId; } // // Check order line final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class); if (orderline == null) { // // C_OrderLine not found (i.e Manual Invoice) return -1; } return orderline.getM_HU_PI_Item_Product_ID();
} @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return invoiceLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { invoiceLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public DeveloperRestApiProperties getDevRestApi() { return developerRestApiProperties; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public boolean isSslRequireAuthentication() { return this.sslRequireAuthentication; } public void setSslRequireAuthentication(boolean sslRequireAuthentication) { this.sslRequireAuthentication = sslRequireAuthentication; } } public static class MemcachedServerProperties { private static final int DEFAULT_PORT = 11211; private int port = DEFAULT_PORT; private EnableMemcachedServer.MemcachedProtocol protocol = EnableMemcachedServer.MemcachedProtocol.ASCII; public int getPort() { return this.port; } public void setPort(int port) { this.port = port; }
public EnableMemcachedServer.MemcachedProtocol getProtocol() { return this.protocol; } public void setProtocol(EnableMemcachedServer.MemcachedProtocol protocol) { this.protocol = protocol; } } public static class RedisServerProperties { public static final int DEFAULT_PORT = 6379; private int port = DEFAULT_PORT; private String bindAddress; public String getBindAddress() { return this.bindAddress; } public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ServiceProperties.java
2
请完成以下Java代码
private Hyperlink createHyperlinkIfURL(@Nullable final String str) { if (str == null || str.isEmpty()) { return null; } final String urlStr = str.trim(); if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { new URI(urlStr); final Hyperlink hyperlink = getWorkbook().getCreationHelper().createHyperlink(HyperlinkType.URL); hyperlink.setAddress(urlStr); return hyperlink; } catch (final URISyntaxException e) { return null; } } else { return null; } } public File exportToTempFile(@NonNull String fileNamePrefix) { final File file; try { file = File.createTempFile(fileNamePrefix, "." + excelFormat.getFileExtension()); } catch (final IOException ex) { throw new AdempiereException("Failed creating temporary excel file", ex); } exportToFile(file); return file; } public void exportToFile(@NonNull final File file) { try (final FileOutputStream out = new FileOutputStream(file)) { export(out); } catch (final IOException ex) {
throw new AdempiereException("Failed exporting to " + file, ex); } } @Value private static final class CellStyleKey { public static CellStyleKey header(final int column) { final int displayType = -1; // N/A final boolean functionRow = false; return new CellStyleKey("header", column, displayType, functionRow); } public static CellStyleKey cell(final int column, final int displayType, final boolean functionRow) { return new CellStyleKey("cell", column, displayType, functionRow); } private final String type; private final int column; private final int displayType; private final boolean functionRow; private CellStyleKey( final String type, final int column, final int displayType, final boolean functionRow) { this.type = type; this.column = column; this.displayType = displayType; this.functionRow = functionRow; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\AbstractExcelExporter.java
1
请完成以下Java代码
public class C_Order_VoidWithRelatedDocsAndRecreate extends JavaProcess implements IProcessPrecondition { private final IDocumentBL documentBL = Services.get(IDocumentBL.class); private final VoidOrderAndRelatedDocsService orderVoidedHandlerRegistry = Adempiere.getBean(VoidOrderAndRelatedDocsService.class); @Param(mandatory = true, parameterName = "VoidedOrderDocumentNoPrefix") private String p_VoidedOrderDocumentNoPrefix; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final I_C_Order orderRecord = context.getSelectedModel(I_C_Order.class); if (!orderRecord.isSOTrx()) { return ProcessPreconditionsResolution.rejectWithInternalReason("Currently this process is only implemented for sales orders"); } final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(orderRecord.getDocStatus()); if (!docStatus.isCompleted()) { return ProcessPreconditionsResolution.rejectWithInternalReason("selected C_Order_ID=" + orderRecord.getC_Order_ID() + " is not completed"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final I_C_Order orderRecord = getRecord(I_C_Order.class); final VoidOrderAndRelatedDocsRequest request = createRequest(orderRecord);
orderVoidedHandlerRegistry.invokeHandlers(request); return MSG_OK; } private VoidOrderAndRelatedDocsRequest createRequest(final I_C_Order orderRecord) { final OrderId requestOrderId = OrderId.ofRepoId(orderRecord.getC_Order_ID()); final IPair<RecordsToHandleKey, List<ITableRecordReference>> // requestRecordsToHandle = ImmutablePair.of( RecordsToHandleKey.of(I_C_Order.Table_Name), ImmutableList.of(TableRecordReference.of(orderRecord))); final VoidOrderAndRelatedDocsRequest request = VoidOrderAndRelatedDocsRequest .builder() .orderId(requestOrderId) .recordsToHandle(requestRecordsToHandle) .voidedOrderDocumentNoPrefix(p_VoidedOrderDocumentNoPrefix) .build(); return request; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\voidorderandrelateddocs\process\C_Order_VoidWithRelatedDocsAndRecreate.java
1
请在Spring Boot框架中完成以下Java代码
public InsuranceContractQuantity quantity(BigDecimal quantity) { this.quantity = quantity; return this; } /** * Anzahl * @return quantity **/ @Schema(example = "3", description = "Anzahl") public BigDecimal getQuantity() { return quantity; } public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } public InsuranceContractQuantity unit(String unit) { this.unit = unit; return this; } /** * Mengeneinheit (mögliche Werte &#x27;Stk&#x27; oder &#x27;Ktn&#x27;) * @return unit **/ @Schema(example = "Stk", description = "Mengeneinheit (mögliche Werte 'Stk' oder 'Ktn')") public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public InsuranceContractQuantity archived(Boolean archived) { this.archived = archived; return this; } /** * Maximalmenge nicht mehr gültig - archiviert * @return archived **/ @Schema(example = "false", description = "Maximalmenge nicht mehr gültig - archiviert") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true;
} if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractQuantity insuranceContractQuantity = (InsuranceContractQuantity) o; return Objects.equals(this.pcn, insuranceContractQuantity.pcn) && Objects.equals(this.quantity, insuranceContractQuantity.quantity) && Objects.equals(this.unit, insuranceContractQuantity.unit) && Objects.equals(this.archived, insuranceContractQuantity.archived); } @Override public int hashCode() { return Objects.hash(pcn, quantity, unit, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractQuantity {\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractQuantity.java
2
请完成以下Java代码
public String toSqlWhereClause() {return toSqlWhereClause0(importTableName, true);} /** * @return `AND ...` where clause */ public String toSqlWhereClause(@Nullable final String importTableAlias) { return toSqlWhereClause0(importTableAlias, true); } private String toSqlWhereClause0(@Nullable final String importTableAlias, final boolean prefixWithAND) { final String importTableAliasWithDot = StringUtils.trimBlankToOptional(importTableAlias).map(alias -> alias + ".").orElse(""); final StringBuilder whereClause = new StringBuilder(); if (prefixWithAND) { whereClause.append(" AND "); } whereClause.append("("); if (empty) { return "1=2"; } else { // AD_Client whereClause.append(importTableAliasWithDot).append(ImportTableDescriptor.COLUMNNAME_AD_Client_ID).append("=").append(clientId.getRepoId()); // Selection_ID if (selectionId != null) {
final String importKeyColumnNameFQ = importTableAliasWithDot + importKeyColumnName; whereClause.append(" AND ").append(DB.createT_Selection_SqlWhereClause(selectionId, importKeyColumnNameFQ)); } } whereClause.append(")"); return whereClause.toString(); } public IQueryFilter<Object> toQueryFilter(@Nullable final String importTableAlias) { return empty ? ConstantQueryFilter.of(false) : TypedSqlQueryFilter.of(toSqlWhereClause0(importTableAlias, false)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportRecordsSelection.java
1
请完成以下Java代码
class WebServerStartStopLifecycle implements SmartLifecycle { private final WebServerManager weServerManager; private volatile boolean running; WebServerStartStopLifecycle(WebServerManager weServerManager) { this.weServerManager = weServerManager; } @Override public void start() { this.weServerManager.start(); this.running = true; } @Override public void stop() { this.running = false; this.weServerManager.stop(); }
@Override public boolean isRunning() { return this.running; } @Override public int getPhase() { return WebServerApplicationContext.START_STOP_LIFECYCLE_PHASE; } @Override public boolean isPauseable() { return false; } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerStartStopLifecycle.java
1
请在Spring Boot框架中完成以下Java代码
public String updateInventory(@Validated @ModelAttribute(INVENTORY_ATTR) Inventory inventory, BindingResult bindingResult, RedirectAttributes redirectAttributes, SessionStatus sessionStatus) { if (!bindingResult.hasErrors()) { try { Inventory updatedInventory = inventoryService.updateInventory(inventory); redirectAttributes.addFlashAttribute("updatedInventory", updatedInventory); } catch (OptimisticLockingFailureException e) { bindingResult.reject("", "Another user updated the data. Press the link above to reload it."); } } if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute(BINDING_RESULT, bindingResult); return "redirect:load/" + inventory.getId(); }
sessionStatus.setComplete(); return "redirect:success"; } @GetMapping(value = "/success") public String success() { return "success"; } @InitBinder void allowFields(WebDataBinder webDataBinder ) { webDataBinder.setAllowedFields("quantity"); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootHTTPLongConversationDetachedEntity\src\main\java\com\bookstore\controller\InventoryController.java
2
请在Spring Boot框架中完成以下Java代码
public class JobResource { // @Autowired private JobRepository jobRepository; @GET @Produces("application/json") @Path("/jobs") public List<Job> getAllJobs(){ return jobRepository.findAll(); } @GET @Produces("application/json") @Path("/jobs") public ResponseEntity<Job> getJobById(@PathVariable(value = "id") Long jobId) throws ResourceNotFoundException{ Job job = jobRepository.findById(jobId) .orElseThrow(()-> new ResourceNotFoundException("Job not found ::" + jobId)); return ResponseEntity.ok().body(job); } @POST @Produces("appliction/json") @Consumes("application/json") @Path("/jobs") @PostMapping("/jobs") public Job createJob(Job job){ return jobRepository.save(job); } @PUT @Consumes("application/json") @Path("/jobs/{id}") public ResponseEntity<Job> updateJob(@PathParam(value = "id") Long jobId, @Valid @RequestBody Job jobDetails) throws ResourceNotFoundException { Job job = jobRepository.findById(jobId)
.orElseThrow(()->new ResourceNotFoundException("Job not found::" + jobId)); job.setEmailId(jobDetails.getEmailId()); job.setLastName(jobDetails.getLastName()); job.setFirstName(jobDetails.getFirstName()); final Job updateJob = jobRepository.save(job); return ResponseEntity.ok(updateJob); } @DELETE @Path("/jobs/{id}") public Map<String, Boolean> deleteJob (@PathParam(value = "id") Long jobId) throws ResourceNotFoundException{ Job job = jobRepository.findById(jobId) .orElseThrow(()-> new ResourceNotFoundException("User not found::" + jobId)); jobRepository.delete(job); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.FALSE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Jersey-JPA\src\main\java\spring\database\controller\JobResource.java
2
请完成以下Java代码
private static DataSource buildDataSource() { // 创建 HikariConfig 配置类 HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver"); hikariConfig.setJdbcUrl(DB_URL + "/" + DB_NAME); hikariConfig.setUsername(DB_USERNAME); hikariConfig.setPassword(DB_PASSWORD); hikariConfig.addDataSourceProperty("useInformationSchema", "true"); // 设置可以获取 tables remarks 信息 // 创建数据源 return new HikariDataSource(hikariConfig); } /** * 创建 screw 的引擎配置 */ private static EngineConfig buildEngineConfig() { return EngineConfig.builder() .fileOutputDir(FILE_OUTPUT_DIR) // 生成文件路径 .openOutputDir(false) // 打开目录 .fileType(FILE_OUTPUT_TYPE) // 文件类型 .produceType(EngineTemplateType.freemarker) // 文件类型 .fileName(DOC_FILE_NAME) // 自定义文件名称
.build(); } /** * 创建 screw 的处理配置,一般可忽略 * 指定生成逻辑、当存在指定表、指定表前缀、指定表后缀时,将生成指定表,其余表不生成、并跳过忽略表配置 */ private static ProcessConfig buildProcessConfig() { return ProcessConfig.builder() .designatedTableName(Collections.<String>emptyList()) // 根据名称指定表生成 .designatedTablePrefix(Collections.<String>emptyList()) //根据表前缀生成 .designatedTableSuffix(Collections.<String>emptyList()) // 根据表后缀生成 .ignoreTableName(Arrays.asList("test_user", "test_group")) // 忽略表名 .ignoreTablePrefix(Collections.singletonList("test_")) // 忽略表前缀 .ignoreTableSuffix(Collections.singletonList("_test")) // 忽略表后缀 .build(); } }
repos\SpringBoot-Labs-master\lab-70-db-doc\lab-70-db-doc-screw-01\src\main\java\ScrewMain.java
1
请完成以下Java代码
public boolean containsKey(Object key) { for (Resolver scriptResolver : scriptResolvers) { if (scriptResolver.containsKey(key)) { return true; } } return defaultBindings.containsKey(key); } public Object get(Object key) { for (Resolver scriptResolver : scriptResolvers) { if (scriptResolver.containsKey(key)) { return scriptResolver.get(key); } } return defaultBindings.get(key); } public Object put(String name, Object value) { if (storeScriptVariables) { Object oldValue = null; if (!UNSTORED_KEYS.contains(name)) { oldValue = variableScope.getVariable(name); variableScope.setVariable(name, value); return oldValue; } } return defaultBindings.put(name, value); } public Set<Map.Entry<String, Object>> entrySet() { return variableScope.getVariables().entrySet(); } public Set<String> keySet() { return variableScope.getVariables().keySet(); } public int size() { return variableScope.getVariables().size(); } public Collection<Object> values() { return variableScope.getVariables().values(); }
public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); } public void clear() { throw new UnsupportedOperationException(); } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public void createRequestsForQuarantineLines(final I_DD_Order ddOrder) { final List<DDOrderLineId> ddOrderLineToQuarantineIds = retrieveLineToQuarantineWarehouseIds(ddOrder); C_Request_CreateFromDDOrder_Async.createWorkpackage(ddOrderLineToQuarantineIds); } @DocValidate(timings = { ModelValidator.TIMING_AFTER_REACTIVATE, ModelValidator.TIMING_AFTER_VOID, ModelValidator.TIMING_AFTER_REVERSEACCRUAL, ModelValidator.TIMING_AFTER_REVERSECORRECT }) public void voidMovements(final I_DD_Order ddOrder) { // void if creating them automating is activated if (ddOrderService.isCreateMovementOnComplete()) { final List<I_M_Movement> movements = movementDAO.retrieveMovementsForDDOrder(ddOrder.getDD_Order_ID()); for (final I_M_Movement movement : movements) { movementBL.voidMovement(movement); } } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void createMovementsIfNeeded(final I_DD_Order ddOrder) { if (ddOrderService.isCreateMovementOnComplete()) { ddOrderService.generateDirectMovements(ddOrder); }
} private List<DDOrderLineId> retrieveLineToQuarantineWarehouseIds(final I_DD_Order ddOrder) { return ddOrderService.retrieveLines(ddOrder) .stream() .filter(this::isQuarantineWarehouseLine) .map(line -> DDOrderLineId.ofRepoId(line.getDD_OrderLine_ID())) .collect(ImmutableList.toImmutableList()); } private boolean isQuarantineWarehouseLine(final I_DD_OrderLine ddOrderLine) { final I_M_Warehouse warehouse = warehouseDAO.getWarehouseByLocatorRepoId(ddOrderLine.getM_LocatorTo_ID()); return warehouse != null && warehouse.isQuarantineWarehouse(); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REVERSEACCRUAL, ModelValidator.TIMING_BEFORE_REVERSECORRECT, ModelValidator.TIMING_BEFORE_VOID }) public void removeDDOrderCandidateAllocations(@NonNull final I_DD_Order ddOrder) { final DDOrderId ddOrderId = DDOrderId.ofRepoId(ddOrder.getDD_Order_ID()); ddOrderCandidateService.deleteAndUpdateCandidatesByDDOrderId(ddOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\interceptor\DD_Order.java
1
请完成以下Java代码
public void process() { assertNotProcessed(); if (checks.size() < weightChecksRequired) { throw new AdempiereException(MSG_LessChecksThanRequired); } updateToleranceExceededFlag(); if (isToleranceExceeded) { throw new AdempiereException(MSG_ToleranceExceeded); } this.isProcessed = true; } public void unprocess() { this.isProcessed = false; } public void updateToleranceExceededFlag() { assertNotProcessed(); boolean isToleranceExceededNew = false; for (PPOrderWeightingRunCheck check : checks) { check.updateIsToleranceExceeded(targetWeightRange); if (check.isToleranceExceeded()) { isToleranceExceededNew = true; } } this.isToleranceExceeded = isToleranceExceededNew; } public void updateTargetWeightRange() { assertNotProcessed(); final Quantity toleranceQty = targetWeight.multiply(tolerance).abs(); this.targetWeightRange = Range.closed(
targetWeight.subtract(toleranceQty), targetWeight.add(toleranceQty) ); updateToleranceExceededFlag(); } public void updateUOMFromHeaderToChecks() { assertNotProcessed(); for (final PPOrderWeightingRunCheck check : checks) { check.setUomId(targetWeight.getUomId()); } } private void assertNotProcessed() { if (isProcessed) { throw new AdempiereException("Already processed"); } } public I_C_UOM getUOM() { return targetWeight.getUOM(); } public SeqNo getNextLineNo() { final SeqNo lastLineNo = checks.stream() .map(PPOrderWeightingRunCheck::getLineNo) .max(Comparator.naturalOrder()) .orElseGet(() -> SeqNo.ofInt(0)); return lastLineNo.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRun.java
1
请完成以下Java代码
public class Todo { private Long id; private String title; private LocalDate dueDate; public Todo() { } public Todo(Long id, String title, LocalDate dueDate) { this.id = id; this.title = title; this.dueDate = dueDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } public LocalDate getDueDate() { return dueDate; } public void setDueDate(LocalDate dueDate) { this.dueDate = dueDate; } }
repos\tutorials-master\spring-boot-modules\spring-boot-swagger-keycloak\src\main\java\com\baeldung\swaggerkeycloak\Todo.java
1
请完成以下Java代码
protected void removeIdentityLinkType(CommandContext commandContext, String processInstanceId, String identityType) { ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId); // this will remove ALL identity links with the given identity type (for users AND groups) IdentityLinkUtil.deleteProcessInstanceIdentityLinks(processInstanceEntity, null, null, identityType); } /** * Creates a new identity link entry for the given process instance, which can either be a user or group based one, but not both the same time. * If both the user and group ids are null, no new identity link is created. * * @param commandContext the command context within which to perform the identity link creation * @param processInstanceId the id of the process instance to create an identity link for * @param userId the user id if this is a user based identity link, otherwise null * @param groupId the group id if this is a group based identity link, otherwise null * @param identityType the type of identity link (e.g. owner or assignee, etc)
*/ protected void createIdentityLinkType(CommandContext commandContext, String processInstanceId, String userId, String groupId, String identityType) { // if both user and group ids are null, don't create an identity link if (userId == null && groupId == null) { return; } // if both are set the same time, throw an exception as this is not allowed if (userId != null && groupId != null) { throw new FlowableIllegalArgumentException("Either set the user id or the group id for an identity link, but not both the same time."); } ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId); IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity, userId, groupId, identityType); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\AbstractProcessInstanceIdentityLinkCmd.java
1
请完成以下Java代码
private final IAttributeStorage getAttributeStorage(final IHUContext huContext, final I_M_HU hu) { final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory(); final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu); return attributeStorage; } private final HUTransformService newHUTransformation() { return HUTransformService.builder() .referencedObjects(getContextDocumentLines()) .build(); } /**
* @return context document/lines (e.g. the receipt schedules) */ private List<TableRecordReference> getContextDocumentLines() { if (view == null) { return ImmutableList.of(); } return view.getReferencingDocumentPaths() .stream() .map(referencingDocumentPath -> documentCollections.getTableRecordReference(referencingDocumentPath)) .collect(GuavaCollectors.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUIHUCreationWithSerialNumberService.java
1
请完成以下Java代码
private static @Nullable Throwable getRootCause(final Throwable throwable) { final List<Throwable> list = getThrowableList(throwable); return list.isEmpty() ? null : list.get(list.size() - 1); } private static List<Throwable> getThrowableList(Throwable throwable) { final List<Throwable> list = new ArrayList<>(); while (throwable != null && !list.contains(throwable)) { list.add(throwable); throwable = throwable.getCause(); } return list; } public static class Config { private static final String EXECUTION_EXCEPTION_TYPE = "Execution-Exception-Type"; private static final String EXECUTION_EXCEPTION_MESSAGE = "Execution-Exception-Message"; private static final String ROOT_CAUSE_EXCEPTION_TYPE = "Root-Cause-Exception-Type"; private static final String ROOT_CAUSE_EXCEPTION_MESSAGE = "Root-Cause-Exception-Message"; private String executionExceptionTypeHeaderName = EXECUTION_EXCEPTION_TYPE; private String executionExceptionMessageHeaderName = EXECUTION_EXCEPTION_MESSAGE; private String rootCauseExceptionTypeHeaderName = ROOT_CAUSE_EXCEPTION_TYPE; private String rootCauseExceptionMessageHeaderName = ROOT_CAUSE_EXCEPTION_MESSAGE; public String getExecutionExceptionTypeHeaderName() { return executionExceptionTypeHeaderName; } public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) { this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName; } public String getExecutionExceptionMessageHeaderName() { return executionExceptionMessageHeaderName; }
public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) { this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName; } public String getRootCauseExceptionTypeHeaderName() { return rootCauseExceptionTypeHeaderName; } public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) { this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName; } public String getRootCauseExceptionMessageHeaderName() { return rootCauseExceptionMessageHeaderName; } public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) { this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\FallbackHeadersGatewayFilterFactory.java
1
请完成以下Java代码
public void setM_ProductDownload_ID (int M_ProductDownload_ID) { if (M_ProductDownload_ID < 1) set_Value (COLUMNNAME_M_ProductDownload_ID, null); else set_Value (COLUMNNAME_M_ProductDownload_ID, Integer.valueOf(M_ProductDownload_ID)); } /** Get Product Download. @return Product downloads */ public int getM_ProductDownload_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Referrer. @param Referrer Referring web address */ public void setReferrer (String Referrer) { set_ValueNoCheck (COLUMNNAME_Referrer, Referrer); } /** Get Referrer. @return Referring web address */ public String getReferrer () { return (String)get_Value(COLUMNNAME_Referrer); } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () {
return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Serial No. @param SerNo Product Serial Number */ public void setSerNo (String SerNo) { set_ValueNoCheck (COLUMNNAME_SerNo, SerNo); } /** Get Serial No. @return Product Serial Number */ public String getSerNo () { return (String)get_Value(COLUMNNAME_SerNo); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } /** Set Version No. @param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java
1
请完成以下Java代码
public static Integer findMajorityElementUsingHashMap(int[] nums) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } int majorityThreshold = nums.length / 2; for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { if (entry.getValue() > majorityThreshold) { return entry.getKey(); } } return null; } public static Integer findMajorityElementUsingMooreVoting(int[] nums) { int majorityThreshold = nums.length / 2; int candidate = nums[0]; int count = 1; for (int i = 1; i < nums.length; i++) { if (count == 0) { candidate = nums[i]; count = 1; } else if (candidate == nums[i]) { count++; } else { count--; } System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]"); } count = 0; for (int num : nums) {
if (num == candidate) { count++; } } return count > majorityThreshold ? candidate : null; } public static void main(String[] args) { int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; Integer majorityElement = findMajorityElementUsingMooreVoting(nums); if (majorityElement != null) { System.out.println("Majority element with maximum occurrences: " + majorityElement); } else { System.out.println("No majority element found"); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\majorityelement\FindMajorityElement.java
1
请完成以下Java代码
public class TypeInfoStructure { public static class Fleet { private List<Vehicle> vehicles; public List<Vehicle> getVehicles() { return vehicles; } public void setVehicles(List<Vehicle> vehicles) { this.vehicles = vehicles; } } public static abstract class Vehicle { private String make; private String model; protected Vehicle() { } protected Vehicle(String make, String model) { this.make = make; this.model = model; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } } public static class Car extends Vehicle { private int seatingCapacity; private double topSpeed;
public Car() { } public Car(String make, String model, int seatingCapacity, double topSpeed) { super(make, model); this.seatingCapacity = seatingCapacity; this.topSpeed = topSpeed; } public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Truck extends Vehicle { private double payloadCapacity; public Truck() { } public Truck(String make, String model, double payloadCapacity) { super(make, model); this.payloadCapacity = payloadCapacity; } public double getPayloadCapacity() { return payloadCapacity; } public void setPayloadCapacity(double payloadCapacity) { this.payloadCapacity = payloadCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\TypeInfoStructure.java
1
请在Spring Boot框架中完成以下Java代码
public R<TopMenu> detail(TopMenu topMenu) { TopMenu detail = topMenuService.getOne(Condition.getQueryWrapper(topMenu)); return R.data(detail); } /** * 分页 顶部菜单表 */ @GetMapping("/list") @ApiOperationSupport(order = 2) @Operation(summary = "分页", description = "传入topMenu") public R<IPage<TopMenu>> list(TopMenu topMenu, Query query) { IPage<TopMenu> pages = topMenuService.page(Condition.getPage(query), Condition.getQueryWrapper(topMenu).lambda().orderByAsc(TopMenu::getSort)); return R.data(pages); } /** * 新增 顶部菜单表 */ @PostMapping("/save") @ApiOperationSupport(order = 4) @Operation(summary = "新增", description = "传入topMenu") public R save(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.save(topMenu)); } /** * 修改 顶部菜单表 */ @PostMapping("/update") @ApiOperationSupport(order = 5) @Operation(summary = "修改", description = "传入topMenu") public R update(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.updateById(topMenu)); } /** * 新增或修改 顶部菜单表 */ @PostMapping("/submit")
@ApiOperationSupport(order = 6) @Operation(summary = "新增或修改", description = "传入topMenu") public R submit(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.saveOrUpdate(topMenu)); } /** * 删除 顶部菜单表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(topMenuService.deleteLogic(Func.toLongList(ids))); } /** * 设置顶部菜单 */ @PostMapping("/grant") @ApiOperationSupport(order = 8) @Operation(summary = "顶部菜单配置", description = "传入topMenuId集合以及menuId集合") public R grant(@RequestBody GrantVO grantVO) { CacheUtil.clear(SYS_CACHE); CacheUtil.clear(MENU_CACHE); CacheUtil.clear(MENU_CACHE); boolean temp = topMenuService.grant(grantVO.getTopMenuIds(), grantVO.getMenuIds()); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TopMenuController.java
2
请完成以下Java代码
public T get(String id) { return cache.get(id); } @Override public void add(String id, T obj) { cache.put(id, obj); } @Override public void remove(String id) { cache.remove(id); } @Override public boolean contains(String id) { return cache.containsKey(id); }
@Override public void clear() { cache.clear(); } @Override public Collection<T> getAll() { return cache.values(); } @Override public int size() { return cache.size(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\deploy\DefaultDeploymentCache.java
1
请在Spring Boot框架中完成以下Java代码
public class Customer { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; return age == customer.age && name.equals(customer.name); } @Override public int hashCode() { return Objects.hash(name, age); } private String name; private int age; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;
public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\flush\Customer.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setTermDuration (final int TermDuration) { set_Value (COLUMNNAME_TermDuration, TermDuration); } @Override public int getTermDuration() { return get_ValueAsInt(COLUMNNAME_TermDuration); } /** * TermDurationUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMDURATIONUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMDURATIONUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMDURATIONUNIT_WocheN = "week"; /** Tag(e) = day */ public static final String TERMDURATIONUNIT_TagE = "day"; /** Jahr(e) = year */ public static final String TERMDURATIONUNIT_JahrE = "year"; @Override
public void setTermDurationUnit (final java.lang.String TermDurationUnit) { set_Value (COLUMNNAME_TermDurationUnit, TermDurationUnit); } @Override public java.lang.String getTermDurationUnit() { return get_ValueAsString(COLUMNNAME_TermDurationUnit); } @Override public void setTermOfNotice (final int TermOfNotice) { set_Value (COLUMNNAME_TermOfNotice, TermOfNotice); } @Override public int getTermOfNotice() { return get_ValueAsInt(COLUMNNAME_TermOfNotice); } /** * TermOfNoticeUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMOFNOTICEUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMOFNOTICEUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMOFNOTICEUNIT_WocheN = "week"; /** Tag(e) = day */ public static final String TERMOFNOTICEUNIT_TagE = "day"; /** Jahr(e) = year */ public static final String TERMOFNOTICEUNIT_JahrE = "year"; @Override public void setTermOfNoticeUnit (final java.lang.String TermOfNoticeUnit) { set_Value (COLUMNNAME_TermOfNoticeUnit, TermOfNoticeUnit); } @Override public java.lang.String getTermOfNoticeUnit() { return get_ValueAsString(COLUMNNAME_TermOfNoticeUnit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Transition.java
1
请完成以下Java代码
public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (processDefinitionId != null) { referenceIdAndClass.put(processDefinitionId, ProcessDefinitionEntity.class); } if (processInstanceId != null) { referenceIdAndClass.put(processInstanceId, ExecutionEntity.class); } if (executionId != null) { referenceIdAndClass.put(executionId, ExecutionEntity.class); } if (caseDefinitionId != null) { referenceIdAndClass.put(caseDefinitionId, CaseDefinitionEntity.class); } if (caseExecutionId != null) { referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class); } return referenceIdAndClass; } public void bpmnError(String errorCode, String errorMessage, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); BpmnError bpmnError = null; if (errorMessage != null) { bpmnError = new BpmnError(errorCode, errorMessage); } else { bpmnError = new BpmnError(errorCode); } try { if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); } BpmnExceptionHandler.propagateBpmnError(bpmnError, activityExecution); } catch (Exception ex) { throw ProcessEngineLogger.CMD_LOGGER.exceptionBpmnErrorPropagationFailed(errorCode, ex); }
} @Override public boolean hasAttachment() { return attachmentExists; } @Override public boolean hasComment() { return commentExists; } public void escalation(String escalationCode, Map<String, Object> variables) { ensureTaskActive(); ActivityExecution activityExecution = getExecution(); if (variables != null && !variables.isEmpty()) { activityExecution.setVariables(variables); } EscalationHandler.propagateEscalation(activityExecution, escalationCode); } public static enum TaskState { STATE_INIT ("Init"), STATE_CREATED ("Created"), STATE_COMPLETED ("Completed"), STATE_DELETED ("Deleted"), STATE_UPDATED ("Updated"); private String taskState; private TaskState(String taskState) { this.taskState = taskState; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskEntity.java
1
请完成以下Java代码
public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } /** * Filter requests on endpoints that are not in the list of authorized microservices endpoints. */ @Override public boolean shouldFilter() { String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI(); String contextPath = RequestContext.getCurrentContext().getRequest().getContextPath(); // If the request Uri does not start with the path of the authorized endpoints, we block the request for (Route route : routeLocator.getRoutes()) { String serviceUrl = contextPath + route.getFullPath(); String serviceName = route.getId(); // If this route correspond to the current request URI // We do a substring to remove the "**" at the end of the route URL if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) { return !isAuthorizedRequest(serviceUrl, serviceName, requestUri); } } return true; } private boolean isAuthorizedRequest(String serviceUrl, String serviceName, String requestUri) { Map<String, List<String>> authorizedMicroservicesEndpoints = jHipsterProperties.getGateway() .getAuthorizedMicroservicesEndpoints(); // If the authorized endpoints list was left empty for this route, all access are allowed if (authorizedMicroservicesEndpoints.get(serviceName) == null) { log.debug("Access Control: allowing access for {}, as no access control policy has been set up for " + "service: {}", requestUri, serviceName); return true; } else { List<String> authorizedEndpoints = authorizedMicroservicesEndpoints.get(serviceName);
// Go over the authorized endpoints to control that the request URI matches it for (String endpoint : authorizedEndpoints) { // We do a substring to remove the "**/" at the end of the route URL String gatewayEndpoint = serviceUrl.substring(0, serviceUrl.length() - 3) + endpoint; if (requestUri.startsWith(gatewayEndpoint)) { log.debug("Access Control: allowing access for {}, as it matches the following authorized " + "microservice endpoint: {}", requestUri, gatewayEndpoint); return true; } } } return false; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value()); ctx.setSendZuulResponse(false); log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI()); return null; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\accesscontrol\AccessControlFilter.java
1
请完成以下Java代码
private static class SingleSharedSequence implements POJONextIdSupplier { // NOTE: because in some tests we are using hardcoded IDs which are like ~50000, we decided to start the IDs sequence from 100k. private static final int DEFAULT_FirstId = 100000; private int nextId = DEFAULT_FirstId; @Override public int nextId(String tableName) { nextId++; return nextId; } public void reset() { nextId = DEFAULT_FirstId; } } @ToString private static class PerTableSequence implements POJONextIdSupplier { private final int firstId = SingleSharedSequence.DEFAULT_FirstId * 10; // multiply by 10 to prevent overlapping in case we switch from Single Sequence
private final HashMap<String, AtomicInteger> nextIds = new HashMap<>(); @Override public int nextId(@NonNull final String tableName) { final String tableNameNorm = tableName.trim().toLowerCase(); return nextIds.computeIfAbsent(tableNameNorm, k -> new AtomicInteger(firstId)) .getAndIncrement(); } public void reset() { nextIds.clear(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJONextIdSuppliers.java
1
请完成以下Java代码
default V getOrFetchFromDB(K key, Supplier<V> dbCall, boolean cacheNullValue, boolean putToCache) { if (putToCache) { return getAndPutInTransaction(key, dbCall, cacheNullValue); } else { TbCacheValueWrapper<V> cacheValueWrapper = get(key); if (cacheValueWrapper != null) { return cacheValueWrapper.get(); } return dbCall.get(); } } default V getAndPutInTransaction(K key, Supplier<V> dbCall, boolean cacheNullValue) { return getAndPutInTransaction(key, dbCall, Function.identity(), Function.identity(), cacheNullValue); } default <R> R getAndPutInTransaction(K key, Supplier<R> dbCall, Function<V, R> cacheValueToResult, Function<R, V> dbValueToCacheValue, boolean cacheNullValue) { TbCacheValueWrapper<V> cacheValueWrapper = get(key); if (cacheValueWrapper != null) { V cacheValue = cacheValueWrapper.get(); return cacheValue != null ? cacheValueToResult.apply(cacheValue) : null; } var cacheTransaction = newTransactionForKey(key); try { R dbValue = dbCall.get(); if (dbValue != null || cacheNullValue) { cacheTransaction.put(key, dbValueToCacheValue.apply(dbValue));
cacheTransaction.commit(); return dbValue; } else { cacheTransaction.rollback(); return null; } } catch (Throwable e) { cacheTransaction.rollback(); throw e; } } default <R> R getOrFetchFromDB(K key, Supplier<R> dbCall, Function<V, R> cacheValueToResult, Function<R, V> dbValueToCacheValue, boolean cacheNullValue, boolean putToCache) { if (putToCache) { return getAndPutInTransaction(key, dbCall, cacheValueToResult, dbValueToCacheValue, cacheNullValue); } else { TbCacheValueWrapper<V> cacheValueWrapper = get(key); if (cacheValueWrapper != null) { var cacheValue = cacheValueWrapper.get(); return cacheValue == null ? null : cacheValueToResult.apply(cacheValue); } return dbCall.get(); } } }
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\TbTransactionalCache.java
1
请在Spring Boot框架中完成以下Java代码
public class TrxItemProcessorExecutorService implements ITrxItemProcessorExecutorService { @Override public ITrxItemProcessorContext createProcessorContext(final Properties ctx, final ITrx trx) { final IParams params = null; return createProcessorContext(ctx, trx, params); } @Override public ITrxItemProcessorContext createProcessorContext(final Properties ctx, final ITrx trx, final IParams params) { final TrxItemProcessorContext processorCtx = new TrxItemProcessorContext(ctx); processorCtx.setTrx(trx); processorCtx.setParams(params); return processorCtx; }
@Override public <IT, RT> ITrxItemProcessorExecutor<IT, RT> createExecutor(final ITrxItemProcessorContext processorCtx, final ITrxItemProcessor<IT, RT> processor) { final ITrxItemExecutorBuilder<IT, RT> builder = createExecutor(); return builder .setContext(processorCtx) .setProcessor(processor) .build(); } @Override public <IT, RT> ITrxItemExecutorBuilder<IT, RT> createExecutor() { return new TrxItemExecutorBuilder<IT, RT>(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessorExecutorService.java
2
请在Spring Boot框架中完成以下Java代码
public ModelAndView index(HttpServletRequest request) { ModelAndView mv = new ModelAndView(); String token = (String) request.getSession().getAttribute(Consts.SESSION_KEY); mv.setViewName("index"); mv.addObject("token", token); return mv; } /** * 跳转到 登录页 * * @param redirect 是否是跳转回来的 */ @GetMapping("/login") public ModelAndView login(Boolean redirect) { ModelAndView mv = new ModelAndView();
if (ObjectUtil.isNotNull(redirect) && ObjectUtil.equal(true, redirect)) { mv.addObject("message", "请先登录!"); } mv.setViewName("login"); return mv; } @GetMapping("/doLogin") public String doLogin(HttpSession session) { session.setAttribute(Consts.SESSION_KEY, IdUtil.fastUUID()); return "redirect:/page/index"; } }
repos\spring-boot-demo-master\demo-session\src\main\java\com\xkcoding\session\controller\PageController.java
2
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() {
return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Java代码
byte[] getPayload() { return this.payload; } @Override public String toString() { return new String(this.payload); } void write(OutputStream outputStream) throws IOException { outputStream.write(0x80 | this.type.code); if (this.payload.length < 126) { outputStream.write(this.payload.length & 0x7F); } else { outputStream.write(0x7E); outputStream.write(this.payload.length >> 8 & 0xFF); outputStream.write(this.payload.length & 0xFF); } outputStream.write(this.payload); outputStream.flush(); } static Frame read(ConnectionInputStream inputStream) throws IOException { int firstByte = inputStream.checkedRead(); Assert.state((firstByte & 0x80) != 0, "Fragmented frames are not supported"); int maskAndLength = inputStream.checkedRead(); boolean hasMask = (maskAndLength & 0x80) != 0; int length = (maskAndLength & 0x7F); Assert.state(length != 127, "Large frames are not supported"); if (length == 126) { length = ((inputStream.checkedRead()) << 8 | inputStream.checkedRead()); } byte[] mask = new byte[4]; if (hasMask) { inputStream.readFully(mask, 0, mask.length); } byte[] payload = new byte[length]; inputStream.readFully(payload, 0, length); if (hasMask) { for (int i = 0; i < payload.length; i++) { payload[i] ^= mask[i % 4]; } } return new Frame(Type.forCode(firstByte & 0x0F), payload); } /** * Frame types. */ enum Type { /** * Continuation frame. */ CONTINUATION(0x00), /** * Text frame. */ TEXT(0x01), /** * Binary frame.
*/ BINARY(0x02), /** * Close frame. */ CLOSE(0x08), /** * Ping frame. */ PING(0x09), /** * Pong frame. */ PONG(0x0A); private final int code; Type(int code) { this.code = code; } static Type forCode(int code) { for (Type type : values()) { if (type.code == code) { return type; } } throw new IllegalStateException("Unknown code " + code); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\Frame.java
1
请完成以下Java代码
public java.lang.String getPrintServiceTray() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray); } @Override public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions)); } @Override public boolean isStatus_Print_Job_Instructions() { return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } @Override public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
} @Override public int getUpdatedby_Print_Job_Instructions() { return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions); } @Override public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions) { set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions); } @Override public java.sql.Timestamp getUpdated_Print_Job_Instructions() { return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java
1
请完成以下Java代码
public CarBuilder color(String color) { this.color = color; return this; } public CarBuilder automatic(boolean automatic) { this.automatic = automatic; return this; } public CarBuilder numDoors(int numDoors) { this.numDoors = numDoors; return this; }
public CarBuilder features(String features) { this.features = features; return this; } public Car build() { return new Car(this); } } @Override public String toString() { return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]"; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\Car.java
1
请完成以下Java代码
public void pointcut() { } @Around("pointcut()") public Object retry(ProceedingJoinPoint joinPoint) throws Exception { // 获取注解 Retryable retryable = AnnotationUtils.findAnnotation(getSpecificmethod(joinPoint), Retryable.class); // 声明Callable Callable<Object> task = () -> getTask(joinPoint); // 声明guava retry对象 Retryer<Object> retryer = null; try { retryer = RetryerBuilder.newBuilder() // 指定触发重试的条件 .retryIfResult(Predicates.isNull()) // 指定触发重试的异常 .retryIfExceptionOfType(retryable.exception())// 抛出Exception异常时重试 // 尝试次数 .withStopStrategy(StopStrategies.stopAfterAttempt(retryable.attemptNumber())) // 重调策略 .withWaitStrategy(WaitStrategies.fixedWait(retryable.sleepTime(), retryable.timeUnit()))// 等待300毫秒 // 指定监听器RetryListener .withRetryListener(retryable.retryListener().newInstance()) .build(); } catch (Exception e) { logger.error(e.getMessage(), e); throw e; } try { // 执行方法 return retryer.call(task); } catch (ExecutionException e) { logger.error(e.getMessage(), e); } catch (RetryException e) { logger.error(e.getMessage(), e); } return null; } private Object getTask(ProceedingJoinPoint joinPoint) { // 执行方法,并获取返回值 try { return joinPoint.proceed(); } catch (Throwable throwable) { logger.error(throwable.getMessage(), throwable);
throw new RuntimeException("执行任务异常"); } } private Method getSpecificmethod(ProceedingJoinPoint pjp) { MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // The method may be on an interface, but we need attributes from the // target class. If the target class is null, the method will be // unchanged. Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget()); if (targetClass == null && pjp.getTarget() != null) { targetClass = pjp.getTarget().getClass(); } Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the // original method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); return specificMethod; } }
repos\spring-boot-student-master\spring-boot-student-guava-retrying\src\main\java\com\xiaolyuh\aspect\RetryAspect.java
1
请完成以下Java代码
public void setValueColumnName(String valueTableName, String valueColumnName, int valueDisplayType) { this.valueTableName = valueTableName; this.valueColumnName = valueColumnName; this.valueDisplayType = valueDisplayType; } public void addElement(TableColumnPathElement e) { elements.add(e); } @Override public List<ITableColumnPathElement> getElements() { return Collections.unmodifiableList(this.elements); } @Override public String getValueTableName() { return valueTableName; } @Override public String getValueColumnName() { return valueColumnName; } @Override public int getValueDisplayType() { return valueDisplayType; } @Override public String getKeyTableName() { return keyTableName;
} @Override public String getKeyColumnName() { return keyColumnName; } @Override public int getRecordId() { return recordId; } @Override public String toString() { return "TableColumnPath [valueTableName=" + valueTableName + ", valueColumnName=" + valueColumnName + ", keyTableName=" + keyTableName + ", keyColumnName=" + keyColumnName + ", recordId=" + recordId + ", elements=" + elements + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\model\TableColumnPath.java
1
请完成以下Java代码
public Cookie get(String name) { return cookieMap.get(name); } @Override public boolean containsAll(Collection<?> collection) { for(Object o : collection) { if (!contains(o)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends Cookie> collection) { boolean result = false; for(Cookie cookie : collection) { result|= add(cookie); } return result; } @Override public boolean removeAll(Collection<?> collection) { boolean result = false; for(Object cookie : collection) { result|= remove(cookie); } return result; } @Override public boolean retainAll(Collection<?> collection) { boolean result = false;
Iterator<Map.Entry<String, Cookie>> it = cookieMap.entrySet().iterator(); while(it.hasNext()) { Map.Entry<String, Cookie> e = it.next(); if (!collection.contains(e.getKey()) && !collection.contains(e.getValue())) { it.remove(); result = true; } } return result; } @Override public void clear() { cookieMap.clear(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\CookieCollection.java
1
请完成以下Java代码
public String toString() { return toSqlString(); } public String toSqlString() { String sqlBuilt = this._sqlBuilt; if (sqlBuilt == null) { final String joinTableNameOrAliasIncludingDot = joinTableNameOrAlias != null ? joinTableNameOrAlias + "." : ""; final Evaluatee2 evalCtx = Evaluatees.ofSingleton(CTX_JoinTableNameOrAliasIncludingDot.toStringWithoutMarkers(), joinTableNameOrAliasIncludingDot); sqlBuilt = this._sqlBuilt = sqlExpression.evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Preserve); } return sqlBuilt;
} public String toSqlStringWrappedInBracketsIfNeeded() { final String sql = toSqlString(); if (sql.contains(" ") && !sql.startsWith("(")) { return "(" + sql + ")"; } else { return sql; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\ColumnSql.java
1
请完成以下Java代码
public class CamundaBpmRunCorsProperty { public static final String PREFIX = CamundaBpmRunProperties.PREFIX + ".cors"; public static final String DEFAULT_ORIGINS = "*"; public static final String DEFAULT_HTTP_METHODS = "GET,POST,HEAD,OPTIONS,PUT,DELETE"; // Duplicate the default values of the following CorsFilter properties, // to ensure they are not changed by a (Tomcat) version bump public static final String DEFAULT_PREFLIGHT_MAXAGE = "1800"; public static final String DEFAULT_ALLOWED_HTTP_HEADERS = "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers"; public static final String DEFAULT_EXPOSED_HEADERS = ""; public static final boolean DEFAULT_ALLOW_CREDENTIALS = false; boolean enabled; // CORS properties String allowedOrigins; String allowedHeaders; String exposedHeaders; boolean allowCredentials; String preflightMaxAge; public CamundaBpmRunCorsProperty() { this.allowedOrigins = DEFAULT_ORIGINS; this.allowedHeaders = DEFAULT_ALLOWED_HTTP_HEADERS; this.exposedHeaders = DEFAULT_EXPOSED_HEADERS; this.allowCredentials = DEFAULT_ALLOW_CREDENTIALS; this.preflightMaxAge =DEFAULT_PREFLIGHT_MAXAGE; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getAllowedOrigins() { if(enabled) { return allowedOrigins == null ? DEFAULT_ORIGINS : allowedOrigins; } return null; } public void setAllowedOrigins(String allowedOrigins) { this.allowedOrigins = allowedOrigins; } public boolean getAllowCredentials() { return allowCredentials; }
public void setAllowCredentials(boolean allowCredentials) { this.allowCredentials = allowCredentials; } public String getAllowedHeaders() { return allowedHeaders; } public void setAllowedHeaders(String allowedHeaders) { this.allowedHeaders = allowedHeaders; } public String getExposedHeaders() { return exposedHeaders; } public void setExposedHeaders(String exposedHeaders) { this.exposedHeaders = exposedHeaders; } public String getPreflightMaxAge() { return preflightMaxAge; } public void setPreflightMaxAge(String preflightMaxAge) { this.preflightMaxAge = preflightMaxAge; } @Override public String toString() { return "CamundaBpmRunCorsProperty [" + "enabled=" + enabled + ", allowCredentials=" + allowCredentials + ", allowedOrigins=" + allowedOrigins + ", allowedHeaders=" + allowedHeaders + ", exposedHeaders=" + exposedHeaders + ", preflightMaxAge=" + preflightMaxAge + ']'; } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunCorsProperty.java
1
请完成以下Java代码
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; String username = usernamePasswordToken.getUsername(); if (StringUtils.isEmpty(username)) { throw new AccountException("Null usernames are not allowed by this realm."); } User userByName = userService.findUserByName(username); if (Objects.isNull(userByName)) { throw new UnknownAccountException("No account found for admin [" + username + "]"); } //查询用户的角色和权限存到SimpleAuthenticationInfo中,这样在其它地方 //SecurityUtils.getSubject().getPrincipal()就能拿出用户的所有信息,包括角色和权限 Set<String> roles = roleService.getRolesByUserId(userByName.getUid()); Set<String> perms = permService.getPermsByUserId(userByName.getUid()); userByName.getRoles().addAll(roles); userByName.getPerms().addAll(perms); SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userByName, userByName.getPwd(), getName());
if (userByName.getSalt() != null) { info.setCredentialsSalt(ByteSource.Util.bytes(userByName.getSalt())); } return info; } public static void main(String[] args) { String hashAlgorithmName = "MD5"; String credentials = "123456"; Object salt = "wxKYXuTPST5SG0jMQzVPsg=="; int hashIterations = 100; SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations); System.out.println(simpleHash); } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\shiro\realm\MyShiroRealm.java
1
请完成以下Java代码
public class Result<T> { private int code; private String message; private T data; public Result setCode(ResultCode resultCode) { this.code = resultCode.code(); return this; } public int getCode() { return code; } public String getMessage() { return message; } public Result setMessage(String message) {
this.message = message; return this; } public T getData() { return data; } public Result setData(T data) { this.data = data; return this; } @Override public String toString() { return JSON.toJSONString(this); } }
repos\spring-boot-api-project-seed-master\src\main\java\com\company\project\core\Result.java
1
请完成以下Java代码
public void setC_ConversionType_Default_ID (int C_ConversionType_Default_ID) { if (C_ConversionType_Default_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ConversionType_Default_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ConversionType_Default_ID, Integer.valueOf(C_ConversionType_Default_ID)); } /** Get Kursart (default). @return Kursart (default) */ @Override public int getC_ConversionType_Default_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_Default_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ConversionType getC_ConversionType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class); } @Override public void setC_ConversionType(org.compiere.model.I_C_ConversionType C_ConversionType) { set_ValueFromPO(COLUMNNAME_C_ConversionType_ID, org.compiere.model.I_C_ConversionType.class, C_ConversionType); } /** Set Kursart. @param C_ConversionType_ID Kursart */ @Override public void setC_ConversionType_ID (int C_ConversionType_ID) {
if (C_ConversionType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ConversionType_ID, Integer.valueOf(C_ConversionType_ID)); } /** Get Kursart. @return Kursart */ @Override public int getC_ConversionType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType_Default.java
1
请在Spring Boot框架中完成以下Java代码
public List<Employee> getAllEmployees() { return employeeList; } public Employee getEmployee(int id) { for (Employee emp : employeeList) { if (emp.getId() == id) { return emp; } } throw new EmployeeNotFound(); } public void updateEmployee(Employee employee, int id) { for (Employee emp : employeeList) { if (emp.getId() == id) { emp.setId(employee.getId()); emp.setFirstName(employee.getFirstName()); return; } } throw new EmployeeNotFound();
} public void deleteEmployee(int id) { for (Employee emp : employeeList) { if (emp.getId() == id) { employeeList.remove(emp); return; } } throw new EmployeeNotFound(); } public void addEmployee(Employee employee) { for (Employee emp : employeeList) { if (emp.getId() == employee.getId()) { throw new EmployeeAlreadyExists(); } } employeeList.add(employee); } }
repos\tutorials-master\spring-web-modules\spring-jersey\src\main\java\com\baeldung\server\repository\EmployeeRepositoryImpl.java
2
请完成以下Java代码
public void setA_Period_7 (BigDecimal A_Period_7) { set_Value (COLUMNNAME_A_Period_7, A_Period_7); } /** Get A_Period_7. @return A_Period_7 */ public BigDecimal getA_Period_7 () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_7); if (bd == null) return Env.ZERO; return bd; } /** Set A_Period_8. @param A_Period_8 A_Period_8 */ public void setA_Period_8 (BigDecimal A_Period_8) { set_Value (COLUMNNAME_A_Period_8, A_Period_8); } /** Get A_Period_8. @return A_Period_8 */ public BigDecimal getA_Period_8 () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_8); if (bd == null) return Env.ZERO; return bd; } /** Set A_Period_9. @param A_Period_9 A_Period_9 */ public void setA_Period_9 (BigDecimal A_Period_9) { set_Value (COLUMNNAME_A_Period_9, A_Period_9);
} /** Get A_Period_9. @return A_Period_9 */ public BigDecimal getA_Period_9 () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_9); if (bd == null) return Env.ZERO; return bd; } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Spread.java
1
请完成以下Java代码
public <CollectedType, ParentModelType> IQueryBuilder<CollectedType> andCollect(final ModelColumn<ParentModelType, CollectedType> column) { return andCollect(column.getColumnName(), column.getColumnModelType()); } @Override public <CollectedBaseType, CollectedType extends CollectedBaseType, ParentModelType> IQueryBuilder<CollectedType> andCollect( @NonNull final ModelColumn<ParentModelType, CollectedBaseType> column, @NonNull final Class<CollectedType> collectedType) { return andCollect(column.getColumnName(), collectedType); } @Override public <CollectedType> IQueryBuilder<CollectedType> andCollect( @NonNull final String columnName, @NonNull Class<CollectedType> collectedType) { final IQuery<T> query = create(); String tableName = InterfaceWrapperHelper.getTableNameOrNull(collectedType); Check.assumeNotEmpty(tableName, "TableName not found for column={} and collectedType={}", columnName, collectedType); final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName); return new QueryBuilder<>(collectedType, null) // tableName=null .setContext(ctx, trxName) .addInSubQueryFilter(keyColumnName, columnName, query); } @Override public <ChildType> IQueryBuilder<ChildType> andCollectChildren( @NonNull final String linkColumnNameInChildTable, @NonNull final Class<ChildType> childType) { final String thisIDColumnName = getKeyColumnName(); final IQuery<T> thisQuery = create(); return new QueryBuilder<>(childType, null) // tableName=null .setContext(ctx, trxName) .addInSubQueryFilter(linkColumnNameInChildTable, thisIDColumnName, thisQuery); } @Override public IQueryBuilder<T> setJoinOr() { filters.setJoinOr(); return this; }
@Override public IQueryBuilder<T> setJoinAnd() { filters.setJoinAnd(); return this; } @Override public <TargetModelType> QueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(final ModelColumn<T, TargetModelType> column) { return aggregateOnColumn(column.getColumnName(), column.getColumnModelType()); } @Override public <TargetModelType> QueryAggregateBuilder<T, TargetModelType> aggregateOnColumn(final String collectOnColumnName, final Class<TargetModelType> targetModelType) { return new QueryAggregateBuilder<>( this, collectOnColumnName, targetModelType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<List<Employee>> getEmployeeByNameAndBeginContactNumber(@PathVariable final String name, @MatrixVariable final String beginContactNumber) { final List<Employee> employeesList = new ArrayList<>(); for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) { final Employee employee = employeeEntry.getValue(); if (employee.getName().equalsIgnoreCase(name) && employee.getContactNumber().startsWith(beginContactNumber)) { employeesList.add(employee); } } return new ResponseEntity<>(employeesList, HttpStatus.OK); } @RequestMapping(value = "/employeesContacts/{contactNumber}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<List<Employee>> getEmployeeByContactNumber(@MatrixVariable(required = true) final String contactNumber) { final List<Employee> employeesList = new ArrayList<>(); for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) { final Employee employee = employeeEntry.getValue(); if (employee.getContactNumber().equalsIgnoreCase(contactNumber)) { employeesList.add(employee); } } return new ResponseEntity<>(employeesList, HttpStatus.OK); } @RequestMapping(value = "employeeData/{employee}", method = RequestMethod.GET) @ResponseBody
public ResponseEntity<Map<String, String>> getEmployeeData(@MatrixVariable final Map<String, String> matrixVars) { return new ResponseEntity<>(matrixVars, HttpStatus.OK); } @RequestMapping(value = "employeeArea/{workingArea}", method = RequestMethod.GET) @ResponseBody public ResponseEntity<List<Employee>> getEmployeeByWorkingArea(@MatrixVariable final Map<String, List<String>> matrixVars) { final List<Employee> employeesList = new ArrayList<>(); final Collection<String> workingArea = matrixVars.get("workingArea"); for (final Map.Entry<Long, Employee> employeeEntry : employeeMap.entrySet()) { final Employee employee = employeeEntry.getValue(); for (final String area : workingArea) { if (employee.getWorkingArea().equalsIgnoreCase(area)) { employeesList.add(employee); break; } } } return new ResponseEntity<>(employeesList, HttpStatus.OK); } }
repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\matrix\controller\EmployeeController.java
2
请完成以下Java代码
private GridController createGridController(GridTab tab, int width, int height) { final GridController gc = new GridController(); gc.initGrid(tab, true, // onlyMultiRow windowNo, null, // APanel null); // GridWindow if (width > 0 && height > 0) { gc.setPreferredSize(new Dimension(width, height)); } // tab.addPropertyChangeListener(this); m_mapVTables.put(tab.getAD_Tab_ID(), gc.getTable()); return gc; } private void vtableAutoSizeAll() {
for (VTable t : m_mapVTables.values()) { t.autoSize(true); } } /** Map AD_Tab_ID -> VTable */ private Map<Integer, VTable> m_mapVTables = new HashMap<>(); @Override public void dispose() { if (frame != null) { frame.dispose(); } frame = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\form\swing\OrderOverview.java
1
请完成以下Java代码
public @Nullable ClassLoaderFile getFile(@Nullable String name) { return this.filesByName.get(name); } /** * Returns a set of all file entries across all source directories for efficient * iteration. * @return a set of all file entries * @since 4.0.0 */ public Set<Entry<String, ClassLoaderFile>> getFileEntries() { return Collections.unmodifiableSet(this.filesByName.entrySet()); } /** * An individual source directory that is being managed by the collection. */ public static class SourceDirectory implements Serializable { @Serial private static final long serialVersionUID = 1; private final String name; private final Map<String, ClassLoaderFile> files = new LinkedHashMap<>(); SourceDirectory(String name) { this.name = name; } public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() { return this.files.entrySet(); } protected final void add(String name, ClassLoaderFile file) { this.files.put(name, file); } protected final void remove(String name) { this.files.remove(name); }
protected final @Nullable ClassLoaderFile get(String name) { return this.files.get(name); } /** * Return the name of the source directory. * @return the name of the source directory */ public String getName() { return this.name; } /** * Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are * contained in this source directory. * @return the files contained in the source directory */ public Collection<ClassLoaderFile> getFiles() { return Collections.unmodifiableCollection(this.files.values()); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java
1
请完成以下Java代码
public String getId() { return this.id; } @Override public int getFieldSize() { // TODO return 0; } @Override public String getFieldNameAt(int index) { // TODO return null; }
@Override public Class<?> getFieldTypeAt(int index) { // TODO return null; } @Override public Class<?> getFieldParameterTypeAt(int index) { // TODO return null; } @Override public StructureInstance createInstance() { return new FieldBaseStructureInstance(this); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\data\ClassStructureDefinition.java
1
请完成以下Java代码
public class ArrayStack { // 数组 private int elementCount; // 栈中元素个数 private String[] items; //栈的大小 private int size; // 初始化数组,申请一个大小为n的数组空间 public ArrayStack(int size) { this.items = new String[size]; this.size = size; this.elementCount = 0; } // 入栈操作 public boolean push(String item) { // 数组空间不够了,直接返回false,入栈失败。 if (elementCount == size) { return false; } // 将item放到下标为count的位置,并且count加一 items[elementCount] = item;
++elementCount; return true; } // 出栈操作 public String pop() { // 栈为空,则直接返回null if (elementCount == 0) { return null; } // 返回下标为count-1的数组元素,并且栈中元素个数count减一 String tmp = items[elementCount - 1]; --elementCount; return tmp; } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ArrayStack.java
1
请完成以下Java代码
public class FactAcctBL implements IFactAcctBL { private final IFactAcctDAO factAcctDAO = Services.get(IFactAcctDAO.class); private final IAccountDAO accountDAO = Services.get(IAccountDAO.class); @Override public Account getAccount(@NonNull final I_Fact_Acct factAcct) { final AccountDimension accountDimension = IFactAcctBL.extractAccountDimension(factAcct); @NonNull final AccountId accountId = accountDAO.getOrCreateOutOfTrx(accountDimension); return Account.ofId(accountId).withAccountConceptualName(FactAcctDAO.extractAccountConceptualName(factAcct)); } @Override public Optional<Money> getAcctBalance(@NonNull final List<FactAcctQuery> queries) { final List<I_Fact_Acct> factLines = factAcctDAO.list(queries); if (factLines.isEmpty()) { return Optional.empty(); } final AcctSchemaId acctSchemaId = factLines.stream() .map(factLine -> AcctSchemaId.ofRepoId(factLine.getC_AcctSchema_ID())) .distinct() .collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Mixing multiple Accounting Schemas when summing amounts is not allowed")));
final CurrencyId acctCurrencyId = Services.get(IAcctSchemaBL.class).getAcctCurrencyId(acctSchemaId); final BigDecimal acctBalanceBD = factLines.stream() .map(factLine -> factLine.getAmtAcctDr().subtract(factLine.getAmtAcctCr())) .reduce(BigDecimal::add) .orElse(BigDecimal.ZERO); return Optional.of(Money.of(acctBalanceBD, acctCurrencyId)); } @Override public Stream<I_Fact_Acct> stream(@NonNull final FactAcctQuery query) { return factAcctDAO.stream(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\acct\api\impl\FactAcctBL.java
1
请在Spring Boot框架中完成以下Java代码
class LoginRedirectSecurityConfig { private static final String LOGIN_USER = "/loginUser"; @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user") .password(encoder().encode("user")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.addFilterAfter(new LoginPageFilter(), UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers(LOGIN_USER).permitAll() .requestMatchers("/user*").hasRole("USER")) .formLogin(httpSecurityFormLoginConfigurer ->
httpSecurityFormLoginConfigurer.loginPage(LOGIN_USER) .loginProcessingUrl("/user_login") .failureUrl("/loginUser?error=loginError") .defaultSuccessUrl("/userMainPage").permitAll()) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer .logoutUrl("/user_logout") .logoutSuccessUrl(LOGIN_USER) .deleteCookies("JSESSIONID")) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public static PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\loginredirect\LoginRedirectSecurityConfig.java
2
请完成以下Java代码
public void setC_Flatrate_Transition(final de.metas.contracts.model.I_C_Flatrate_Transition C_Flatrate_Transition) { set_ValueFromPO(COLUMNNAME_C_Flatrate_Transition_ID, de.metas.contracts.model.I_C_Flatrate_Transition.class, C_Flatrate_Transition); } @Override public void setC_Flatrate_Transition_ID (final int C_Flatrate_Transition_ID) { if (C_Flatrate_Transition_ID < 1) set_Value (COLUMNNAME_C_Flatrate_Transition_ID, null); else set_Value (COLUMNNAME_C_Flatrate_Transition_ID, C_Flatrate_Transition_ID); } @Override public int getC_Flatrate_Transition_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_Transition_ID); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Product_Category_Matching_ID (final int M_Product_Category_Matching_ID) { if (M_Product_Category_Matching_ID < 1) set_Value (COLUMNNAME_M_Product_Category_Matching_ID, null); else set_Value (COLUMNNAME_M_Product_Category_Matching_ID, M_Product_Category_Matching_ID); } @Override public int getM_Product_Category_Matching_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null);
else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyPerDelivery (final BigDecimal QtyPerDelivery) { set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery); } @Override public BigDecimal getQtyPerDelivery() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java
1
请完成以下Java代码
public class GetExecutionVariableInstanceCmd implements Command<VariableInstance>, Serializable { private static final long serialVersionUID = 1L; protected String executionId; protected String variableName; protected boolean isLocal; public GetExecutionVariableInstanceCmd(String executionId, String variableName, boolean isLocal) { this.executionId = executionId; this.variableName = variableName; this.isLocal = isLocal; } @Override public VariableInstance execute(CommandContext commandContext) { if (executionId == null) { throw new ActivitiIllegalArgumentException("executionId is null"); } if (variableName == null) { throw new ActivitiIllegalArgumentException("variableName is null"); } ExecutionEntity execution = commandContext.getExecutionEntityManager().findById(executionId); if (execution == null) { throw new ActivitiObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); } VariableInstance variableEntity = getVariable(execution, commandContext);
if (variableEntity != null) { variableEntity.getValue(); } return variableEntity; } protected VariableInstance getVariable(ExecutionEntity execution, CommandContext commandContext) { VariableInstance variableEntity = null; if (isLocal) { variableEntity = execution.getVariableInstanceLocal(variableName, false); } else { variableEntity = execution.getVariableInstance(variableName, false); } return variableEntity; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetExecutionVariableInstanceCmd.java
1
请完成以下Java代码
public boolean addTU(final I_M_HU tuHU) { if (!isMatchTU(tuHU)) { return false; } if (!luItemStorage.requestNewHU()) { return false; } huTrxBL.setParentHU(huContext, luItem, tuHU); return true; } /** * @return {@code true} if the given {@code tuHU} fits to this instance's wrapped item. */ public boolean isMatchTU(final I_M_HU tuHU) { // // Check if TU's M_HU_PI_ID is accepted if (requiredTU_HU_PI_ID > 0)
{ final int tuPIId = Services.get(IHandlingUnitsBL.class).getPIVersion(tuHU).getM_HU_PI_ID(); if (tuPIId != requiredTU_HU_PI_ID) { return false; } } // // Check if TU's BPartner is accepted if (requiredBPartnerId != null) { final BPartnerId tuBPartnerId = BPartnerId.ofRepoIdOrNull(tuHU.getC_BPartner_ID()); if (!BPartnerId.equals(tuBPartnerId, requiredBPartnerId)) { return false; } } // // Default: accept return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\LULoaderItemInstance.java
1
请在Spring Boot框架中完成以下Java代码
public int updateShowStatus(List<Long> ids, Integer showStatus) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setShowStatus(showStatus); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.createCriteria().andIdIn(ids); return productCategoryMapper.updateByExampleSelective(productCategory, example); } @Override public List<PmsProductCategoryWithChildrenItem> listWithChildren() { return productCategoryDao.listWithChildren(); } /** * 根据分类的parentId设置分类的level
*/ private void setCategoryLevel(PmsProductCategory productCategory) { //没有父分类时为一级分类 if (productCategory.getParentId() == 0) { productCategory.setLevel(0); } else { //有父分类时选择根据父分类level设置 PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId()); if (parentCategory != null) { productCategory.setLevel(parentCategory.getLevel() + 1); } else { productCategory.setLevel(0); } } } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductCategoryServiceImpl.java
2
请完成以下Java代码
private void processRows(Statement statement, AsyncResultSet resultSet, List<Row> allRows, SettableFuture<List<Row>> resultFuture, Executor executor) { allRows.addAll(loadRows(resultSet)); if (resultSet.hasMorePages()) { ByteBuffer nextPagingState = resultSet.getExecutionInfo().getPagingState(); Statement<?> nextStatement = statement.setPagingState(nextPagingState); TbResultSetFuture resultSetFuture = executeAsyncFunction.apply(nextStatement); Futures.addCallback(resultSetFuture, new FutureCallback<TbResultSet>() { @Override public void onSuccess(@Nullable TbResultSet result) { processRows(nextStatement, result, allRows, resultFuture, executor); } @Override
public void onFailure(Throwable t) { resultFuture.setException(t); } }, executor != null ? executor : MoreExecutors.directExecutor() ); } else { resultFuture.set(allRows); } } List<Row> loadRows(AsyncResultSet resultSet) { return Lists.newArrayList(resultSet.currentPage()); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSet.java
1
请完成以下Java代码
public Builder issuedAt(Instant issuedAt) { this.claim(JwtClaimNames.IAT, issuedAt); return this; } /** * Use this issuer in the resulting {@link Jwt} * @param issuer The issuer to use * @return the {@link Builder} for further configurations */ public Builder issuer(String issuer) { this.claim(JwtClaimNames.ISS, issuer); return this; } /** * Use this not-before timestamp in the resulting {@link Jwt} * @param notBefore The not-before timestamp to use * @return the {@link Builder} for further configurations */ public Builder notBefore(Instant notBefore) { this.claim(JwtClaimNames.NBF, notBefore); return this; } /** * Use this subject in the resulting {@link Jwt} * @param subject The subject to use * @return the {@link Builder} for further configurations */ public Builder subject(String subject) { this.claim(JwtClaimNames.SUB, subject);
return this; } /** * Build the {@link Jwt} * @return The constructed {@link Jwt} */ public Jwt build() { Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT)); Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP)); return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims); } private Instant toInstant(Object timestamp) { if (timestamp != null) { Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant"); } return (Instant) timestamp; } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\Jwt.java
1
请在Spring Boot框架中完成以下Java代码
public String getSpecialConditions() { return specialConditions; } /** * Sets the value of the specialConditions property. * * @param value * allowed object is * {@link String } * */ public void setSpecialConditions(String value) { this.specialConditions = value; } /** * Gets the value of the progressNumberDifference property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getProgressNumberDifference() { return progressNumberDifference; } /** * Sets the value of the progressNumberDifference property. * * @param value * allowed object is * {@link BigInteger } * */ public void setProgressNumberDifference(BigInteger value) { this.progressNumberDifference = value; } /** * Gets the value of the kanbanID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the kanbanID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getKanbanID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getKanbanID() { if (kanbanID == null) { kanbanID = new ArrayList<String>(); }
return this.kanbanID; } /** * The classification of the product/service in free-text form.Gets the value of the classification property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the classification property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassification().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ClassificationType } * * */ public List<ClassificationType> getClassification() { if (classification == null) { classification = new ArrayList<ClassificationType>(); } return this.classification; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalLineItemInformationType.java
2
请在Spring Boot框架中完成以下Java代码
public List<ResourceExportData> exportResources(WidgetTypeDetails widgetTypeDetails, SecurityUser user) throws ThingsboardException { return exportResources(() -> imageService.getUsedImages(widgetTypeDetails), () -> resourceService.getUsedResources(user.getTenantId(), widgetTypeDetails), user); } @Override public void importResources(List<ResourceExportData> resources, SecurityUser user) throws Exception { for (ResourceExportData resourceData : resources) { TbResourceInfo resourceInfo; if (resourceData.getType() == ResourceType.IMAGE) { resourceInfo = tbImageService.importImage(resourceData, true, user); } else { resourceInfo = importResource(resourceData, user); } resourceData.setNewLink(resourceInfo.getLink()); } } private <T> List<ResourceExportData> exportResources(Supplier<Collection<TbResourceInfo>> imagesProcessor, Supplier<Collection<TbResourceInfo>> resourcesProcessor, SecurityUser user) throws ThingsboardException { List<TbResourceInfo> resources = new ArrayList<>(); resources.addAll(imagesProcessor.get()); resources.addAll(resourcesProcessor.get()); for (TbResourceInfo resourceInfo : resources) { accessControlService.checkPermission(user, Resource.TB_RESOURCE, Operation.READ, resourceInfo.getId(), resourceInfo); } return resourceService.exportResources(user.getTenantId(), resources);
} private TbResourceInfo importResource(ResourceExportData resourceData, SecurityUser user) throws ThingsboardException { TbResource resource = resourceService.toResource(user.getTenantId(), resourceData); if (resource.getData() != null) { accessControlService.checkPermission(user, Resource.TB_RESOURCE, Operation.CREATE, null, resource); return save(resource, user); } else { accessControlService.checkPermission(user, Resource.TB_RESOURCE, Operation.READ, resource.getId(), resource); return resource; } } private Comparator<? super LwM2mObject> getComparator(String sortProperty, String sortOrder) { Comparator<LwM2mObject> comparator; if ("name".equals(sortProperty)) { comparator = Comparator.comparing(LwM2mObject::getName); } else { comparator = Comparator.comparingLong(LwM2mObject::getId); } return "DESC".equals(sortOrder) ? comparator.reversed() : comparator; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\resource\DefaultTbResourceService.java
2
请完成以下Java代码
public List<SequenceFlow> getIncomingFlows() { return incomingFlows; } public void setIncomingFlows(List<SequenceFlow> incomingFlows) { this.incomingFlows = incomingFlows; } public List<SequenceFlow> getOutgoingFlows() { return outgoingFlows; } public void setOutgoingFlows(List<SequenceFlow> outgoingFlows) { this.outgoingFlows = outgoingFlows; } public void setValues(FlowNode otherNode) { super.setValues(otherNode); setAsynchronous(otherNode.isAsynchronous());
setNotExclusive(otherNode.isNotExclusive()); setAsynchronousLeave(otherNode.isAsynchronousLeave()); setAsynchronousLeaveNotExclusive(otherNode.isAsynchronousLeaveNotExclusive()); if (otherNode.getIncomingFlows() != null) { setIncomingFlows(otherNode.getIncomingFlows() .stream() .map(SequenceFlow::clone) .collect(Collectors.toList())); } if (otherNode.getOutgoingFlows() != null) { setOutgoingFlows(otherNode.getOutgoingFlows() .stream() .map(SequenceFlow::clone) .collect(Collectors.toList())); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowNode.java
1
请完成以下Java代码
public void setEmail(final String username) { email = username; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true;
if (obj == null) return false; if (getClass() != obj.getClass()) return false; final User user = (User) obj; return email.equals(user.email); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public Object lIndex(String key, long index) { return redisTemplate.opsForList().index(key, index); } @Override public Long lPush(String key, Object value) { return redisTemplate.opsForList().rightPush(key, value); } @Override public Long lPush(String key, Object value, long time) { Long index = redisTemplate.opsForList().rightPush(key, value); expire(key, time); return index; } @Override
public Long lPushAll(String key, Object... values) { return redisTemplate.opsForList().rightPushAll(key, values); } @Override public Long lPushAll(String key, Long time, Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); expire(key, time); return count; } @Override public Long lRemove(String key, long count, Object value) { return redisTemplate.opsForList().remove(key, count, value); } }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\service\impl\RedisServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
NettyDriverMongoClientSettingsBuilderCustomizer nettyDriverCustomizer( ObjectProvider<MongoClientSettings> settings) { return new NettyDriverMongoClientSettingsBuilderCustomizer(settings); } } /** * {@link MongoClientSettingsBuilderCustomizer} to apply Mongo client settings. */ static final class NettyDriverMongoClientSettingsBuilderCustomizer implements MongoClientSettingsBuilderCustomizer, DisposableBean { private final ObjectProvider<MongoClientSettings> settings; private volatile @Nullable EventLoopGroup eventLoopGroup; NettyDriverMongoClientSettingsBuilderCustomizer(ObjectProvider<MongoClientSettings> settings) { this.settings = settings; } @Override public void customize(Builder builder) { if (!isCustomTransportConfiguration(this.settings.getIfAvailable())) { EventLoopGroup eventLoopGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); this.eventLoopGroup = eventLoopGroup; builder.transportSettings(TransportSettings.nettyBuilder().eventLoopGroup(eventLoopGroup).build()); } }
@Override public void destroy() { EventLoopGroup eventLoopGroup = this.eventLoopGroup; if (eventLoopGroup != null) { eventLoopGroup.shutdownGracefully().awaitUninterruptibly(); this.eventLoopGroup = null; } } private boolean isCustomTransportConfiguration(@Nullable MongoClientSettings settings) { return settings != null && settings.getTransportSettings() != null; } } }
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\MongoReactiveAutoConfiguration.java
2
请完成以下Java代码
public class ExecutorRouteFailover extends ExecutorRouter { @Override public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) { StringBuffer beatResultSB = new StringBuffer(); for (String address : addressList) { // beat ReturnT<String> beatResult = null; try { ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(address); beatResult = executorBiz.beat(); } catch (Exception e) { logger.error(e.getMessage(), e); beatResult = new ReturnT<String>(ReturnT.FAIL_CODE, ""+e ); } beatResultSB.append( (beatResultSB.length()>0)?"<br><br>":"") .append(I18nUtil.getString("jobconf_beat") + ":") .append("<br>address:").append(address)
.append("<br>code:").append(beatResult.getCode()) .append("<br>msg:").append(beatResult.getMsg()); // beat success if (beatResult.getCode() == ReturnT.SUCCESS_CODE) { beatResult.setMsg(beatResultSB.toString()); beatResult.setContent(address); return beatResult; } } return new ReturnT<String>(ReturnT.FAIL_CODE, beatResultSB.toString()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteFailover.java
1
请完成以下Java代码
public RegisteredClient getRegisteredClient() { return get(RegisteredClient.class); } /** * Returns the {@link OAuth2AuthorizationRequest authorization request}. * @return the {@link OAuth2AuthorizationRequest} */ @Nullable public OAuth2AuthorizationRequest getAuthorizationRequest() { return get(OAuth2AuthorizationRequest.class); } /** * Returns the {@link OAuth2AuthorizationConsent authorization consent}. * @return the {@link OAuth2AuthorizationConsent} */ @Nullable public OAuth2AuthorizationConsent getAuthorizationConsent() { return get(OAuth2AuthorizationConsent.class); } /** * Constructs a new {@link Builder} with the provided * {@link OAuth2AuthorizationCodeRequestAuthenticationToken}. * @param authentication the {@link OAuth2AuthorizationCodeRequestAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2AuthorizationCodeRequestAuthenticationContext, Builder> { private Builder(OAuth2AuthorizationCodeRequestAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration */ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); }
/** * Sets the {@link OAuth2AuthorizationRequest authorization request}. * @param authorizationRequest the {@link OAuth2AuthorizationRequest} * @return the {@link Builder} for further configuration */ public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) { return put(OAuth2AuthorizationRequest.class, authorizationRequest); } /** * Sets the {@link OAuth2AuthorizationConsent authorization consent}. * @param authorizationConsent the {@link OAuth2AuthorizationConsent} * @return the {@link Builder} for further configuration */ public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) { return put(OAuth2AuthorizationConsent.class, authorizationConsent); } /** * Builds a new {@link OAuth2AuthorizationCodeRequestAuthenticationContext}. * @return the {@link OAuth2AuthorizationCodeRequestAuthenticationContext} */ @Override public OAuth2AuthorizationCodeRequestAuthenticationContext build() { Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); return new OAuth2AuthorizationCodeRequestAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationContext.java
1
请完成以下Java代码
public void setSequence (BigDecimal Sequence) { set_Value (COLUMNNAME_Sequence, Sequence); } /** Get Sequence. @return Sequence */ public BigDecimal getSequence () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence); if (bd == null) return Env.ZERO; return bd; } /** Set Web Menu. @param U_WebMenu_ID Web Menu */ public void setU_WebMenu_ID (int U_WebMenu_ID)
{ if (U_WebMenu_ID < 1) set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null); else set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID)); } /** Get Web Menu. @return Web Menu */ public int getU_WebMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_WebMenu.java
1
请完成以下Java代码
public Result beforeHU(final IMutable<I_M_HU> hu) { return defaultResult; } @Override public Result afterHU(final I_M_HU hu) { return defaultResult; } @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return defaultResult; } @Override public Result afterHUItem(final I_M_HU_Item item)
{ return defaultResult; } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return defaultResult; } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return defaultResult; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\NullHUIteratorListener.java
1
请完成以下Java代码
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException { final String targetUrl = determineTargetUrl(authentication); if (response.isCommitted()) { logger.debug("Response has already been committed. Unable to redirect to " + targetUrl); return; } redirectStrategy.sendRedirect(request, response, targetUrl); } protected String determineTargetUrl(final Authentication authentication) { Map<String, String> roleTargetUrlMap = new HashMap<>(); roleTargetUrlMap.put("ROLE_USER", "/homepage.html"); roleTargetUrlMap.put("ROLE_ADMIN", "/console.html"); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { String authorityName = grantedAuthority.getAuthority(); if(roleTargetUrlMap.containsKey(authorityName)) { return roleTargetUrlMap.get(authorityName); } } throw new IllegalStateException();
} /** * Removes temporary authentication-related data which may have been stored in the session * during the authentication process. */ protected final void clearAuthenticationAttributes(final HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue private Long id; private String name; public Book() { super(); } public Book(Long id, String name) { super(); this.id = id; this.name = name; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\springboothibernate\application\models\Book.java
2
请完成以下Java代码
public POSPayment changingStatusFromRemote(@NonNull final POSPaymentProcessResponse response) { paymentMethod.assertCard(); // NOTE: when changing status from remote we cannot validate if the status transition is OK // we have to accept what we have on remote. return toBuilder() .paymentProcessingStatus(response.getStatus()) .cardProcessingDetails(POSPaymentCardProcessingDetails.builder() .config(response.getConfig()) .transactionId(response.getTransactionId()) .summary(response.getSummary()) .cardReader(response.getCardReader()) .build()) .build(); } public POSPayment withPaymentReceipt(@Nullable final PaymentId paymentReceiptId) { if (PaymentId.equals(this.paymentReceiptId, paymentReceiptId)) { return this; } if (paymentReceiptId != null && !paymentProcessingStatus.isSuccessful()) { throw new AdempiereException("Cannot set a payment receipt if status is not successful"); } if (this.paymentReceiptId != null && paymentReceiptId != null) { throw new AdempiereException("Changing the payment receipt is not allowed"); } return toBuilder().paymentReceiptId(paymentReceiptId).build(); }
public POSPayment withCashTenderedAmount(@NonNull final BigDecimal cashTenderedAmountBD) { paymentMethod.assertCash(); Check.assume(cashTenderedAmountBD.signum() > 0, "Cash Tendered Amount must be positive"); final Money cashTenderedAmountNew = Money.of(cashTenderedAmountBD, this.cashTenderedAmount.getCurrencyId()); if (Money.equals(this.cashTenderedAmount, cashTenderedAmountNew)) { return this; } return toBuilder().cashTenderedAmount(cashTenderedAmountNew).build(); } public POSPayment withCardPayAmount(@NonNull final BigDecimal cardPayAmountBD) { paymentMethod.assertCard(); Check.assume(cardPayAmountBD.signum() > 0, "Card Pay Amount must be positive"); final Money amountNew = Money.of(cardPayAmountBD, this.amount.getCurrencyId()); if (Money.equals(this.amount, amountNew)) { return this; } return toBuilder().amount(amountNew).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPayment.java
1
请完成以下Java代码
protected final IHandlingUnitsDAO getHandlingUnitsDAO() { return handlingUnitsDAO; } @Override public void updateHUTrxAttribute(@NonNull final MutableHUTransactionAttribute huTrxAttribute, @NonNull final IAttributeValue fromAttributeValue) { assertNotDisposed(); // // Set M_HU final I_M_HU hu = getM_HU(); huTrxAttribute.setReferencedObject(hu); // // Set HU related fields // // NOTE: we assume given "attributeValue" was created by "toAttributeValue" if (fromAttributeValue instanceof HUAttributeValue) { final HUAttributeValue attributeValueImpl = (HUAttributeValue)fromAttributeValue; final I_M_HU_PI_Attribute piAttribute = attributeValueImpl.getM_HU_PI_Attribute(); huTrxAttribute.setPiAttributeId(piAttribute != null ? HuPackingInstructionsAttributeId.ofRepoId(piAttribute.getM_HU_PI_Attribute_ID()) : null); final I_M_HU_Attribute huAttribute = attributeValueImpl.getM_HU_Attribute(); huTrxAttribute.setHuAttribute(huAttribute); } else { throw new AdempiereException("Attribute value " + fromAttributeValue + " is not valid for this storage (" + this + ")"); } } @Override
public final UOMType getQtyUOMTypeOrNull() { final I_M_HU hu = getM_HU(); final IHUStorageDAO huStorageDAO = getHUStorageDAO(); return huStorageDAO.getC_UOMTypeOrNull(hu); } @Override public final BigDecimal getStorageQtyOrZERO() { final IHUStorageFactory huStorageFactory = getAttributeStorageFactory().getHUStorageFactory(); final IHUStorage storage = huStorageFactory.getStorage(getM_HU()); final BigDecimal fullStorageQty = storage.getQtyForProductStorages().toBigDecimal(); return fullStorageQty; } @Override public final boolean isVirtual() { return handlingUnitsBL.isVirtual(getM_HU()); } @Override public Optional<WarehouseId> getWarehouseId() { final I_M_HU hu = getM_HU(); if (hu == null) { return Optional.empty(); } final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu); return Optional.ofNullable(warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractHUAttributeStorage.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() {
return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getCallbackIds() { return callbackIds; } public void setCallbackIds(Set<String> callbackIds) { this.callbackIds = callbackIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceQueryRequest.java
2
请完成以下Java代码
public class Post { private int userId; private String title; private String body; public Post() { } public Post(int userId, String title, String body) { this.userId = userId; this.title = title; this.body = body; } public int getUserId() { return userId; }
public void setUserId(int userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } }
repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\camel\postrequest\Post.java
1
请完成以下Java代码
public void invalidateDocument() { invalidateDocument = true; } public void invalidateAllIncludedDocuments(@NonNull final String includedTableName) { getIncludedDocument(includedTableName).invalidateAll(); } public void addIncludedDocument(@NonNull final String includedTableName, final int includedRecordId) { getIncludedDocument(includedTableName).addRecordId(includedRecordId); } private IncludedDocumentToInvalidate getIncludedDocument(@NonNull final String includedTableName) { return includedDocumentsByTableName.computeIfAbsent(includedTableName, IncludedDocumentToInvalidate::new); } public String getTableName() { return recordRef.getTableName(); } public DocumentId getDocumentId() { return DocumentId.of(recordRef.getRecord_ID()); }
public Collection<IncludedDocumentToInvalidate> getIncludedDocuments() { return includedDocumentsByTableName.values(); } DocumentToInvalidate combine(@NonNull final DocumentToInvalidate other) { Check.assumeEquals(this.recordRef, other.recordRef, "recordRef"); this.invalidateDocument = this.invalidateDocument || other.invalidateDocument; for (final Map.Entry<String, IncludedDocumentToInvalidate> e : other.includedDocumentsByTableName.entrySet()) { this.includedDocumentsByTableName.merge( e.getKey(), e.getValue(), (item1, item2) -> item1.combine(item2)); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentToInvalidate.java
1
请完成以下Java代码
private UOMConversionsMap retrieveProductConversions(@NonNull final ProductId productId) { final UomId productStockingUomId = Services.get(IProductBL.class).getStockUOMId(productId); final ImmutableList<UOMConversionRate> rates = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_UOM_Conversion.class) .addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_M_Product_ID, productId) .addOnlyActiveRecordsFilter() .create() .stream() .map(UOMConversionDAO::toUOMConversionOrNull) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); return buildUOMConversionsMap(productId, productStockingUomId, rates); }
@NonNull private static UOMConversionsMap buildUOMConversionsMap( @NonNull final ProductId productId, @NonNull final UomId productStockingUomId, @NonNull final ImmutableList<UOMConversionRate> rates) { return UOMConversionsMap.builder() .productId(productId) .hasRatesForNonStockingUOMs(!rates.isEmpty()) .rates(ImmutableList.<UOMConversionRate>builder() .add(UOMConversionRate.one(productStockingUomId)) // default conversion .addAll(rates) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMConversionDAO.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<?> saveUserProfile(UserPrincipal userPrincipal, UserProfile userProfileForm){ Optional<User> userDto = userRepository.findById(userPrincipal.getId()); User user = userDto.orElse(null); if(user !=null && user.getPhone().equals(userProfileForm.getPhone()) && userRepository.existsByPhone(userProfileForm.getPhone())) return new ResponseEntity<>( new ApiResponse(false, "Please, you may show phone number for register!, Or show other number"), HttpStatus.BAD_REQUEST); if(user != null && user.getEmail() !=null && !user.getEmail().equals(userProfileForm.getEmail()) && userRepository.existsByEmail(userProfileForm.getEmail())) return new ResponseEntity<>( new ApiResponse (false, "Please email you may register, or different one."), HttpStatus.BAD_REQUEST); if (user != null) { user.setSurname(userProfileForm.getSurname()); user.setName(userProfileForm.getName()); user.setLastname(userProfileForm.getLastname()); user.setEmail(userProfileForm.getEmail()); user.setPhone(userProfileForm.getPhone()); userRepository.save(user); return new ResponseEntity<>(new ApiResponse(true, "change already saved"), HttpStatus.OK); } else { return new ResponseEntity<>( new ApiResponse(false, "Oops, issues! Please update page!"), HttpStatus.BAD_REQUEST);
} } public Boolean saveCity(UserPrincipal userPrincipal, String city){ Optional<User> userDto = userRepository.findById(userPrincipal.getId()); User user = userDto.orElse(null); if(user!= null) { user.setCity(city); userRepository.save(user); return true; } else{ return false; } } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\UserService.java
2
请完成以下Java代码
public Shengmu getShengmu() { return shengmu; } /** * 获取韵母 * @return */ public Yunmu getYunmu() { return yunmu; } /** * 获取声调 * @return */ public int getTone() { return tone; } /** * 获取带音调的拼音 * @return */ public String getPinyinWithToneMark() { return pinyinWithToneMark; } /** * 获取纯字母的拼音 * @return */ public String getPinyinWithoutTone() { return pinyinWithoutTone; } /** * 获取输入法头 * @return */
public String getHeadString() { return head.toString(); } /** * 获取输入法头 * @return */ public Head getHead() { return head; } /** * 获取首字母 * @return */ public char getFirstChar() { return firstChar; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\Pinyin.java
1
请在Spring Boot框架中完成以下Java代码
WebClientCustomizer webClientHttpConnectorCustomizer(ClientHttpConnector clientHttpConnector) { return (builder) -> builder.clientConnector(clientHttpConnector); } @Bean @ConditionalOnMissingBean(WebClientSsl.class) @ConditionalOnBean(SslBundles.class) AutoConfiguredWebClientSsl webClientSsl(ResourceLoader resourceLoader, ObjectProvider<ClientHttpConnectorBuilder<?>> clientHttpConnectorBuilder, ObjectProvider<HttpClientSettings> httpClientSettings, SslBundles sslBundles) { return new AutoConfiguredWebClientSsl( clientHttpConnectorBuilder .getIfAvailable(() -> ClientHttpConnectorBuilder.detect(resourceLoader.getClassLoader())), httpClientSettings.getIfAvailable(HttpClientSettings::defaults), sslBundles); }
@Configuration(proxyBeanMethods = false) @ConditionalOnBean(CodecCustomizer.class) protected static class WebClientCodecsConfiguration { @Bean @ConditionalOnMissingBean @Order(0) WebClientCodecCustomizer exchangeStrategiesCustomizer(ObjectProvider<CodecCustomizer> codecCustomizers) { return new WebClientCodecCustomizer(codecCustomizers.orderedStream().toList()); } } }
repos\spring-boot-4.0.1\module\spring-boot-webclient\src\main\java\org\springframework\boot\webclient\autoconfigure\WebClientAutoConfiguration.java
2
请完成以下Java代码
public List<I_C_ReferenceNo_Type_Table> retrieveTableAssignments(I_C_ReferenceNo_Type type) { throw new UnsupportedOperationException(); } @Override public List<I_C_ReferenceNo_Doc> retrieveAllDocAssignments(Properties ctx, int referenceNoTypeId, int tableId, int recordId, String trxName) { throw new UnsupportedOperationException(); } @Override public List<I_C_ReferenceNo> retrieveReferenceNos(final Object model, final I_C_ReferenceNo_Type type) { // get all I_C_ReferenceNo_Docs that references 'model' final List<I_C_ReferenceNo_Doc> docs = lookupMap.getRecords(I_C_ReferenceNo_Doc.class, new IPOJOFilter<I_C_ReferenceNo_Doc>() { @Override public boolean accept(I_C_ReferenceNo_Doc pojo) { return pojo.getRecord_ID() == InterfaceWrapperHelper.getId(model) && pojo.getAD_Table_ID() == MTable.getTable_ID(InterfaceWrapperHelper.getModelTableName(model)); } }); // add the C_ReferenceNos into a set to avoid duplicates final Set<I_C_ReferenceNo> refNos = new HashSet<>(); for (final I_C_ReferenceNo_Doc doc : docs) { final I_C_ReferenceNo referenceNo = doc.getC_ReferenceNo(); if (referenceNo.getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID()) { refNos.add(referenceNo); } } return new ArrayList<>(refNos);
} @Override protected List<I_C_ReferenceNo_Doc> retrieveRefNoDocByRefNoAndTableName(final I_C_ReferenceNo referenceNo, final String tableName) { return lookupMap.getRecords(I_C_ReferenceNo_Doc.class, new IPOJOFilter<I_C_ReferenceNo_Doc>() { @Override public boolean accept(I_C_ReferenceNo_Doc pojo) { return pojo.getC_ReferenceNo_ID() == referenceNo.getC_ReferenceNo_ID() && pojo.getAD_Table_ID() == MTable.getTable_ID(tableName); } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\PlainReferenceNoDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class WikiDocumentsController { private final WikiDocumentsServiceImpl wikiDocumentsService; private final ChatClient chatClient; private final QuestionAnswerAdvisor questionAnswerAdvisor; public WikiDocumentsController(WikiDocumentsServiceImpl wikiDocumentsService, @Qualifier("openAiChatModel") ChatModel chatModel, QuestionAnswerAdvisor questionAnswerAdvisor) { this.wikiDocumentsService = wikiDocumentsService; this.questionAnswerAdvisor = questionAnswerAdvisor; this.chatClient = ChatClient.builder(chatModel).build(); } @PostMapping public ResponseEntity<Void> saveDocument(@RequestParam("filePath") String filePath) { wikiDocumentsService.saveWikiDocument(filePath); return ResponseEntity.status(201).build();
} @GetMapping public List<WikiDocument> get(@RequestParam("searchText") String searchText) { return wikiDocumentsService.findSimilarDocuments(searchText); } @GetMapping("/search") public String getWikiAnswer(@RequestParam("question") String question) { return chatClient.prompt() .user(question) .advisors(questionAnswerAdvisor) .call() .content(); } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\rag\mongodb\controller\WikiDocumentsController.java
2
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; }
public Integer getInstances() { return instances; } public void setInstances(Integer instances) { this.instances = instances; } public Integer getIncidents() { return incidents; } public void setIncidents(Integer incidents) { this.incidents = incidents; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessDefinitionStatisticsDto.java
1
请在Spring Boot框架中完成以下Java代码
protected Integer getDurableClientTimeout() { return this.durableClientTimeout != null ? this.durableClientTimeout : DEFAULT_DURABLE_CLIENT_TIMEOUT; } protected Boolean getKeepAlive() { return this.keepAlive != null ? this.keepAlive : DEFAULT_KEEP_ALIVE; } protected Boolean getReadyForEvents() { return this.readyForEvents != null ? this.readyForEvents : DEFAULT_READY_FOR_EVENTS; } protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> {
clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive()); clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); } @Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { // @formatter:off http .oauth2AuthorizationServer(Customizer.withDefaults()) .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ); // @formatter:on return http.build(); } public static JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { Set<JWSAlgorithm> jwsAlgs = new HashSet<>(); jwsAlgs.addAll(JWSAlgorithm.Family.RSA); jwsAlgs.addAll(JWSAlgorithm.Family.EC); jwsAlgs.addAll(JWSAlgorithm.Family.HMAC_SHA); ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>(); JWSKeySelector<SecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(jwsAlgs, jwkSource);
jwtProcessor.setJWSKeySelector(jwsKeySelector); // Override the default Nimbus claims set verifier as NimbusJwtDecoder handles it // instead jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> { }); return new NimbusJwtDecoder(jwtProcessor); } @Bean RegisterMissingBeanPostProcessor registerMissingBeanPostProcessor() { RegisterMissingBeanPostProcessor postProcessor = new RegisterMissingBeanPostProcessor(); postProcessor.addBeanDefinition(AuthorizationServerSettings.class, () -> AuthorizationServerSettings.builder().build()); return postProcessor; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\OAuth2AuthorizationServerConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class MultiSourceExAop implements Ordered { private Logger log = LoggerFactory.getLogger(this.getClass()); @Pointcut(value = "@annotation(com.xncoding.pos.common.annotion.DataSource)") private void cut() { } @Around("cut()") public Object around(ProceedingJoinPoint point) throws Throwable { Signature signature = point.getSignature(); MethodSignature methodSignature = null; if (!(signature instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } methodSignature = (MethodSignature) signature; Object target = point.getTarget(); Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes()); DataSource datasource = currentMethod.getAnnotation(DataSource.class); if (datasource != null) { DataSourceContextHolder.setDataSourceType(datasource.name()); log.debug("设置数据源为:" + datasource.name()); } else { DataSourceContextHolder.setDataSourceType(DSEnum.DATA_SOURCE_CORE);
log.debug("设置数据源为:dataSourceCore"); } try { return point.proceed(); } finally { log.debug("清空数据源信息!"); DataSourceContextHolder.clearDataSourceType(); } } /** * aop的顺序要早于spring的事务 */ @Override public int getOrder() { return 1; } }
repos\SpringBootBucket-master\springboot-multisource\src\main\java\com\xncoding\pos\common\aop\MultiSourceExAop.java
2