instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public final class CarrierAdviseProcessService { @NonNull public static final AdMessageKey ONLY_EXACTLY_ONE_SHIPPER_ALLOWED = AdMessageKey.of("MoreThanOneOrNoShipperSelected"); // Services @NonNull private final ShipmentScheduleService shipmentScheduleService; @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); public boolean isSingleShipper(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds) { return getShipperIds(shipmentScheduleIds).size() == 1; } public ImmutableSet<ShipperId> getShipperIds(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds) { return CollectionUtils.extractDistinctElements(shipmentScheduleService.getByIds(shipmentScheduleIds), ShipmentSchedule::getShipperId) .stream() .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public void requestCarrierAdvises(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds, final boolean isIncludeCarrierAdviseManual) { shipmentScheduleService.getByIds(shipmentScheduleIds) .forEach(schedule -> requestCarrierAdvise(schedule, isIncludeCarrierAdviseManual)); } public void requestCarrierAdvises(@NonNull final ShipmentScheduleQuery query) { shipmentScheduleService.getBy(query) .forEach(schedule -> requestCarrierAdvise(schedule, false)); } private void requestCarrierAdvise(@NonNull final ShipmentSchedule shipmentSchedule, final boolean isIncludeCarrierAdviseManual) { trxManager.runInThreadInheritedTrx(() -> { if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(shipmentSchedule, isIncludeCarrierAdviseManual)) { return; } shipmentSchedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Requested); shipmentSchedule.setCarrierProductId(null);
shipmentScheduleService.save(shipmentSchedule); }); } public void updateEligibleShipmentSchedules(@NonNull final CarrierAdviseUpdateRequest request) { shipmentScheduleService.updateByQuery(request.getQuery(), schedule -> updateEligibleShipmentSchedule(schedule, request)); } private void updateEligibleShipmentSchedule(@NonNull final ShipmentSchedule schedule, @NonNull final CarrierAdviseUpdateRequest request) { if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(schedule, request.isIncludeCarrierAdviseManual())) { return; } schedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Manual); schedule.setCarrierProductId(request.getCarrierProductId()); schedule.setCarrierGoodsTypeId(request.getCarrierGoodsTypeId()); schedule.setCarrierServices(request.getCarrierServiceIds()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\CarrierAdviseProcessService.java
2
请完成以下Java代码
public void createBucket(String bucketName) { s3Client.createBucket(request -> request.bucket(bucketName)); } public List<Bucket> listBuckets() { List<Bucket> allBuckets = new ArrayList<>(); String nextToken = null; do { String continuationToken = nextToken; ListBucketsResponse listBucketsResponse = s3Client.listBuckets( request -> request.continuationToken(continuationToken) ); allBuckets.addAll(listBucketsResponse.buckets()); nextToken = listBucketsResponse.continuationToken(); } while (nextToken != null);
return allBuckets; } public void deleteBucket(String bucketName) { try { s3Client.deleteBucket(request -> request.bucket(bucketName)); } catch (S3Exception exception) { if (exception.statusCode() == HttpStatus.SC_CONFLICT) { throw new BucketNotEmptyException(); } throw exception; } } }
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\S3BucketOperationService.java
1
请完成以下Java代码
default SqlOrderByValue getFieldOrderBy(String fieldName) { return getFieldByFieldName(fieldName).getSqlOrderBy(); } default DocumentFilterDescriptorsProvider getFilterDescriptors() { throw new UnsupportedOperationException(); } /** * @return registered document filter to SQL converters */ default SqlDocumentFilterConvertersList getFilterConverters() { return SqlDocumentFilterConverters.emptyList(); } default Optional<SqlDocumentFilterConverterDecorator> getFilterConverterDecorator() { return Optional.empty(); } default String replaceTableNameWithTableAlias(final String sql) { final String tableName = getTableName(); final String tableAlias = getTableAlias(); return replaceTableNameWithTableAlias(sql, tableName, tableAlias); } default String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableAlias) { final String tableName = getTableName(); return replaceTableNameWithTableAlias(sql, tableName, tableAlias); }
default SqlAndParams replaceTableNameWithTableAlias(final SqlAndParams sql, @NonNull final String tableAlias) { return SqlAndParams.of( replaceTableNameWithTableAlias(sql.getSql(), tableAlias), sql.getSqlParams()); } static String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableName, @NonNull final String tableAlias) { if (sql == null || sql.isEmpty()) { return sql; } final String matchTableNameIgnoringCase = "(?i)" + Pattern.quote(tableName + "."); final String sqlFixed = sql.replaceAll(matchTableNameIgnoringCase, tableAlias + "."); return sqlFixed; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlEntityBinding.java
1
请完成以下Java代码
public int getCarrier_ShipmentOrder_Parcel_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID); } @Override public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProductName (final @Nullable java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyShipped (final @Nullable BigDecimal QtyShipped)
{ set_Value (COLUMNNAME_QtyShipped, QtyShipped); } @Override public BigDecimal getQtyShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalPrice (final BigDecimal TotalPrice) { set_Value (COLUMNNAME_TotalPrice, TotalPrice); } @Override public BigDecimal getTotalPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalWeightInKg (final BigDecimal TotalWeightInKg) { set_Value (COLUMNNAME_TotalWeightInKg, TotalWeightInKg); } @Override public BigDecimal getTotalWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalWeightInKg); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Item.java
1
请完成以下Java代码
private String getTrxName() { if (trxManager.isNull(_trxName)) { return ITrx.TRXNAME_ThreadInherited; } return _trxName; } @Override public IInvoiceCandInvalidUpdater setLockedBy(final ILock lockedBy) { assertNotExecuted(); icTagger.setLockedBy(lockedBy); return this; } @Override public IInvoiceCandInvalidUpdater setTaggedWithNoTag() { assertNotExecuted(); icTagger.setTaggedWithNoTag(); return this; } @Override public IInvoiceCandInvalidUpdater setTaggedWithAnyTag() { assertNotExecuted(); icTagger.setTaggedWithAnyTag(); return this; } @Override public IInvoiceCandInvalidUpdater setLimit(final int limit) { assertNotExecuted(); icTagger.setLimit(limit); return this; } @Override public IInvoiceCandInvalidUpdater setRecomputeTagToUse(final InvoiceCandRecomputeTag tag) { assertNotExecuted(); icTagger.setRecomputeTag(tag); return this; } @Override public IInvoiceCandInvalidUpdater setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { assertNotExecuted(); icTagger.setOnlyInvoiceCandidateIds(onlyInvoiceCandidateIds); return this; } private int getItemsPerBatch() { return sysConfigBL.getIntValue(SYSCONFIG_ItemsPerBatch, DEFAULT_ItemsPerBatch); } /** * IC update result. * * @author metas-dev <dev@metasfresh.com> */ private static final class ICUpdateResult { private int countOk = 0; private int countErrors = 0; public void addInvoiceCandidate() { countOk++; } public void incrementErrorsCount() { countErrors++; } @Override public String toString() { return getSummary(); }
public String getSummary() { return "Updated " + countOk + " invoice candidates, " + countErrors + " errors"; } } /** * IC update exception handler */ private final class ICTrxItemExceptionHandler extends FailTrxItemExceptionHandler { private final ICUpdateResult result; public ICTrxItemExceptionHandler(@NonNull final ICUpdateResult result) { this.result = result; } /** * Resets the given IC to its old values, and sets an error flag in it. */ @Override public void onItemError(final Throwable e, final Object item) { result.incrementErrorsCount(); final I_C_Invoice_Candidate ic = InterfaceWrapperHelper.create(item, I_C_Invoice_Candidate.class); // gh #428: don't discard changes that were already made, because they might include a change of QtyInvoice. // in that case, a formerly Processed IC might need to be flagged as unprocessed. // if we discard all changes in this case, then we will have IsError='Y' and also an error message in the IC, // but the user will probably ignore it, because the IC is still flagged as processed. invoiceCandBL.setError(ic, e); // invoiceCandBL.discardChangesAndSetError(ic, e); invoiceCandDAO.save(ic); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandInvalidUpdater.java
1
请完成以下Java代码
public <D> Mono<List<D>> toEntityList(Class<D> elementType) { return this.responseMono.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } @Override public <D> Mono<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseMono.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } private static class DefaultRetrieveSubscriptionSpec extends RetrieveSpecSupport implements RetrieveSubscriptionSpec { private final Flux<ClientGraphQlResponse> responseFlux; DefaultRetrieveSubscriptionSpec(Flux<ClientGraphQlResponse> responseFlux, String path) { super(path); this.responseFlux = responseFlux; } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override public <D> Flux<D> toEntity(Class<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290 @Override
public <D> Flux<D> toEntity(ParameterizedTypeReference<D> entityType) { return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType)); } @Override public <D> Flux<List<D>> toEntityList(Class<D> elementType) { return this.responseFlux.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } @Override public <D> Flux<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) { return this.responseFlux.map((response) -> { ClientResponseField field = getValidField(response); return (field != null) ? field.toEntityList(elementType) : Collections.emptyList(); }); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultGraphQlClient.java
1
请完成以下Java代码
public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /** * Gets the value of the adr property. * * @return * possible object is * {@link PostalAddress6 } * */ public PostalAddress6 getAdr() {
return adr; } /** * Sets the value of the adr property. * * @param value * allowed object is * {@link PostalAddress6 } * */ public void setAdr(PostalAddress6 value) { this.adr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\NameAndAddress10.java
1
请完成以下Java代码
public @Nullable String getMethod() { return this.savedRequest.getMethod(); } @Override public @Nullable String getContentType() { return getHeader(HttpHeaders.CONTENT_TYPE); } /** * If the parameter is available from the wrapped request then the request has been * forwarded/included to a URL with parameters, either supplementing or overriding the * saved request values. * <p> * In this case, the value from the wrapped request should be used. * <p> * If the value from the wrapped request is null, an attempt will be made to retrieve * the parameter from the saved request. */ @Override public @Nullable String getParameter(String name) { String value = super.getParameter(name); if (value != null) { return value; } String[] values = this.savedRequest.getParameterValues(name); if (values == null || values.length == 0) { return null; } return values[0]; } @Override public Map<String, String[]> getParameterMap() { Set<String> names = getCombinedParameterNames(); Map<String, String[]> parameterMap = new HashMap<>(names.size()); for (String name : names) { parameterMap.put(name, getParameterValues(name)); } return parameterMap; } private Set<String> getCombinedParameterNames() { Set<String> names = new HashSet<>(); names.addAll(super.getParameterMap().keySet()); names.addAll(this.savedRequest.getParameterMap().keySet());
return names; } @Override public Enumeration<String> getParameterNames() { return new Enumerator<>(getCombinedParameterNames()); } @Override public String[] getParameterValues(String name) { String[] savedRequestParams = this.savedRequest.getParameterValues(name); String[] wrappedRequestParams = super.getParameterValues(name); if (savedRequestParams == null) { return wrappedRequestParams; } if (wrappedRequestParams == null) { return savedRequestParams; } // We have parameters in both saved and wrapped requests so have to merge them List<String> wrappedParamsList = Arrays.asList(wrappedRequestParams); List<String> combinedParams = new ArrayList<>(wrappedParamsList); // We want to add all parameters of the saved request *apart from* duplicates of // those already added for (String savedRequestParam : savedRequestParams) { if (!wrappedParamsList.contains(savedRequestParam)) { combinedParams.add(savedRequestParam); } } return combinedParams.toArray(new String[0]); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SavedRequestAwareWrapper.java
1
请完成以下Java代码
protected String doIt() { if (p_M_Product_Category_ID > 0) { final IQueryBuilder<I_M_Product> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_Product.class) .addEqualsFilter(I_M_Product.COLUMNNAME_IsBOM, true) .addEqualsFilter(I_M_Product.COLUMNNAME_M_Product_Category_ID, p_M_Product_Category_ID) .orderBy() .addColumn(I_M_Product.COLUMNNAME_Name) .endOrderBy(); final AtomicInteger counter = new AtomicInteger(0); queryBuilder.create() .stream() .forEach(product -> { try { validateProduct(product); counter.incrementAndGet(); } catch (final Exception ex) { log.warn("Product is not valid: {}", product, ex); } }); return "#" + counter.get(); } else { final I_M_Product product = InterfaceWrapperHelper.load(getM_Product_ID(), I_M_Product.class); validateProduct(product); return MSG_OK; } } private int getM_Product_ID() { final String tableName = getTableName(); if (I_M_Product.Table_Name.equals(tableName)) { return getRecord_ID(); } else if (I_PP_Product_BOM.Table_Name.equals(tableName)) { final ProductBOMId bomId = ProductBOMId.ofRepoId(getRecord_ID()); final I_PP_Product_BOM bom = productBOMDAO.getById(bomId); return bom.getM_Product_ID(); } else { throw new AdempiereException(StringUtils.formatMessage("Table {} has not yet been implemented to support BOM validation.", tableName)); } } private void validateProduct(@NonNull final I_M_Product product) { try { trxManager.runInNewTrx(() -> checkProductById(product)); } catch (final Exception ex) { product.setIsVerified(false);
InterfaceWrapperHelper.save(product); throw AdempiereException.wrapIfNeeded(ex); } } private void checkProductById(@NonNull final I_M_Product product) { if (!product.isBOM()) { log.info("Product is not a BOM"); // No BOM - should not happen, but no problem return; } // Check this level checkProductBOMCyclesAndMarkAsVerified(product); // Get Default BOM from this product final I_PP_Product_BOM bom = productBOMDAO.getDefaultBOMByProductId(ProductId.ofRepoId(product.getM_Product_ID())) .orElseThrow(() -> new AdempiereException(NO_DEFAULT_PP_PRODUCT_BOM_FOR_PRODUCT_MESSAGE_KEY, product.getValue() + "_" + product.getName())); // Check All BOM Lines for (final I_PP_Product_BOMLine tbomline : productBOMDAO.retrieveLines(bom)) { final ProductId productId = ProductId.ofRepoId(tbomline.getM_Product_ID()); final I_M_Product bomLineProduct = productBL.getById(productId); checkProductBOMCyclesAndMarkAsVerified(bomLineProduct); } } private void checkProductBOMCyclesAndMarkAsVerified(final I_M_Product product) { final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); productBOMBL.checkCycles(productId); product.setIsVerified(true); InterfaceWrapperHelper.save(product); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Product_BOM_Check.java
1
请在Spring Boot框架中完成以下Java代码
private void removeRequest(Integer rowId, IWebSession webSession) { if (rowId != null) { List<SessionNameRequest> requests = getRequestsFromSession(webSession); if (requests != null) { requests.remove(rowId.intValue()); } } } private void performNameRequest(final NameRequest nameRequest, IWebSession webSession) { try { CompletableFuture<NameAnalysisEntity> nameAnalysis = this.nameAnalysisService.searchForName(nameRequest); NameAnalysisEntity nameAnalysisEntity = nameAnalysis.get(30, TimeUnit.SECONDS); sessionRegisterRequest(nameRequest, webSession); sessionRegisterAnalysis(nameAnalysisEntity, webSession); sessionClearAnalysisError(webSession); } catch (Exception e) { e.printStackTrace(); sessionSetAnalysisError(nameRequest, webSession); } } private void sessionClearAnalysisError(IWebSession webSession) { webSession.removeAttribute("analysisError"); } private void sessionSetAnalysisError(NameRequest nameRequest, IWebSession webSession) { webSession.setAttributeValue("analysisError", nameRequest); } private void clearAnalysis(IWebSession webSession) {
webSession.removeAttribute("lastAnalysis"); } private void sessionRegisterAnalysis(NameAnalysisEntity analysis, IWebSession webSession) { webSession.setAttributeValue("lastAnalysis", analysis); } private void sessionRegisterRequest(NameRequest nameRequest, IWebSession webSession) { webSession.setAttributeValue("lastRequest", nameRequest); SessionNameRequest sessionNameRequest = sessionNameRequestFactory.getInstance(nameRequest); List<SessionNameRequest> requests = getRequestsFromSession(webSession); requests.add(0, sessionNameRequest); } private List<SessionNameRequest> getRequestsFromSession(IWebSession session) { Object requests = session.getAttributeValue("requests"); if (requests == null || !(requests instanceof List)) { List<SessionNameRequest> sessionNameRequests = new ArrayList<>(); session.setAttributeValue("requests", sessionNameRequests); requests = sessionNameRequests; } return (List<SessionNameRequest>) requests; } private IWebSession getIWebSession(HttpServletRequest request, HttpServletResponse response) { IServletWebExchange exchange = webApp.buildExchange(request, response); return exchange == null ? null : exchange.getSession(); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\web\controllers\NameAnalysisController.java
2
请完成以下Java代码
protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return customerDao.findCustomersByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, Customer entity) { deleteCustomer(tenantId, new CustomerId(entity.getUuidId())); } }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public long countByTenantId(TenantId tenantId) { return customerDao.countByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java
1
请完成以下Java代码
public DocSequenceId getDocNoSequenceId(final ClientId adClientId, final OrgId adOrgId) { if (!docTypeSequences.isEmpty()) { final ArrayKey key = mkKey(adClientId, adOrgId); final DocTypeSequence docTypeSequence = docTypeSequences.get(key); if (docTypeSequence != null) { return docTypeSequence.getDocSequenceId(); } } return defaultDocNoSequenceId; } private static ArrayKey mkKey(@NonNull final ClientId adClientId, @NonNull final OrgId adOrgId) { return Util.mkKey(adClientId, adOrgId); } public static final class Builder { private final Map<ArrayKey, DocTypeSequence> docTypeSequences = new HashMap<>(); private DocSequenceId defaultDocNoSequenceId = null; private Builder() { } public DocTypeSequenceMap build() { return new DocTypeSequenceMap(this); } public void addDocSequenceId(final ClientId adClientId, final OrgId adOrgId, final DocSequenceId docSequenceId) { final DocTypeSequence docTypeSequence = new DocTypeSequence(adClientId, adOrgId, docSequenceId); final ArrayKey key = mkKey(docTypeSequence.getAdClientId(), docTypeSequence.getAdOrgId());
docTypeSequences.put(key, docTypeSequence); } public Builder defaultDocNoSequenceId(final DocSequenceId defaultDocNoSequenceId) { this.defaultDocNoSequenceId = defaultDocNoSequenceId; return this; } } @Value private static final class DocTypeSequence { private final ClientId adClientId; private final OrgId adOrgId; private final DocSequenceId docSequenceId; private DocTypeSequence( @Nullable final ClientId adClientId, @Nullable final OrgId adOrgId, @NonNull final DocSequenceId docSequenceId) { this.adClientId = adClientId != null ? adClientId : ClientId.SYSTEM; this.adOrgId = adOrgId != null ? adOrgId : OrgId.ANY; this.docSequenceId = docSequenceId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocTypeSequenceMap.java
1
请完成以下Spring Boot application配置
spring: # Quartz 的配置,对应 QuartzProperties 配置类 quartz: job-store-type: memory # Job 存储器类型。默认为 memory 表示内存,可选 jdbc 使用数据库。 auto-startup: true # Quartz 是否自动启动 startup-delay: 0 # 延迟 N 秒启动 wait-for-jobs-to-complete-on-shutdown: true # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true overwrite-existing-jobs: false # 是否覆盖已有 Job 的配置 properties: # 添加 Quartz Scheduler 附加属性,更多可以看 http://www.quartz-scheduler.org/documentation/2.4.0-SNAPSHOT/configuration.html 文档 org: quartz:
threadPool: threadCount: 25 # 线程池大小。默认为 10 。 threadPriority: 5 # 线程优先级 class: org.quartz.simpl.SimpleThreadPool # 线程池类型 # jdbc: # 这里暂时不说明,使用 JDBC 的 JobStore 的时候,才需要配置
repos\SpringBoot-Labs-master\lab-28\lab-28-task-quartz-memory\src\main\resources\application.yaml
2
请完成以下Java代码
public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setIsDynamic (final boolean IsDynamic) { set_Value (COLUMNNAME_IsDynamic, IsDynamic); } @Override public boolean isDynamic() { return get_ValueAsBoolean(COLUMNNAME_IsDynamic); } @Override public void setIsPickingRackSystem (final boolean IsPickingRackSystem) { set_Value (COLUMNNAME_IsPickingRackSystem, IsPickingRackSystem); } @Override public boolean isPickingRackSystem() { return get_ValueAsBoolean(COLUMNNAME_IsPickingRackSystem); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); }
@Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请完成以下Java代码
protected static <T> T convertFromJsonNodeToObject(JsonNode jsonNode, ObjectMapper objectMapper) { return objectMapper.convertValue(jsonNode, new TypeReference<>() { }); } protected static String getJsonProperty(String propertyName, JsonNode jsonNode) { if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) { return jsonNode.get(propertyName).asString(); } return null; } protected static Integer getJsonPropertyAsInteger(String propertyName, JsonNode jsonNode) { if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) {
return jsonNode.get(propertyName).asInt(); } return null; } protected static <V> V getLocalVariablesFromJson(JsonNode jsonNode, ObjectMapper objectMapper) { JsonNode localVariablesNode = jsonNode.get(LOCAL_VARIABLES_JSON_SECTION); if (localVariablesNode != null) { return convertFromJsonNodeToObject(localVariablesNode, objectMapper); } return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentConverter.java
1
请完成以下Java代码
public Boolean getUvInitialized() { return uvInitialized; } public void setUvInitialized(Boolean uvInitialized) { this.uvInitialized = uvInitialized; } public String getTransports() { return transports; } public void setTransports(String transports) { this.transports = transports; } public Boolean getBackupEligible() { return backupEligible; } public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible; } public Boolean getBackupState() { return backupState; } public void setBackupState(Boolean backupState) { this.backupState = backupState; } public String getAttestationObject() { return attestationObject; } public void setAttestationObject(String attestationObject) { this.attestationObject = attestationObject;
} public Instant getLastUsed() { return lastUsed; } public void setLastUsed(Instant lastUsed) { this.lastUsed = lastUsed; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java
1
请在Spring Boot框架中完成以下Java代码
public class Player { @Id private int id; private String playerName; private String teamName; private int age; @ManyToOne @JoinColumn(name = "league_id") private League league; public Player() { } public Player(int id, String playerName, String teamName, int age, League league) { this.id = id; this.playerName = playerName; this.teamName = teamName; this.age = age; this.league = league; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPlayerName() { return playerName; }
public void setPlayerName(String playerName) { this.playerName = playerName; } public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public League getLeague() { return league; } public void setLeague(League league) { this.league = league; } @Override public String toString() { return "Player{" + "id=" + id + ", playerName='" + playerName + '\'' + ", teamName='" + teamName + '\'' + ", age=" + age + ", league_id=" + (league != null ? league.getId() : "null") + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\joinfetchcriteriaquery\model\Player.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult<UmsResource> getItem(@PathVariable Long id) { UmsResource umsResource = resourceService.getItem(id); return CommonResult.success(umsResource); } @ApiOperation("根据ID删除后台资源") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = resourceService.delete(id); dynamicSecurityMetadataSource.clearDataSource(); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页模糊查询后台资源") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsResource>> list(@RequestParam(required = false) Long categoryId, @RequestParam(required = false) String nameKeyword,
@RequestParam(required = false) String urlKeyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsResource> resourceList = resourceService.list(categoryId,nameKeyword, urlKeyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(resourceList)); } @ApiOperation("查询所有后台资源") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listAll() { List<UmsResource> resourceList = resourceService.listAll(); return CommonResult.success(resourceList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsResourceController.java
2
请完成以下Java代码
public ArrayList<CompactTree> readStringData() throws IOException { ArrayList<CompactTree> treeSet = new ArrayList<CompactTree>(); String line; ArrayList<String> tags = new ArrayList<String>(); HashMap<Integer, Pair<Integer, String>> goldDependencies = new HashMap<Integer, Pair<Integer, String>>(); while ((line = fileReader.readLine()) != null) { line = line.trim(); if (line.length() == 0) { if (tags.size() >= 1) { CompactTree goldConfiguration = new CompactTree(goldDependencies, tags); treeSet.add(goldConfiguration); } tags = new ArrayList<String>(); goldDependencies = new HashMap<Integer, Pair<Integer, String>>(); } else { String[] splitLine = line.split("\t"); if (splitLine.length < 8) throw new IllegalArgumentException("wrong file format"); int wordIndex = Integer.parseInt(splitLine[0]); String pos = splitLine[3].trim(); tags.add(pos);
int headIndex = Integer.parseInt(splitLine[6]); String relation = splitLine[7]; if (headIndex == 0) { relation = "ROOT"; } if (pos.length() > 0) goldDependencies.put(wordIndex, new Pair<Integer, String>(headIndex, relation)); } } if (tags.size() > 0) { treeSet.add(new CompactTree(goldDependencies, tags)); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\accessories\CoNLLReader.java
1
请完成以下Java代码
public static void main(String[] args) { SpringApplication.run(ThreadStarvationApp.class); } @RestController class RestApi { @GetMapping("/blocking") Mono<String> getBlocking() { return Mono.fromCallable(() -> { try { Thread.sleep(2_000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "foo"; }); } @GetMapping("/non-blocking") Mono<String> getNonBlocking() { return Mono.just("bar") .delayElement(Duration.ofSeconds(2)); } @SuppressWarnings("BlockingMethodInNonBlockingContext") @GetMapping("/warning") Mono<String> warning() { Mono<String> data = fetchData(); String response = "retrieved data: " + data.block(); return Mono.just(response);
} private Mono<String> fetchData() { return Mono.just("bar"); } @GetMapping("/blocking-with-scheduler") Mono<String> getBlockingWithDedicatedScheduler() { return Mono.fromCallable(this::fetchDataBlocking) .subscribeOn(Schedulers.boundedElastic()) .map(data -> "retrieved data: " + data); } private String fetchDataBlocking() { try { Thread.sleep(2_000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "foo"; } } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\threadstarvation\ThreadStarvationApp.java
1
请在Spring Boot框架中完成以下Java代码
public class CacheController { @Autowired PersonService personService; @Autowired CacheManager cacheManager; @RequestMapping("/put") public long put(@RequestBody Person person) { Person p = personService.save(person); return p.getId(); } @RequestMapping("/able") public Person cacheable(Person person) { String a = "a"; String[] b = {"1", "2"}; List<Long> c = new ArrayList<>(); c.add(3L); c.add(4L); return personService.findOne(person, a, b, c); } @RequestMapping("/able1")
public Person cacheable1(Person person) { return personService.findOne1(); } @RequestMapping("/able2") public Person cacheable2(Person person) { return personService.findOne2(person); } @RequestMapping("/evit") public String evit(Long id) { personService.remove(id); return "ok"; } }
repos\spring-boot-student-master\spring-boot-student-cache-caffeine\src\main\java\com\xiaolyuh\controller\CacheController.java
2
请完成以下Java代码
private ApiResponse wrapBodyIfNeeded( @Nullable final ApiAuditConfig apiAuditConfig, @Nullable final ApiRequestAudit apiRequestAudit, @NonNull final ApiResponse apiResponse) { if (apiAuditConfig != null && apiRequestAudit != null && apiAuditConfig.isWrapApiResponse() && apiResponse.isJson()) { return apiResponse.toBuilder() .contentType(MediaType.APPLICATION_JSON) .charset(StandardCharsets.UTF_8) .body(JsonApiResponse.builder() .requestId(JsonMetasfreshId.of(apiRequestAudit.getIdNotNull().getRepoId())) .endpointResponse(apiResponse.getBody()) .build()) .build(); } else { final HttpHeaders httpHeaders = apiResponse.getHttpHeaders() != null ? new HttpHeaders(apiResponse.getHttpHeaders()) : new HttpHeaders(); if (apiRequestAudit != null) { httpHeaders.add(API_RESPONSE_HEADER_REQUEST_AUDIT_ID, String.valueOf(apiRequestAudit.getIdNotNull().getRepoId()));
} return apiResponse.toBuilder().httpHeaders(httpHeaders).build(); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean isResetServletResponse(@NonNull final HttpServletResponse response) { if (!response.isCommitted()) { response.reset(); return true; } Loggables.addLog("HttpServletResponse has already been committed -> cannot be altered! response status = {}", response.getStatus()); return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ResponseHandler.java
1
请完成以下Java代码
protected void executeCommand(Command<?> command) { try { if(commandExecutor != null) { commandExecutor.execute(command); } else { command.execute(commandContext); } } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (CaseExecutionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (CaseDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (CaseIllegalStateTransitionException e) { throw new NotAllowedException(e.getMessage(), e); } } // getters //////////////////////////////////////////////////////////////////////////////// public String getCaseExecutionId() { return caseExecutionId; } public VariableMap getVariables() {
return variables; } public VariableMap getVariablesLocal() { return variablesLocal; } public Collection<String> getVariableDeletions() { return variableDeletions; } public Collection<String> getVariableLocalDeletions() { return variableLocalDeletions; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseExecutionCommandBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderPropertiesCommandLineRunner implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OrderProperties orderProperties; @Override public void run(String... args) { logger.info("payTimeoutSeconds:" + orderProperties.getPayTimeoutSeconds()); logger.info("createFrequencySeconds:" + orderProperties.getCreateFrequencySeconds()); } } @Component public class ValueCommandLineRunner implements CommandLineRunner { private final Logger logger = LoggerFactory.getLogger(getClass()); @Value("${order.pay-timeout-seconds}") private Integer payTimeoutSeconds;
@Value("${order.create-frequency-seconds}") private Integer createFrequencySeconds; // @Value("${order.desc}") // private String desc; @Override public void run(String... args) { logger.info("payTimeoutSeconds:" + payTimeoutSeconds); logger.info("createFrequencySeconds:" + createFrequencySeconds); } } }
repos\SpringBoot-Labs-master\lab-43\lab-43-demo\src\main\java\cn\iocoder\springboot\lab43\propertydemo\Application.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_A_Depreciation[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Depreciation Type. @param A_Depreciation_ID Depreciation Type */ public void setA_Depreciation_ID (int A_Depreciation_ID) { if (A_Depreciation_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, Integer.valueOf(A_Depreciation_ID)); } /** Get Depreciation Type. @return Depreciation Type */ public int getA_Depreciation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DepreciationType. @param DepreciationType DepreciationType */ public void setDepreciationType (String DepreciationType) { set_Value (COLUMNNAME_DepreciationType, DepreciationType); } /** Get DepreciationType. @return DepreciationType */ public String getDepreciationType () { return (String)get_Value(COLUMNNAME_DepreciationType); } /** 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); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java
1
请在Spring Boot框架中完成以下Java代码
private static class DocTypePrintOptionsKey { @NonNull DocTypeId docTypeId; @Nullable DocumentReportFlavor flavor; } private static class DocTypePrintOptionsMap { public static final DocTypePrintOptionsMap EMPTY = new DocTypePrintOptionsMap(ImmutableMap.of()); private final ImmutableMap<DocTypePrintOptionsKey, DocumentPrintOptions> map; DocTypePrintOptionsMap(final Map<DocTypePrintOptionsKey, DocumentPrintOptions> map)
{ this.map = ImmutableMap.copyOf(map); } public DocumentPrintOptions getByDocTypeAndFlavor( @NonNull final DocTypeId docTypeId, @NonNull final DocumentReportFlavor flavor) { return CoalesceUtil.coalesceSuppliers( () -> map.get(DocTypePrintOptionsKey.of(docTypeId, flavor)), () -> map.get(DocTypePrintOptionsKey.of(docTypeId, null)), () -> DocumentPrintOptions.NONE); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocTypePrintOptionsRepository.java
2
请完成以下Java代码
public int getMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne getMSV3_VerfuegbarkeitsanfrageEinzelne() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class); } @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpResponse { /** * 返回中的Header信息 */ private Header[] responseHeaders; /** * String类型的result */ private String stringResult; /** * btye类型的result */ private byte[] byteResult; public Header[] getResponseHeaders() { return responseHeaders; } public void setResponseHeaders(Header[] responseHeaders) { this.responseHeaders = responseHeaders; } public byte[] getByteResult() { if (byteResult != null) { return byteResult; }
if (stringResult != null) { return stringResult.getBytes(); } return null; } public void setByteResult(byte[] byteResult) { this.byteResult = byteResult; } public String getStringResult() throws UnsupportedEncodingException { if (stringResult != null) { return stringResult; } if (byteResult != null) { return new String(byteResult, AlipayConfigUtil.readConfig("input_charset")); } return null; } public void setStringResult(String stringResult) { this.stringResult = stringResult; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\httpClient\HttpResponse.java
2
请在Spring Boot框架中完成以下Java代码
public Mono<Long> countManagedUsers() { return userRepository.count(); } @Transactional(readOnly = true) public Mono<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public Mono<User> getUserWithAuthorities() { return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { removeNotActivatedUsersReactively().blockLast(); } @Transactional public Flux<User> removeNotActivatedUsersReactively() { return userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore( LocalDateTime.ofInstant(Instant.now().minus(3, ChronoUnit.DAYS), ZoneOffset.UTC) ) .flatMap(user -> userRepository.delete(user).thenReturn(user)) .doOnNext(user -> log.debug("Deleted User: {}", user)); } /** * Gets a list of all the authorities. * @return a list of all the authorities. */ @Transactional(readOnly = true) public Flux<String> getAuthorities() { return authorityRepository.findAll().map(Authority::getName); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\UserService.java
2
请完成以下Java代码
public void setHasGraphicalNotation(boolean hasGraphicalNotation) { this.isGraphicalNotationDefined = hasGraphicalNotation; } @Override public void setDiagramResourceName(String diagramResourceName) { this.diagramResourceName = diagramResourceName; } @Override public void setHasStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public List<IdentityLinkEntity> getIdentityLinks() { if (!isIdentityLinksInitialized) { definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration() .getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true; } return definitionIdentityLinkEntities; } public String getLocalizedName() { return localizedName; } @Override public void setLocalizedName(String localizedName) { this.localizedName = localizedName; } public String getLocalizedDescription() { return localizedDescription; } @Override public void setLocalizedDescription(String localizedDescription) { this.localizedDescription = localizedDescription; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public final class OpenSaml5LogoutRequestValidatorParametersResolver implements Saml2LogoutRequestValidatorParametersResolver { static { OpenSamlInitializationService.initialize(); } private final BaseOpenSamlLogoutRequestValidatorParametersResolver delegate; /** * Constructs a {@link OpenSaml5LogoutRequestValidatorParametersResolver} */ public OpenSaml5LogoutRequestValidatorParametersResolver(RelyingPartyRegistrationRepository registrations) { Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); this.delegate = new BaseOpenSamlLogoutRequestValidatorParametersResolver(new OpenSaml5Template(), registrations); } /** * Construct the parameters necessary for validating an asserting party's * {@code <saml2:LogoutRequest>} based on the given {@link HttpServletRequest} * * <p> * Uses the configured {@link RequestMatcher} to identify the processing request, * including looking for any indicated {@code registrationId}. * * <p> * If a {@code registrationId} is found in the request, it will attempt to use that, * erroring if no {@link RelyingPartyRegistration} is found. * * <p> * If no {@code registrationId} is found in the request, it will look for a currently * logged-in user and use the associated {@code registrationId}. * * <p> * In the event that neither the URL nor any logged in user could determine a * {@code registrationId}, this code then will try and derive a * {@link RelyingPartyRegistration} given the {@code <saml2:LogoutRequest>}'s * {@code Issuer} value. * @param request the HTTP request * @return a {@link Saml2LogoutRequestValidatorParameters} instance, or {@code null}
* if one could not be resolved * @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a * non-existent {@code registrationId} */ @Override public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication) { return this.delegate.resolve(request, authentication); } /** * The request matcher to use to identify a request to process a * {@code <saml2:LogoutRequest>}. By default, checks for {@code /logout/saml2/slo} and * {@code /logout/saml2/slo/{registrationId}}. * * <p> * Generally speaking, the URL does not need to have a {@code registrationId} in it * since either it can be looked up from the active logged in user or it can be * derived through the {@code Issuer} in the {@code <saml2:LogoutRequest>}. * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.delegate.setRequestMatcher(requestMatcher); } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolver.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("sql", sql) .add("sqlParams", sqlParams) .toString(); } public SqlAndParams build() { final String sql = this.sql != null ? this.sql.toString() : ""; final Object[] sqlParamsArray = sqlParams != null ? sqlParams.toArray() : null; return new SqlAndParams(sql, sqlParamsArray); } public Builder clear() { sql = null; sqlParams = null; return this; } public boolean isEmpty() { return length() <= 0 && !hasParameters(); } public int length() { return sql != null ? sql.length() : 0; } public boolean hasParameters() { return sqlParams != null && !sqlParams.isEmpty(); } public int getParametersCount() { return sqlParams != null ? sqlParams.size() : 0; } public Builder appendIfHasParameters(@NonNull final CharSequence sql) { if (hasParameters()) { return append(sql); } else { return this; } } public Builder appendIfNotEmpty(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { if (!isEmpty()) { append(sql, sqlParams); } return this;
} public Builder append(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { final List<Object> sqlParamsList = sqlParams != null && sqlParams.length > 0 ? Arrays.asList(sqlParams) : null; return append(sql, sqlParamsList); } public Builder append(@NonNull final CharSequence sql, @Nullable final List<Object> sqlParams) { if (sql.length() > 0) { if (this.sql == null) { this.sql = new StringBuilder(); } this.sql.append(sql); } if (sqlParams != null && !sqlParams.isEmpty()) { if (this.sqlParams == null) { this.sqlParams = new ArrayList<>(); } this.sqlParams.addAll(sqlParams); } return this; } public Builder append(@NonNull final SqlAndParams other) { return append(other.sql, other.sqlParams); } public Builder append(@NonNull final SqlAndParams.Builder other) { return append(other.sql, other.sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParams.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonPaymentAllocationLine { @NonNull @ApiModelProperty(required = true, dataType = "java.lang.String", value = SwaggerDocConstants.INVOICE_IDENTIFIER_DOC) String invoiceIdentifier; @ApiModelProperty(position = 10) @Nullable String docBaseType; @ApiModelProperty(position = 20) @Nullable String docSubType; @ApiModelProperty(position = 30)
@Nullable BigDecimal amount; @ApiModelProperty(position = 40) @Nullable BigDecimal discountAmt; @ApiModelProperty(position = 50) @Nullable BigDecimal writeOffAmt; @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") public static class JsonPaymentAllocationLineBuilder { } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\payment\JsonPaymentAllocationLine.java
2
请完成以下Java代码
public void setCounter (int Counter) { throw new IllegalArgumentException ("Counter is virtual column"); } /** Get Counter. @return Count Value */ public int getCounter () { Integer ii = (Integer)get_Value(COLUMNNAME_Counter); if (ii == null) return 0; return ii.intValue(); } /** 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); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Page URL. @param PageURL Page URL */ public void setPageURL (String PageURL)
{ set_Value (COLUMNNAME_PageURL, PageURL); } /** Get Page URL. @return Page URL */ public String getPageURL () { return (String)get_Value(COLUMNNAME_PageURL); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_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_W_CounterCount.java
1
请在Spring Boot框架中完成以下Java代码
public class CityWebFluxController { @Autowired private CityHandler cityHandler; @GetMapping(value = "/{id}") @ResponseBody public Mono<City> findCityById(@PathVariable("id") Long id) { return cityHandler.findCityById(id); } @GetMapping() @ResponseBody public Flux<City> findAllCity() { return cityHandler.findAllCity(); } @PostMapping() @ResponseBody public Mono<Long> saveCity(@RequestBody City city) { return cityHandler.save(city); } @PutMapping() @ResponseBody public Mono<Long> modifyCity(@RequestBody City city) { return cityHandler.modifyCity(city); }
@DeleteMapping(value = "/{id}") @ResponseBody public Mono<Long> deleteCity(@PathVariable("id") Long id) { return cityHandler.deleteCity(id); } @GetMapping("/hello") public Mono<String> hello(final Model model) { model.addAttribute("name", "泥瓦匠"); model.addAttribute("city", "浙江温岭"); String path = "hello"; return Mono.create(monoSink -> monoSink.success(path)); } private static final String CITY_LIST_PATH_NAME = "cityList"; @GetMapping("/page/list") public String listPage(final Model model) { final Flux<City> cityFluxList = cityHandler.findAllCity(); model.addAttribute("cityList", cityFluxList); return CITY_LIST_PATH_NAME; } }
repos\springboot-learning-example-master\springboot-webflux-4-thymeleaf\src\main\java\org\spring\springboot\webflux\controller\CityWebFluxController.java
2
请完成以下Java代码
public void setDocStatus (final java.lang.String DocStatus) { set_Value (COLUMNNAME_DocStatus, DocStatus); } @Override public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setDocumentNo (final java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setEvaluationStartDate (final java.sql.Timestamp EvaluationStartDate) { set_Value (COLUMNNAME_EvaluationStartDate, EvaluationStartDate); } @Override public java.sql.Timestamp getEvaluationStartDate() { return get_ValueAsTimestamp(COLUMNNAME_EvaluationStartDate); } @Override public org.compiere.model.I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class); } @Override public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } @Override public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID) { if (M_CostRevaluation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID); } @Override public int getM_CostRevaluation_ID() { return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID); } @Override public void setPosted (final boolean Posted) { set_Value (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluation.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BP_Contact_ID (final int C_BP_Contact_ID) { if (C_BP_Contact_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BP_Contact_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BP_Contact_ID, C_BP_Contact_ID); } @Override public int getC_BP_Contact_ID() { return get_ValueAsInt(COLUMNNAME_C_BP_Contact_ID); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setCity (final @Nullable java.lang.String City) { set_Value (COLUMNNAME_City, City); } @Override public java.lang.String getCity() { return get_ValueAsString(COLUMNNAME_City); } @Override public void setFirstname (final @Nullable java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() {
return get_ValueAsString(COLUMNNAME_Firstname); } @Override public void setIsCompany (final boolean IsCompany) { set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany); } @Override public boolean isCompany() { return get_ValueAsBoolean(COLUMNNAME_IsCompany); } @Override public void setLastname (final @Nullable java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); } @Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search_v.java
1
请完成以下Java代码
private PO createNode(int nodeId, int parentId) { final String nodeTableName = getNodeTableName(); PO node = null; if (nodeTableName.equals(MTree_Node.Table_Name)) { MTree_Node n = new MTree_Node(this, nodeId); if (nodeId != ROOT_Node_ID) n.setParent_ID(parentId); node = n; } else if (nodeTableName.equals(MTree_NodeBP.Table_Name)) { MTree_NodeBP n = new MTree_NodeBP(this, nodeId); if (nodeId != ROOT_Node_ID) n.setParent_ID(parentId); node = n; } else if (nodeTableName.equals(MTree_NodePR.Table_Name)) { MTree_NodePR n = new MTree_NodePR(this, nodeId); if (nodeId != ROOT_Node_ID) n.setParent_ID(parentId); node = n; } else if (nodeTableName.equals(MTree_NodeMM.Table_Name)) { MTree_NodeMM n = new MTree_NodeMM(this, nodeId);
if (nodeId != ROOT_Node_ID) n.setParent_ID(parentId); node = n; } else { throw new AdempiereException("No Table Model for " + nodeTableName); } node.saveEx(); return node; } private final static TreeListenerSupport listeners = new TreeListenerSupport(); public static void registerTreeListener(ITreeListener listener, boolean isWeak) { listeners.addTreeListener(listener, isWeak); } public static void unregisterTreeListener(ITreeListener listener) { listeners.removeTreeListener(listener); } } // MTree_Base
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree_Base.java
1
请完成以下Java代码
private List<I_MD_Stock_From_HUs_V> retrieveHuData() { addLog("Performing a select for Records to correct on MD_Stock_From_HUs_V"); return queryBL .createQueryBuilder(I_MD_Stock_From_HUs_V.class) .addNotEqualsFilter(I_MD_Stock_From_HUs_V.COLUMNNAME_QtyOnHandChange, ZERO) .create() .list(); } private void createAndHandleDataUpdateRequests( @NonNull final List<I_MD_Stock_From_HUs_V> huBasedDataRecords) { final ResetStockPInstanceId resetStockPInstanceId = ResetStockPInstanceId.ofPInstanceId(getProcessInfo().getPinstanceId()); final StockChangeSourceInfo info = StockChangeSourceInfo.ofResetStockPInstanceId(resetStockPInstanceId); for (final I_MD_Stock_From_HUs_V huBasedDataRecord : huBasedDataRecords) { final StockDataUpdateRequest dataUpdateRequest = createDataUpdatedRequest( huBasedDataRecord, info); addLog("Handling corrective dataUpdateRequest={}", dataUpdateRequest); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } } private StockDataUpdateRequest createDataUpdatedRequest( @NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord, @NonNull final StockChangeSourceInfo stockDataUpdateRequestSourceInfo) { final StockDataRecordIdentifier recordIdentifier = toStockDataRecordIdentifier(huBasedDataRecord);
final ProductId productId = ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID()); final Quantity qtyInStorageUOM = Quantitys.of(huBasedDataRecord.getQtyOnHandChange(), UomId.ofRepoId(huBasedDataRecord.getC_UOM_ID())); final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(qtyInStorageUOM, productId); return StockDataUpdateRequest.builder() .identifier(recordIdentifier) .onHandQtyChange(qtyInProductUOM.toBigDecimal()) .sourceInfo(stockDataUpdateRequestSourceInfo) .build(); } private static StockDataRecordIdentifier toStockDataRecordIdentifier(@NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord) { return StockDataRecordIdentifier.builder() .clientId(ClientId.ofRepoId(huBasedDataRecord.getAD_Client_ID())) .orgId(OrgId.ofRepoId(huBasedDataRecord.getAD_Org_ID())) .warehouseId(WarehouseId.ofRepoId(huBasedDataRecord.getM_Warehouse_ID())) .productId(ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID())) .storageAttributesKey(AttributesKey.ofString(huBasedDataRecord.getAttributesKey())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\process\MD_Stock_Update_From_M_HUs.java
1
请在Spring Boot框架中完成以下Java代码
public HelloWorldBean helloWorldBean() { return new HelloWorldBean("Hello World"); } // Path Parameters // /users/{id}/todos/{id} => /users/2/todos/200 // /hello-world/path-variable/{name} // /hello-world/path-variable/Ranga @GetMapping(path = "/hello-world/path-variable/{name}") public HelloWorldBean helloWorldPathVariable(@PathVariable String name) { return new HelloWorldBean(String.format("Hello World, %s", name)); } @GetMapping(path = "/hello-world-internationalized") public String helloWorldInternationalized() {
Locale locale = LocaleContextHolder.getLocale(); return messageSource.getMessage("good.morning.message", null, "Default Message", locale ); //return "Hello World V2"; //1: //2: // - Example: `en` - English (Good Morning) // - Example: `nl` - Dutch (Goedemorgen) // - Example: `fr` - French (Bonjour) // - Example: `de` - Deutsch (Guten Morgen) } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\helloworld\HelloWorldController.java
2
请完成以下Java代码
public List<BpmnParseHandler> getHandlersFor(Class<? extends BaseElement> clazz) { return parseHandlers.get(clazz); } public void addHandlers(List<BpmnParseHandler> bpmnParseHandlers) { for (BpmnParseHandler bpmnParseHandler : bpmnParseHandlers) { addHandler(bpmnParseHandler); } } public void addHandler(BpmnParseHandler bpmnParseHandler) { for (Class<? extends BaseElement> type : bpmnParseHandler.getHandledTypes()) { List<BpmnParseHandler> handlers = parseHandlers.get(type); if (handlers == null) { handlers = new ArrayList<BpmnParseHandler>(); parseHandlers.put(type, handlers); } handlers.add(bpmnParseHandler); } } public void parseElement(BpmnParse bpmnParse, BaseElement element) { if (element instanceof DataObject) { // ignore DataObject elements because they are processed on Process // and Sub process level return; }
if (element instanceof FlowElement) { bpmnParse.setCurrentFlowElement((FlowElement) element); } // Execute parse handlers List<BpmnParseHandler> handlers = parseHandlers.get(element.getClass()); if (handlers == null) { LOGGER.warn("Could not find matching parse handler for + " + element.getId() + " this is likely a bug."); } else { for (BpmnParseHandler handler : handlers) { handler.parse(bpmnParse, element); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParseHandlers.java
1
请完成以下Java代码
public Attribute get(String from, String to) { return get(from + "@" + to); } static class Attribute { final static Attribute NULL = new Attribute("未知", 10000.0f); /** * 依存关系 */ public String[] dependencyRelation; /** * 概率 */ public float[] p; public Attribute(int size) { dependencyRelation = new String[size]; p = new float[size]; } Attribute(String dr, float p) { dependencyRelation = new String[]{dr};
this.p = new float[]{p}; } /** * 加权 * @param boost */ public void setBoost(float boost) { for (int i = 0; i < p.length; ++i) { p[i] *= boost; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(dependencyRelation.length * 10); for (int i = 0; i < dependencyRelation.length; ++i) { sb.append(dependencyRelation[i]).append(' ').append(p[i]).append(' '); } return sb.toString(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\WordNatureDependencyModel.java
1
请完成以下Java代码
public class MyKey { private static final Logger LOG = LoggerFactory.getLogger(MyKey.class); private String name; private int id; public MyKey(int id, String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int hashCode() { LOG.debug("Calling hashCode()");
return id; } @Override public String toString() { return "MyKey [name=" + name + ", id=" + id + "]"; } @Override public boolean equals(Object obj) { LOG.debug("Calling equals() for key: " + obj); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyKey other = (MyKey) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-3\src\main\java\com\baeldung\map\advanced\MyKey.java
1
请完成以下Java代码
public static class VariableInfo { protected Map<String, Object> variables; protected Map<String, Object> formVariables; protected String formOutcome; protected FormInfo formInfo; public VariableInfo(Map<String, Object> variables) { this.variables = variables; } public VariableInfo(Map<String, Object> variables, Map<String, Object> formVariables, String formOutcome, FormInfo formInfo) { this(variables); this.formVariables = formVariables; this.formOutcome = formOutcome; this.formInfo = formInfo; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public Map<String, Object> getFormVariables() { return formVariables;
} public void setFormVariables(Map<String, Object> formVariables) { this.formVariables = formVariables; } public String getFormOutcome() { return formOutcome; } public void setFormOutcome(String formOutcome) { this.formOutcome = formOutcome; } public FormInfo getFormInfo() { return formInfo; } public void setFormInfo(FormInfo formInfo) { this.formInfo = formInfo; } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\ChildTaskActivityBehavior.java
1
请完成以下Java代码
public class RescheduleTimerJobCmd implements Command<TimerJobEntity>, Serializable { private static final long serialVersionUID = 1L; private final String timerJobId; private String timeDate; private String timeDuration; private String timeCycle; private String endDate; private String calendarName; public RescheduleTimerJobCmd(String timerJobId, String timeDate, String timeDuration, String timeCycle, String endDate, String calendarName) { if (timerJobId == null) { throw new FlowableIllegalArgumentException("The timer job id is mandatory, but 'null' has been provided."); } int timeValues = Collections.frequency(Arrays.asList(timeDate, timeDuration, timeCycle), null); if (timeValues == 0) { throw new FlowableIllegalArgumentException("A non-null value is required for one of timeDate, timeDuration, or timeCycle"); } else if (timeValues != 2) { throw new FlowableIllegalArgumentException("At most one non-null value can be provided for timeDate, timeDuration, or timeCycle"); } if (endDate != null && timeCycle == null) { throw new FlowableIllegalArgumentException("An end date can only be provided when rescheduling a timer using timeDuration."); } this.timerJobId = timerJobId; this.timeDate = timeDate; this.timeDuration = timeDuration; this.timeCycle = timeCycle; this.endDate = endDate; this.calendarName = calendarName;
} @Override public TimerJobEntity execute(CommandContext commandContext) { TimerEventDefinition ted = new TimerEventDefinition(); ted.setTimeDate(timeDate); ted.setTimeDuration(timeDuration); ted.setTimeCycle(timeCycle); ted.setEndDate(endDate); ted.setCalendarName(calendarName); TimerJobEntity timerJob = TimerUtil.rescheduleTimerJob(timerJobId, ted); return timerJob; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\RescheduleTimerJobCmd.java
1
请在Spring Boot框架中完成以下Java代码
public static class Config { @Min(1) private int replenishRate; @Min(0) private long burstCapacity = 1; @Min(1) private int requestedTokens = 1; public int getReplenishRate() { return replenishRate; } public Config setReplenishRate(int replenishRate) { this.replenishRate = replenishRate; return this; } public long getBurstCapacity() { return burstCapacity; } public Config setBurstCapacity(long burstCapacity) { Assert.isTrue(burstCapacity >= this.replenishRate, "BurstCapacity(" + burstCapacity + ") must be greater than or equal than replenishRate(" + this.replenishRate + ")"); Assert.isTrue(burstCapacity <= REDIS_LUA_MAX_SAFE_INTEGER, "BurstCapacity(" + burstCapacity + ") must not exceed the maximum allowed value of " + REDIS_LUA_MAX_SAFE_INTEGER);
this.burstCapacity = burstCapacity; return this; } public int getRequestedTokens() { return requestedTokens; } public Config setRequestedTokens(int requestedTokens) { this.requestedTokens = requestedTokens; return this; } @Override public String toString() { return new ToStringCreator(this).append("replenishRate", replenishRate) .append("burstCapacity", burstCapacity) .append("requestedTokens", requestedTokens) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\ratelimit\RedisRateLimiter.java
2
请完成以下Java代码
private static final class BPartnerToUpdate { private final int bpartnerId; private final boolean alsoResetCreditStatusFromBPGroup; } private static final WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate>(C_BPartner_UpdateStatsFromBPartner.class) { @Override protected Properties extractCtxFromItem(final BPartnerToUpdate item) { return Env.getCtx(); } @Override protected String extractTrxNameFromItem(final BPartnerToUpdate item) { return ITrx.TRXNAME_ThreadInherited; } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final BPartnerToUpdate item) { return TableRecordReference.of(I_C_BPartner.Table_Name, item.getBpartnerId()); } @Override protected Map<String, Object> extractParametersFromItem(BPartnerToUpdate item) { return ImmutableMap.of(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP, item.isAlsoResetCreditStatusFromBPGroup());
} }; @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName) { // Services final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class); final List<I_C_BPartner> bpartners = retrieveAllItems(I_C_BPartner.class); final boolean alsoSetCreditStatusBaseOnBPGroup = getParameters().getParameterAsBool(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP); for (final I_C_BPartner bpartner : bpartners) { if (alsoSetCreditStatusBaseOnBPGroup) { Services.get(IBPartnerStatsBL.class).resetCreditStatusFromBPGroup(bpartner); } final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(bpartner); bpartnerStatsDAO.updateBPartnerStatistics(stats); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\service\async\spi\impl\C_BPartner_UpdateStatsFromBPartner.java
1
请完成以下Java代码
public MUserDefField getField(AdFieldId AD_Field_ID) { if (AD_Field_ID == null) { return null; } for (MUserDefField field : getFields()) { if (AD_Field_ID.getRepoId() == field.getAD_Field_ID()) { return field; } } return null; } public void apply(GridTabVO vo) {
final String name = getName(); if (!Check.isEmpty(name) && name.length() > 1) vo.setName(name); if (!Check.isEmpty(getDescription())) vo.setDescription(getDescription()); if (!Check.isEmpty(getHelp())) vo.setHelp(getHelp()); // vo.IsSingleRow = this.isSingleRow(); vo.setReadOnly(this.isReadOnly()); // vo.IsDeleteable // vo.IsHighVolume // vo.IsInsertRecord } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MUserDefTab.java
1
请完成以下Java代码
public void setExpressionTextLengthCacheLimit(int expressionTextLengthCacheLimit) { this.expressionTextLengthCacheLimit = expressionTextLengthCacheLimit; } public void addPreDefaultResolver(ELResolver elResolver) { if (this.preDefaultResolvers == null) { this.preDefaultResolvers = new ArrayList<>(); } this.preDefaultResolvers.add(elResolver); } public ELResolver getJsonNodeResolver() { return jsonNodeResolver; } public void setJsonNodeResolver(ELResolver jsonNodeResolver) { // When the bean resolver is modified we need to reset the el resolver this.staticElResolver = null; this.jsonNodeResolver = jsonNodeResolver; } public void addPostDefaultResolver(ELResolver elResolver) { if (this.postDefaultResolvers == null) {
this.postDefaultResolvers = new ArrayList<>(); } this.postDefaultResolvers.add(elResolver); } public void addPreBeanResolver(ELResolver elResolver) { if (this.preBeanResolvers == null) { this.preBeanResolvers = new ArrayList<>(); } this.preBeanResolvers.add(elResolver); } public ELResolver getBeanResolver() { return beanResolver; } public void setBeanResolver(ELResolver beanResolver) { // When the bean resolver is modified we need to reset the el resolver this.staticElResolver = null; this.beanResolver = beanResolver; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\DefaultExpressionManager.java
1
请完成以下Java代码
public IUnlockCommand setRecordByModel(final Object model) { _recordsToUnlock.setRecordByModel(model); return this; } @Override public IUnlockCommand setRecordsByModels(final Collection<?> models) { _recordsToUnlock.setRecordsByModels(models); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final int tableId, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableId, recordId); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final String tableName, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableName, recordId); return this; } @Override public IUnlockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId adPIstanceId)
{ _recordsToUnlock.setRecordsBySelection(modelClass, adPIstanceId); return this; } @Override public final AdTableId getSelectionToUnlock_AD_Table_ID() { return _recordsToUnlock.getSelection_AD_Table_ID(); } @Override public final PInstanceId getSelectionToUnlock_AD_PInstance_ID() { return _recordsToUnlock.getSelection_PInstanceId(); } @Override public final Iterator<TableRecordReference> getRecordsToUnlockIterator() { return _recordsToUnlock.getRecordsIterator(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\UnlockCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class RabbitMQEnqueuer implements EventEnqueuer { @NonNull private static final Logger logger = EventBusConfig.getLogger(RabbitMQEnqueuer.class); @NonNull private final AmqpTemplate amqpTemplate; @NonNull private final RabbitMQDestinationResolver rabbitMQDestinationResolver; @Override public void enqueueDistributedEvent(final Event event, final Topic topic) { final String topicName = topic.getName(); final String amqpExchangeName = rabbitMQDestinationResolver.getAMQPExchangeNameByTopicName(topicName); final String routingKey = amqpExchangeName; // this corresponds to the way we bound our queues to the exchanges in IEventBusQueueConfiguration implementations amqpTemplate.convertAndSend( amqpExchangeName, routingKey, event, getMessagePostProcessor(topic)); logger.debug("Send event; topicName={}; event={}; type={}; timestamp={}, ThreadId={}", topicName, event, topic.getType(), SystemTime.asTimestamp(), Thread.currentThread().getId()); } @Override public void enqueueLocalEvent(final Event event, final Topic topic) { final String queueName = rabbitMQDestinationResolver.getAMQPQueueNameByTopicName(topic.getName()); amqpTemplate.convertAndSend(queueName, event, getMessagePostProcessor(topic));
logger.debug("Send event; topicName={}; event={}; type={}", topic.getName(), event, topic.getType()); } @NonNull private MessagePostProcessor getMessagePostProcessor(@NonNull final Topic topic) { return message -> { final Map<String, Object> headers = message.getMessageProperties().getHeaders(); headers.put(HEADER_SenderId, getSenderId()); headers.put(HEADER_TopicName, topic.getName()); headers.put(HEADER_TopicType, topic.getType()); return message; }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\RabbitMQEnqueuer.java
2
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Phone phone = (Phone)o; return Objects.equals(this.countryCode, phone.countryCode) && Objects.equals(this.number, phone.number); } @Override public int hashCode() { return Objects.hash(countryCode, number); } @Override public String toString()
{ StringBuilder sb = new StringBuilder(); sb.append("class Phone {\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" number: ").append(toIndentedString(number)).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(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\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Phone.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricIdentityLinksByProcessInstanceId(String processInstanceId) { getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByProcInstance(processInstanceId); } @Override public void deleteHistoricIdentityLinksByTaskId(String taskId) { getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByTaskId(taskId); } @Override public void deleteHistoricIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByScopeIdAndScopeType(scopeId, scopeType); } @Override public void bulkDeleteHistoricIdentityLinksForProcessInstanceIds(Collection<String> processInstanceIds) { getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForProcessInstanceIds(processInstanceIds); } @Override public void bulkDeleteHistoricIdentityLinksForTaskIds(Collection<String> taskIds) { getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForTaskIds(taskIds); }
@Override public void bulkDeleteHistoricIdentityLinksByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) { getHistoricIdentityLinkEntityManager().bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType); } @Override public void deleteHistoricProcessIdentityLinksForNonExistingInstances() { getHistoricIdentityLinkEntityManager().deleteHistoricProcessIdentityLinksForNonExistingInstances(); } @Override public void deleteHistoricCaseIdentityLinksForNonExistingInstances() { getHistoricIdentityLinkEntityManager().deleteHistoricCaseIdentityLinksForNonExistingInstances(); } @Override public void deleteHistoricTaskIdentityLinksForNonExistingInstances() { getHistoricIdentityLinkEntityManager().deleteHistoricTaskIdentityLinksForNonExistingInstances(); } public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return configuration.getHistoricIdentityLinkEntityManager(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\HistoricIdentityLinkServiceImpl.java
2
请完成以下Java代码
private void detectDuplicates(final ImportRecordsSelection selection) { final StringBuilder sql = new StringBuilder("SELECT i.I_BankStatement_ID, l.C_BankStatementLine_ID, i.EftTrxID " + "FROM I_BankStatement i, C_BankStatement s, C_BankStatementLine l " + "WHERE i.I_isImported='N' " + "AND s.C_BankStatement_ID=l.C_BankStatement_ID " + "AND i.EftTrxID IS NOT NULL AND " // Concatenate EFT Info + "(l.EftTrxID||l.EftAmt||l.EftStatementLineDate||l.EftValutaDate||l.EftTrxType||l.EftCurrency||l.EftReference||s.EftStatementReference " + "||l.EftCheckNo||l.EftMemo||l.EftPayee||l.EftPayeeAccount) " + "= " + "(i.EftTrxID||i.EftAmt||i.EftStatementLineDate||i.EftValutaDate||i.EftTrxType||i.EftCurrency||i.EftReference||i.EftStatementReference " + "||i.EftCheckNo||i.EftMemo||i.EftPayee||i.EftPayeeAccount) "); final StringBuilder updateSql = new StringBuilder("UPDATE I_Bankstatement " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'Err=Duplicate['||?||']' " + "WHERE I_BankStatement_ID=?") .append(selection.toSqlWhereClause()); PreparedStatement pupdt = DB.prepareStatement(updateSql.toString(), ITrx.TRXNAME_ThreadInherited); PreparedStatement pstmtDuplicates = null; int no = 0; try { pstmtDuplicates = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_ThreadInherited); ResultSet rs = pstmtDuplicates.executeQuery(); while (rs.next()) { String info = "Line_ID=" + rs.getInt(2) // l.C_BankStatementLine_ID + ",EDTTrxID=" + rs.getString(3); // i.EftTrxID pupdt.setString(1, info); pupdt.setInt(2, rs.getInt(1)); // i.I_BankStatement_ID pupdt.executeUpdate(); no++; }
rs.close(); pstmtDuplicates.close(); pupdt.close(); rs = null; pstmtDuplicates = null; pupdt = null; } catch (Exception e) { logger.error("DetectDuplicates {}", e.getMessage()); } logger.warn("Duplicates= {}", no); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\impexp\BankStatementImportTableSqlUpdater.java
1
请完成以下Java代码
public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public Date getTimeStamp() { return timeStamp; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Override public String getCaseInstanceId() { return caseInstanceId; } @Override public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @Override public String getCaseDefinitionId() { return caseDefinitionId; } @Override public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @Override public String getElementId() {
return elementId; } @Override public void setElementId(String elementId) { this.elementId = elementId; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricMilestoneInstanceEntityImpl.java
1
请完成以下Java代码
public OAuth2User getPrincipal() { return this.principal; } @Override public Object getCredentials() { return ""; } /** * Returns the {@link ClientRegistration client registration}. * @return the {@link ClientRegistration} */ public ClientRegistration getClientRegistration() { return this.clientRegistration; } /** * Returns the {@link OAuth2AuthorizationExchange authorization exchange}. * @return the {@link OAuth2AuthorizationExchange} */ public OAuth2AuthorizationExchange getAuthorizationExchange() { return this.authorizationExchange;
} /** * Returns the {@link OAuth2AccessToken access token}. * @return the {@link OAuth2AccessToken} */ public OAuth2AccessToken getAccessToken() { return this.accessToken; } /** * Returns the {@link OAuth2RefreshToken refresh token}. * @return the {@link OAuth2RefreshToken} * @since 5.1 */ public @Nullable OAuth2RefreshToken getRefreshToken() { return this.refreshToken; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginAuthenticationToken.java
1
请完成以下Java代码
public static <V> LinkedList<ResultTerm<V>> segmentReverseOrder(String text, AhoCorasickDoubleArrayTrie<V> trie) { return segmentReverseOrder(text.toCharArray(), trie); } /** * 逆向最长分词,合并未知语素 * @param charArray 文本 * @param trie 自动机 * @param <V> 类型 * @return 结果链表 */ public static <V> LinkedList<ResultTerm<V>> segmentReverseOrder(final char[] charArray, AhoCorasickDoubleArrayTrie<V> trie) { LinkedList<ResultTerm<V>> termList = new LinkedList<ResultTerm<V>>(); final ResultTerm<V>[] wordNet = new ResultTerm[charArray.length + 1]; trie.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<V>() { @Override public void hit(int begin, int end, V value) { if (wordNet[end] == null || wordNet[end].word.length() < end - begin) { wordNet[end] = new ResultTerm<V>(new String(charArray, begin, end - begin), value, begin); } } }); for (int i = charArray.length; i > 0;) { if (wordNet[i] == null) { StringBuilder sbTerm = new StringBuilder();
int offset = i - 1; byte preCharType = CharType.get(charArray[offset]); while (i > 0 && wordNet[i] == null && CharType.get(charArray[i - 1]) == preCharType) { sbTerm.append(charArray[i - 1]); preCharType = CharType.get(charArray[i - 1]); --i; } termList.addFirst(new ResultTerm<V>(sbTerm.reverse().toString(), null, offset)); } else { termList.addFirst(wordNet[i]); i -= wordNet[i].word.length(); } } return termList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\CommonAhoCorasickSegmentUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class DDOrderDeletedEventHandler implements MaterialEventHandler<DDOrderDeletedEvent> { private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); private final MainDataRequestHandler mainDataRequestHandler; private final DDOrderDetailRequestHandler ddOrderDetailRequestHandler; private final CandidateRepositoryRetrieval candidateRepositoryRetrieval; private final CandidateChangeService candidateChangeService; public DDOrderDeletedEventHandler( @NonNull final MainDataRequestHandler mainDataRequestHandler, @NonNull final DDOrderDetailRequestHandler ddOrderDetailRequestHandler, @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval, @NonNull final CandidateChangeService candidateChangeService) { this.mainDataRequestHandler = mainDataRequestHandler; this.ddOrderDetailRequestHandler = ddOrderDetailRequestHandler; this.candidateRepositoryRetrieval = candidateRepositoryRetrieval; this.candidateChangeService = candidateChangeService; } @Override public Collection<Class<? extends DDOrderDeletedEvent>> getHandledEventType() { return ImmutableList.of(DDOrderDeletedEvent.class); } @Override public void handleEvent(final DDOrderDeletedEvent event) { final OrgId orgId = event.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); for (final DDOrderLine ddOrderLine : event.getDdOrder().getLines()) { final DDOrderMainDataHandler mainDataUpdater = DDOrderMainDataHandler.builder() .ddOrderDetailRequestHandler(ddOrderDetailRequestHandler)
.mainDataRequestHandler(mainDataRequestHandler) .abstractDDOrderEvent(event) .ddOrderLine(ddOrderLine) .orgZone(timeZone) .build(); mainDataUpdater.handleDelete(); } final int ddOrderId = event.getDdOrder().getDdOrderId(); event.getDdOrder().getLines().forEach(line -> deleteCandidates(ddOrderId, line)); } private void deleteCandidates(final int ddOrderId, @NonNull final DDOrderLine ddOrderLine) { final CandidatesQuery query = CandidatesQuery .builder() .distributionDetailsQuery(DistributionDetailsQuery.builder() .ddOrderId(ddOrderId) .ddOrderLineId(ddOrderLine.getDdOrderLineId()) .build()) .build(); candidateRepositoryRetrieval.retrieveOrderedByDateAndSeqNo(query) .forEach(candidateChangeService::onCandidateDelete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderDeletedEventHandler.java
2
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSingleSelectedInvoiceId().isPresent()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selected Invoice"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final I_C_Invoice invoice = Services.get(IInvoiceDAO.class).getByIdInTrx(getSingleSelectedInvoiceId().get()); final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID) .setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bPartnerId) .build()) .getViewId(); getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.getViewId()) .target(ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private Optional<InvoiceId> getSingleSelectedInvoiceId() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); return selectedRowIds.isSingleDocumentId() ? Optional.of(selectedRowIds.getSingleDocumentId().toId(InvoiceId::ofRepoId)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_C_Invoice_View.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer { private final SecurityConfigurationProperties properties; SecurityConfiguration(SecurityConfigurationProperties properties) { this.properties = properties; } @Override public void configure(WebSecurity web) { web.ignoring().antMatchers(POST, "/users", "/users/login"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.cors(); http.formLogin().disable(); http.logout().disable(); http.addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); http.authorizeRequests() .antMatchers(GET, "/profiles/*").permitAll() .antMatchers(GET, "/articles/**").permitAll() .antMatchers(GET, "/tags/**").permitAll() .anyRequest().authenticated(); } @Bean JWTAuthenticationProvider jwtAuthenticationProvider(JWTDeserializer jwtDeserializer) { return new JWTAuthenticationProvider(jwtDeserializer); } @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "HEAD", "POST", "DELETE", "PUT")
.allowedOrigins(properties.getAllowedOrigins().toArray(new String[0])) .allowedHeaders("*") .allowCredentials(true); } } @ConstructorBinding @ConfigurationProperties("security") class SecurityConfigurationProperties { private final List<String> allowedOrigins; SecurityConfigurationProperties(List<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public List<String> getAllowedOrigins() { return allowedOrigins; } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\security\SecurityConfiguration.java
2
请完成以下Java代码
public void setFilterType (final java.lang.String FilterType) { set_Value (COLUMNNAME_FilterType, FilterType); } @Override public java.lang.String getFilterType() { return get_ValueAsString(COLUMNNAME_FilterType); } @Override public org.compiere.model.I_MobileUI_UserProfile_Picking getMobileUI_UserProfile_Picking() { return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class); } @Override public void setMobileUI_UserProfile_Picking(final org.compiere.model.I_MobileUI_UserProfile_Picking MobileUI_UserProfile_Picking) { set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class, MobileUI_UserProfile_Picking); } @Override public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID) { if (MobileUI_UserProfile_Picking_ID < 1) set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null); else set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID); } @Override public int getMobileUI_UserProfile_Picking_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID); } @Override public void setPickingProfile_Filter_ID (final int PickingProfile_Filter_ID) { if (PickingProfile_Filter_ID < 1) set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, null); else set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, PickingProfile_Filter_ID);
} @Override public int getPickingProfile_Filter_ID() { return get_ValueAsInt(COLUMNNAME_PickingProfile_Filter_ID); } @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.adempiere.adempiere\base\src\main\java-gen\de\metas\picking\model\X_PickingProfile_Filter.java
1
请完成以下Java代码
public Builder noSorting() { _noSorting = true; _orderBys = null; return this; } public boolean isNoSorting() { return _noSorting; } public Builder addOrderBy(@NonNull final DocumentQueryOrderBy orderBy) { Check.assume(!_noSorting, "sorting not disabled for {}", this); if (_orderBys == null) { _orderBys = new ArrayList<>(); } _orderBys.add(orderBy); return this; } public Builder setOrderBys(final DocumentQueryOrderByList orderBys) { if (orderBys == null || orderBys.isEmpty()) { _orderBys = null; } else { _orderBys = new ArrayList<>(orderBys.toList()); } return this; } private DocumentQueryOrderByList getOrderBysEffective() { return _noSorting ? DocumentQueryOrderByList.EMPTY : DocumentQueryOrderByList.ofList(_orderBys); } public Builder setFirstRow(final int firstRow) {
this.firstRow = firstRow; return this; } public Builder setPageLength(final int pageLength) { this.pageLength = pageLength; return this; } public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier) { this.existingDocumentsSupplier = existingDocumentsSupplier; return this; } public Builder setChangesCollector(IDocumentChangesCollector changesCollector) { this.changesCollector = changesCollector; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java
1
请完成以下Spring Boot application配置
# database init, supports mysql too database=h2 spring.sql.init.schema-locations=classpath*:db/${database}/schema.sql spring.sql.init.data-locations=classpath*:db/${database}/data.sql # Web spring.thymeleaf.mode=HTML # JPA spring.jpa.hibernate.ddl-auto=none spring.jpa.open-in-view=false spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategySnakeCaseImpl # Internationalization spring.messages.basename=messages/messages # Actuator management.endpoints.web.exposure.include=* # Logging logging.lev
el.org.springframework=INFO # logging.level.org.springframework.web=DEBUG # logging.level.org.springframework.context.annotation=TRACE # Maximum time static resources should be cached spring.web.resources.cache.cachecontrol.max-age=12h
repos\spring-petclinic-main\src\main\resources\application.properties
2
请完成以下Java代码
public Execution getExecution() { return execution; } public void setExecution(Execution execution) { this.execution = execution; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } @SuppressWarnings("unchecked") public <T extends TypedValue> T getVariable(String variableName) { TypedValue value = cachedVariables.getValueTyped(variableName); if(value == null) { if(execution != null) { value = runtimeService.getVariableTyped(execution.getId(), variableName); cachedVariables.put(variableName, value); } } return (T) value; } public void setVariable(String variableName, Object value) { cachedVariables.put(variableName, value); } public VariableMap getCachedVariables() { return cachedVariables; } @SuppressWarnings("unchecked") public <T extends TypedValue> T getVariableLocal(String variableName) { TypedValue value = cachedVariablesLocal.getValueTyped(variableName); if (value == null) { if (task != null) { value = taskService.getVariableLocalTyped(task.getId(), variableName); cachedVariablesLocal.put(variableName, value); } else if (execution != null) { value = runtimeService.getVariableLocalTyped(execution.getId(), variableName); cachedVariablesLocal.put(variableName, value); } } return (T) value; } public void setVariableLocal(String variableName, Object value) { if (execution == null && task == null) {
throw new ProcessEngineCdiException("Cannot set a local cached variable: neither a Task nor an Execution is associated."); } cachedVariablesLocal.put(variableName, value); } public VariableMap getCachedVariablesLocal() { return cachedVariablesLocal; } public void flushVariableCache() { if(task != null) { taskService.setVariablesLocal(task.getId(), cachedVariablesLocal); taskService.setVariables(task.getId(), cachedVariables); } else if(execution != null) { runtimeService.setVariablesLocal(execution.getId(), cachedVariablesLocal); runtimeService.setVariables(execution.getId(), cachedVariables); } else { throw new ProcessEngineCdiException("Cannot flush variable cache: neither a Task nor an Execution is associated."); } // clear variable cache after flush cachedVariables.clear(); cachedVariablesLocal.clear(); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\ScopedAssociation.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonBPartnerProduct { @Nullable @JsonProperty("MKREDID") String bpartnerId; @JsonProperty("STDKRED") boolean currentVendor; @JsonProperty("LIEFERANTENFREIGABE") boolean isExcludedFromPurchase; @JsonProperty("INAKTIV") boolean isActive; @Nullable @JsonProperty("METASFRESHID") String bPartnerMetasfreshId; @Nullable @JsonProperty("ROHKREDDATA") JsonBPartnerProductAdditionalInfo attachmentAdditionalInfos; @Builder
public JsonBPartnerProduct( @JsonProperty("MKREDID") final @Nullable String bpartnerId, @JsonProperty("STDKRED") final @NonNull Integer currentVendor, @JsonProperty("LIEFERANTENFREIGABE") final int approvedForPurchase, @JsonProperty("INAKTIV") final int inactive, @JsonProperty("METASFRESHID") final @Nullable String bPartnerMetasfreshId, @JsonProperty("ROHKREDDATA") final @Nullable JsonBPartnerProductAdditionalInfo attachmentAdditionalInfos) { this.bpartnerId = bpartnerId; this.currentVendor = currentVendor == 1; this.isExcludedFromPurchase = approvedForPurchase != 1; this.isActive = inactive != 1; this.bPartnerMetasfreshId = bPartnerMetasfreshId; this.attachmentAdditionalInfos = attachmentAdditionalInfos; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonPOJOBuilder(withPrefix = "") static class JsonBPartnerProductBuilder { } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\api\model\JsonBPartnerProduct.java
2
请完成以下Java代码
public void setConfidentialType (java.lang.String ConfidentialType) { set_Value (COLUMNNAME_ConfidentialType, ConfidentialType); } /** Get Vertraulichkeit. @return Type of Confidentiality */ @Override public java.lang.String getConfidentialType () { return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType); } /** * ModeratorStatus AD_Reference_ID=396 * Reference name: CM_ChatEntry ModeratorStatus */ public static final int MODERATORSTATUS_AD_Reference_ID=396; /** Nicht angezeigt = N */ public static final String MODERATORSTATUS_NichtAngezeigt = "N"; /** Veröffentlicht = P */ public static final String MODERATORSTATUS_Veroeffentlicht = "P"; /** To be reviewed = R */ public static final String MODERATORSTATUS_ToBeReviewed = "R"; /** Verdächtig = S */ public static final String MODERATORSTATUS_Verdaechtig = "S"; /** Set Moderation Status. @param ModeratorStatus Status of Moderation */ @Override public void setModeratorStatus (java.lang.String ModeratorStatus) { set_Value (COLUMNNAME_ModeratorStatus, ModeratorStatus);
} /** Get Moderation Status. @return Status of Moderation */ @Override public java.lang.String getModeratorStatus () { return (java.lang.String)get_Value(COLUMNNAME_ModeratorStatus); } /** Set Betreff. @param Subject Mail Betreff */ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatEntry.java
1
请完成以下Java代码
public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setM_ShipmentSchedule_QtyPicked_ID (final int M_ShipmentSchedule_QtyPicked_ID) { if (M_ShipmentSchedule_QtyPicked_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_QtyPicked_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_QtyPicked_ID, M_ShipmentSchedule_QtyPicked_ID); } @Override public int getM_ShipmentSchedule_QtyPicked_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_QtyPicked_ID); } @Override public void setM_TU_HU_ID (final int M_TU_HU_ID) { if (M_TU_HU_ID < 1) set_Value (COLUMNNAME_M_TU_HU_ID, null); else set_Value (COLUMNNAME_M_TU_HU_ID, M_TU_HU_ID); } @Override public int getM_TU_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyDeliveredCatch (final @Nullable BigDecimal QtyDeliveredCatch) { set_Value (COLUMNNAME_QtyDeliveredCatch, QtyDeliveredCatch); } @Override public BigDecimal getQtyDeliveredCatch() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredCatch); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyLU (final @Nullable BigDecimal QtyLU) { set_Value (COLUMNNAME_QtyLU, QtyLU); } @Override public BigDecimal getQtyLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyPicked (final BigDecimal QtyPicked) { set_Value (COLUMNNAME_QtyPicked, QtyPicked); } @Override public BigDecimal getQtyPicked() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final @Nullable BigDecimal QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public BigDecimal getQtyTU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_QtyPicked.java
1
请完成以下Java代码
public DataEntryRecord copyAsImmutable() { if (readOnly) { return this; } else { return new DataEntryRecord(this, true); } } private void assertReadWrite() { if (readOnly) { throw new AdempiereException("Changing readonly instance is not allowed: " + this); } } void setId(@NonNull final DataEntryRecordId id) { this.id = Optional.of(id); } /** * @return {@code true} if the given value is different from the previous one. */ public boolean setRecordField( @NonNull final DataEntryFieldId dataEntryFieldId, @NonNull final UserId updatedBy, @Nullable final Object value) { assertReadWrite(); final DataEntryRecordField<?> previousFieldVersion = fields.get(dataEntryFieldId); final Object previousValue = previousFieldVersion == null ? null : previousFieldVersion.getValue(); final boolean valueChanged = !Objects.equals(previousValue, value); if (!valueChanged) { return false; } final ZonedDateTime updated = ZonedDateTime.now(); final CreatedUpdatedInfo createdUpdatedInfo; if (previousFieldVersion == null) { createdUpdatedInfo = CreatedUpdatedInfo.createNew(updatedBy, updated); } else { createdUpdatedInfo = previousFieldVersion.getCreatedUpdatedInfo().updated(updatedBy, updated); } final DataEntryRecordField<?> dataEntryRecordField = value != null ? DataEntryRecordField.createDataEntryRecordField(dataEntryFieldId, createdUpdatedInfo, value) : DataEntryRecordFieldString.of(dataEntryFieldId, createdUpdatedInfo, null); fields.put(dataEntryFieldId, dataEntryRecordField); return true; } public boolean isEmpty() { return fields.isEmpty(); } public ImmutableList<DataEntryRecordField<?>> getFields() { return ImmutableList.copyOf(fields.values()); } public Optional<ZonedDateTime> getCreatedValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getCreated);
} public Optional<UserId> getCreatedByValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getCreatedBy); } public Optional<ZonedDateTime> getUpdatedValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getUpdated); } public Optional<UserId> getUpdatedByValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getUpdatedBy); } public Optional<CreatedUpdatedInfo> getCreatedUpdatedInfo(@NonNull final DataEntryFieldId fieldId) { return getOptional(fieldId) .map(DataEntryRecordField::getCreatedUpdatedInfo); } public Optional<Object> getFieldValue(@NonNull final DataEntryFieldId fieldId) { return getOptional(fieldId) .map(DataEntryRecordField::getValue); } private Optional<DataEntryRecordField<?>> getOptional(@NonNull final DataEntryFieldId fieldId) { return Optional.ofNullable(fields.get(fieldId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecord.java
1
请在Spring Boot框架中完成以下Java代码
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { TextMessage textMessage = (TextMessage)message; String payload = textMessage.getPayload(); LOG.info("WS Terminal message: {} message={}", session.getId(), payload); session.sendMessage(new TextMessage("Echo: " + payload)); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { LOG.info("WS Terminal transport error: {}", session.getId()); this.sessions.remove(session.getId(), session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
LOG.info("WS Terminal connection closed: {}", session.getId()); this.sessions.remove(session.getId(), session); } @Override public boolean supportsPartialMessages() { return false; } @PreDestroy public void close() throws Exception { LOG.info("WS Terminal shutdown"); this.executorService.shutdownNow(); } }
repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSTerminalHandler.java
2
请完成以下Java代码
private DocumentFilterDescriptor createIsCustomerFilterDescriptor() { return DocumentFilterDescriptor.builder() .setFilterId(FILTERID_IsCustomer) .setFrequentUsed(true) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_IsCustomer) .displayName(Services.get(IMsgBL.class).translatable(PARAM_IsCustomer)) .widgetType(DocumentFieldWidgetType.YesNo)) .build(); } private DocumentFilterDescriptor createIsVendorFilterDescriptor() { return DocumentFilterDescriptor.builder() .setFilterId(FILTERID_IsVendor) .setFrequentUsed(true) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_IsVendor) .displayName(Services.get(IMsgBL.class).translatable(PARAM_IsVendor)) .widgetType(DocumentFieldWidgetType.YesNo)) .build(); } public static Predicate<PricingConditionsRow> isEditableRowOrMatching(final DocumentFilterList filters) { if (filters.isEmpty()) { return Predicates.alwaysTrue(); } final boolean showCustomers = filters.getParamValueAsBoolean(FILTERID_IsCustomer, PARAM_IsCustomer, false); final boolean showVendors = filters.getParamValueAsBoolean(FILTERID_IsVendor, PARAM_IsVendor, false); final boolean showAll = !showCustomers && !showVendors; if (showAll) { return Predicates.alwaysTrue(); } return row -> row.isEditable() || ((showCustomers && row.isCustomer()) || (showVendors && row.isVendor())); } public DocumentFilterList extractFilters(@NonNull final JSONFilterViewRequest filterViewRequest) { return filterViewRequest.getFiltersUnwrapped(getFilterDescriptorsProvider());
} public DocumentFilterList extractFilters(@NonNull final CreateViewRequest request) { return request.isUseAutoFilters() ? getDefaultFilters() : request.getFiltersUnwrapped(getFilterDescriptorsProvider()); } private DocumentFilterList getDefaultFilters() { if (defaultFilters == null) { final DocumentFilter isCustomer = DocumentFilter.singleParameterFilter(FILTERID_IsCustomer, PARAM_IsCustomer, Operator.EQUAL, true); defaultFilters = DocumentFilterList.of(isCustomer); } return defaultFilters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFilters.java
1
请完成以下Java代码
public void setIsOneTime (final boolean IsOneTime) { set_Value (COLUMNNAME_IsOneTime, IsOneTime); } @Override public boolean isOneTime() { return get_ValueAsBoolean(COLUMNNAME_IsOneTime); } @Override public void setIsRemitTo (final boolean IsRemitTo) { set_Value (COLUMNNAME_IsRemitTo, IsRemitTo); } @Override public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsReplicationLookupDefault (final boolean IsReplicationLookupDefault) { set_Value (COLUMNNAME_IsReplicationLookupDefault, IsReplicationLookupDefault); } @Override public boolean isReplicationLookupDefault() { return get_ValueAsBoolean(COLUMNNAME_IsReplicationLookupDefault); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setIsShipToDefault (final boolean IsShipToDefault) { set_Value (COLUMNNAME_IsShipToDefault, IsShipToDefault); } @Override public boolean isShipToDefault() { return get_ValueAsBoolean(COLUMNNAME_IsShipToDefault); } @Override 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 setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location_QuickInput.java
1
请在Spring Boot框架中完成以下Java代码
public final class OAuth2AuthorizationServerJwtAutoConfiguration { @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) @ConditionalOnMissingBean JWKSource<SecurityContext> jwkSource() { RSAKey rsaKey = getRsaKey(); JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static RSAKey getRsaKey() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); return rsaKey; } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); }
return keyPair; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(JwtDecoder.class) static class JwtDecoderConfiguration { @Bean @ConditionalOnMissingBean JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-authorization-server\src\main\java\org\springframework\boot\security\oauth2\server\authorization\autoconfigure\servlet\OAuth2AuthorizationServerJwtAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getWithTransactionTimeout(@RequestParam String title) { return getAuthor(title); } private final TimeLimiter ourTimeLimiter = TimeLimiter.of(TimeLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(500)) .build()); @GetMapping("/author/resilience4j") public Callable<String> getWithResilience4jTimeLimiter(@RequestParam String title) { return TimeLimiter.decorateFutureSupplier(ourTimeLimiter, () -> CompletableFuture.supplyAsync(() -> getAuthor(title))); } @GetMapping("/author/mvc-request-timeout") public Callable<String> getWithMvcRequestTimeout(@RequestParam String title) { return () -> getAuthor(title); } @GetMapping("/author/webclient") public String getWithWebClient(@RequestParam String title) { return webClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build())
.retrieve() .bodyToMono(String.class) .block(); } @GetMapping("/author/restclient") public String getWithRestClient(@RequestParam String title) { return restClient.get() .uri(uriBuilder -> uriBuilder.path("/author/transactional") .queryParam("title", title) .build()) .retrieve() .body(String.class); } private String getAuthor(String title) { bookRepository.wasteTime(); return bookRepository.findById(title) .map(Book::getAuthor) .orElse("No book found for this title."); } }
repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requesttimeout\RequestTimeoutRestController.java
2
请完成以下Java代码
public class AccountSchemeName1Choice { @XmlElement(name = "Cd") protected String cd; @XmlElement(name = "Prtry") protected String prtry; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value;
} /** * Gets the value of the prtry property. * * @return * possible object is * {@link String } * */ public String getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link String } * */ public void setPrtry(String value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AccountSchemeName1Choice.java
1
请完成以下Spring Boot application配置
spring: datasource: driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver url: jdbc:shardingsphere:classpath:sharding.yml jpa: properties: hibernate: d
ialect: org.hibernate.dialect.MySQL8Dialect hibernate: ddl-auto: create-drop
repos\springboot-demo-master\sharding-jdbc\src\main\resources\application.yml
2
请完成以下Java代码
public HistoricExternalTaskLogQuery orderByProcessDefinitionId() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessDefinitionKey() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_KEY); return this; } @Override public HistoricExternalTaskLogQuery orderByTenantId() { orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID); return this; } // results ////////////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsCountByQueryCriteria(this); } @Override public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) { checkQueryOk();
return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsByQueryCriteria(this, page); } // getters & setters //////////////////////////////////////////////////////////// protected void setState(ExternalTaskState state) { this.state = state; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class); //Send an user System.out.println("Sending an user message."); jmsTemplate.convertAndSend("userQueue", new User("rameshfadatare@gmail.com", 5d, true)); logger.info("Waiting for user and confirmation ..."); System.in.read(); context.close(); } @Bean // Serialize message content to json using TextMessage
public MessageConverter jacksonJmsMessageConverter() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setTargetType(MessageType.TEXT); converter.setTypeIdPropertyName("_type"); return converter; } @Bean public JmsListenerContainerFactory<?> connectionFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); // This provides all boot's default to this factory, including the message converter configurer.configure(factory, connectionFactory); // You could still override some of Boot's default if necessary. return factory; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jms-activemq\src\main\java\net\alanbinu\springboot\Application.java
1
请完成以下Java代码
private void validateState() { if (OrderStatus.COMPLETED.equals(status)) { throw new DomainException("The order is in completed state."); } } private void validateProduct(final Product product) { if (product == null) { throw new DomainException("The product cannot be null."); } } public UUID getId() { return id; } public OrderStatus getStatus() { return status; } public BigDecimal getPrice() { return price; } public List<OrderItem> getOrderItems() { return Collections.unmodifiableList(orderItems);
} @Override public int hashCode() { return Objects.hash(id, orderItems, price, status); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Order)) return false; Order other = (Order) obj; return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; } private Order() { } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\Order.java
1
请完成以下Java代码
private SourceDocumentLine createSourceDocumentLine(@NonNull final I_C_OrderLine orderLineRecord, @NonNull final SOTrx soTrx) { final IProductDAO productsRepo = Services.get(IProductDAO.class); final ProductId productId = ProductId.ofRepoId(orderLineRecord.getM_Product_ID()); final ProductCategoryId productCategoryId = productsRepo.retrieveProductCategoryByProductId(productId); final Money priceEntered = Money.of(orderLineRecord.getPriceEntered(), CurrencyId.ofRepoId(orderLineRecord.getC_Currency_ID())); return SourceDocumentLine.builder() .orderLineId(OrderLineId.ofRepoIdOrNull(orderLineRecord.getC_OrderLine_ID())) .soTrx(soTrx) .bpartnerId(BPartnerId.ofRepoId(orderLineRecord.getC_BPartner_ID())) .productId(productId) .productCategoryId(productCategoryId) .priceEntered(priceEntered) .discount(Percent.of(orderLineRecord.getDiscount())) .paymentTermId(PaymentTermId.ofRepoIdOrNull(orderLineRecord.getC_PaymentTerm_Override_ID())) .pricingConditionsBreakId(PricingConditionsBreakId.ofOrNull(orderLineRecord.getM_DiscountSchema_ID(), orderLineRecord.getM_DiscountSchemaBreak_ID())) .build(); } private static class OrderLineBasePricingSystemPriceCalculator implements BasePricingSystemPriceCalculator { private final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class); private final I_C_OrderLine orderLine;
private final ConcurrentHashMap<PricingConditionsBreak, Money> basePricesCache = new ConcurrentHashMap<>(); public OrderLineBasePricingSystemPriceCalculator(@NonNull final I_C_OrderLine orderLine) { this.orderLine = orderLine; } @Override public Money calculate(final BasePricingSystemPriceCalculatorRequest request) { final PricingConditionsBreak pricingConditionsBreak = request.getPricingConditionsBreak(); return basePricesCache.computeIfAbsent(pricingConditionsBreak, this::calculate); } private Money calculate(final PricingConditionsBreak pricingConditionsBreak) { final IPricingResult pricingResult = orderLineBL.computePrices(OrderLinePriceUpdateRequest.builder() .orderLine(orderLine) .pricingConditionsBreakOverride(pricingConditionsBreak) .resultUOM(ResultUOM.PRICE_UOM_IF_ORDERLINE_IS_NEW) .build()); return Money.of(pricingResult.getPriceStd(), pricingResult.getCurrencyId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\OrderLinePricingConditionsViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public AuthenticationManager authManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(authProvider()) .build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll() .requestMatchers("/protectedbyrole").hasRole("USER") .requestMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE")) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login").failureUrl("/login?error=true").permitAll()) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(myLogoutSuccessHandler).invalidateHttpSession(false) .logoutSuccessUrl("/logout.html?logSucc=true").deleteCookies("JSESSIONID").permitAll());
return http.build(); } @Bean public DaoAuthenticationProvider authProvider() { final CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider(userRepository, userDetailsService); authProvider.setPasswordEncoder(encoder()); return authProvider; } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(11); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\config\SecurityConfig.java
2
请完成以下Java代码
public class Order { //下单日期 private Date bookingDate; //订单原价金额 private int amout; private int score; private Person person; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Date getBookingDate() { return bookingDate; } public void setBookingDate(Date bookingDate) { this.bookingDate = bookingDate; }
public int getAmout() { return amout; } public void setAmout(int amout) { this.amout = amout; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\domain\model\Order.java
1
请完成以下Java代码
public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_Location getOrg_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class); } @Override public void setOrg_Location(org.compiere.model.I_C_Location Org_Location) { set_ValueFromPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class, Org_Location); } /** Set Org Address. @param Org_Location_ID Organization Location/Address */ @Override public void setOrg_Location_ID (int Org_Location_ID) { if (Org_Location_ID < 1) set_ValueNoCheck (COLUMNNAME_Org_Location_ID, null); else set_ValueNoCheck (COLUMNNAME_Org_Location_ID, Integer.valueOf(Org_Location_ID)); } /** Get Org Address. @return Organization Location/Address */ @Override public int getOrg_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Org_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { set_ValueNoCheck (COLUMNNAME_Phone, Phone); } /** Get Telefon. @return Beschreibt eine Telefon Nummer
*/ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Steuer-ID. @param TaxID Tax Identification */ @Override public void setTaxID (java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } /** Get Steuer-ID. @return Tax Identification */ @Override public java.lang.String getTaxID () { return (java.lang.String)get_Value(COLUMNNAME_TaxID); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java
1
请完成以下Java代码
public class CamundaBpmRunLogger extends BaseLogger { public static final String PROJECT_CODE = "RUN"; public static final String PROJECT_ID = "CR"; public static final String PACKAGE = "org.camunda.bpm.run"; public static final CamundaBpmRunLogger LOG = createLogger(CamundaBpmRunLogger.class, PROJECT_CODE, PACKAGE, PROJECT_ID); public void processEnginePluginRegistered(String pluginClass) { logInfo("001", "The process engine plugin '{}' was registered with the " + "Camunda Run process engine.", pluginClass); } public ProcessEngineException failedProcessEnginePluginInstantiation(String pluginClass, Exception e) { return new ProcessEngineException( exceptionMessage("002",
"Unable to register the process engine plugin '{}'. " + "Please ensure that the correct plugin class is configured in your " + "YAML configuration file, and that the class is present on the " + "classpath. More details: {}", pluginClass, e.getMessage(), e)); } public ProcessEngineException pluginPropertyNotFound(String pluginName, String propertyName, Exception e) { return new ProcessEngineException( exceptionMessage("003", "Please check the configuration options for plugin '{}'. " + "Some configuration parameters could not be found. More details: {}", pluginName, e.getMessage(), e)); } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\utils\CamundaBpmRunLogger.java
1
请完成以下Java代码
public int getSerializerIndex(TypedValueSerializer<?> serializer) { return serializerList.indexOf(serializer); } public int getSerializerIndexByName(String serializerName) { TypedValueSerializer<?> serializer = serializerMap.get(serializerName); if(serializer != null) { return getSerializerIndex(serializer); } else { return -1; } } public VariableSerializers removeSerializer(TypedValueSerializer<?> serializer) { serializerList.remove(serializer); serializerMap.remove(serializer.getName()); return this; } public VariableSerializers join(VariableSerializers other) { DefaultVariableSerializers copy = new DefaultVariableSerializers(); // "other" serializers override existing ones if their names match for (TypedValueSerializer<?> thisSerializer : serializerList) { TypedValueSerializer<?> serializer = other.getSerializerByName(thisSerializer.getName()); if (serializer == null) {
serializer = thisSerializer; } copy.addSerializer(serializer); } // add all "other" serializers that did not exist before to the end of the list for (TypedValueSerializer<?> otherSerializer : other.getSerializers()) { if (!copy.serializerMap.containsKey(otherSerializer.getName())) { copy.addSerializer(otherSerializer); } } return copy; } public List<TypedValueSerializer<?>> getSerializers() { return new ArrayList<TypedValueSerializer<?>>(serializerList); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\DefaultVariableSerializers.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http. authorizeRequests().antMatchers("/**").permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("123456").roles("USER"); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
@Bean public PasswordEncoder passwordEncoder() { return new PasswordEncoder() { @Override public String encode(CharSequence charSequence) { return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return Objects.equals(charSequence.toString(),s); } }; } }
repos\SpringBootLearning-master (1)\springboot-security-oauth2-jwt\jwt-authserver\src\main\java\com\gf\config\WebSecurityConfig.java
2
请完成以下Java代码
public void destroy(final IDocOutboundProducerService producerService) { final String tableName = getTableName(); modelValidationEngine.removeModelChange(tableName, this); modelValidationEngine.removeDocValidate(tableName, this); } // NOTE: keep in sync with destroy method @Override public void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { m_AD_Client_ID = client.getAD_Client_ID(); } final String tableName = getTableName(); if (isDocument()) { engine.addDocValidate(tableName, this); } else { engine.addModelChange(tableName, this); } } @Override public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { return null; // nothing } @Override public String modelChange(final PO po, final int type) { if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE) { if (isDocument()) { if (!acceptDocument(po)) { return null; } if (po.is_ValueChanged(IDocument.COLUMNNAME_DocStatus) && Services.get(IDocumentBL.class).isDocumentReversedOrVoided(po)) { voidDocOutbound(po); } } if (isJustProcessed(po, type)) { createDocOutbound(po); } } return null; } @Override public String docValidate(@NonNull final PO po, final int timing) { Check.assume(isDocument(), "PO '{}' is a document", po);
if (!acceptDocument(po)) { return null; } if (timing == ModelValidator.TIMING_AFTER_COMPLETE && !Services.get(IDocumentBL.class).isReversalDocument(po)) { createDocOutbound(po); } if (timing == ModelValidator.TIMING_AFTER_VOID || timing == ModelValidator.TIMING_AFTER_REVERSEACCRUAL || timing == ModelValidator.TIMING_AFTER_REVERSECORRECT) { voidDocOutbound(po); } return null; } /** * @return true if the given PO was just processed */ private boolean isJustProcessed(final PO po, final int changeType) { if (!po.isActive()) { return false; } final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW; final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed); final boolean processedColumnAvailable = idxProcessed > 0; final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true; if (processedColumnAvailable) { if (isNew) { return processed; } else if (po.is_ValueChanged(idxProcessed)) { return processed; } else { return false; } } else // Processed column is not available { // If is not available, we always consider the record as processed right after it was created // This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters) return isNew; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java
1
请完成以下Java代码
static void initCipher(Cipher cipher, int mode, SecretKey secretKey, @Nullable AlgorithmParameterSpec parameterSpec) { try { if (parameterSpec != null) { cipher.init(mode, secretKey, parameterSpec); } else { cipher.init(mode, secretKey); } } catch (InvalidKeyException ex) { throw new IllegalArgumentException("Unable to initialize due to invalid secret key", ex); } catch (InvalidAlgorithmParameterException ex) { throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", ex); } } /** * Invokes the Cipher to perform encryption or decryption (depending on the
* initialized mode). */ static byte[] doFinal(Cipher cipher, byte[] input) { try { return cipher.doFinal(input); } catch (IllegalBlockSizeException ex) { throw new IllegalStateException("Unable to invoke Cipher due to illegal block size", ex); } catch (BadPaddingException ex) { throw new IllegalStateException("Unable to invoke Cipher due to bad padding", ex); } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\CipherUtils.java
1
请完成以下Java代码
private UOMConversionRate getRateOrNull(@NonNull final UomId fromUomId, @NonNull final UomId toUomId) { if (fromUomId.equals(toUomId)) { return UOMConversionRate.one(fromUomId); } final FromAndToUomIds key = FromAndToUomIds.builder() .fromUomId(fromUomId) .toUomId(toUomId) .build(); final UOMConversionRate directRate = rates.get(key); if (directRate != null) { return directRate; } final UOMConversionRate invertedRate = rates.get(key.invert()); if (invertedRate != null) { return invertedRate.invert(); } return null; } public boolean isEmpty() { return rates.isEmpty(); } public ImmutableSet<UomId> getCatchUomIds() { if (rates.isEmpty()) { return ImmutableSet.of(); } return rates.values() .stream()
.filter(UOMConversionRate::isCatchUOMForProduct) .map(UOMConversionRate::getToUomId) .collect(ImmutableSet.toImmutableSet()); } private static FromAndToUomIds toFromAndToUomIds(final UOMConversionRate conversion) { return FromAndToUomIds.builder() .fromUomId(conversion.getFromUomId()) .toUomId(conversion.getToUomId()) .build(); } @Value @Builder public static class FromAndToUomIds { @NonNull UomId fromUomId; @NonNull UomId toUomId; public FromAndToUomIds invert() { return builder().fromUomId(toUomId).toUomId(fromUomId).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionsMap.java
1
请完成以下Java代码
public ColumnInfo setWidthMin(final int widthMin) { this.widthMin = widthMin; return this; } public int getWidthMin(final int widthMinDefault) { if (widthMin < 0) { return widthMinDefault; } return widthMin; } private String columnName = null; /** * Sets internal (not translated) name of this column. * * @param columnName * @return this */ public ColumnInfo setColumnName(final String columnName) { this.columnName = columnName; return this; } /** * * @return internal (not translated) column name */ public String getColumnName() { return columnName; } private int precision = -1; /** * Sets precision to be used in case it's a number. * * If not set, default displayType's precision will be used. * * @param precision * @return this */ public ColumnInfo setPrecision(final int precision) { this.precision = precision; return this; } /** * * @return precision to be used in case it's a number */
public int getPrecision() { return this.precision; } public ColumnInfo setSortNo(final int sortNo) { this.sortNo = sortNo; return this; } /** * Gets SortNo. * * @return * @see I_AD_Field#COLUMNNAME_SortNo. */ public int getSortNo() { return sortNo; } @Override public String toString() { return ObjectUtils.toString(this); } } // infoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\minigrid\ColumnInfo.java
1
请完成以下Java代码
private static Method getMethodOrNull( @NonNull final Class<? extends RepoIdAware> repoIdClass, @NonNull final String methodName, final Class<?>... parameterTypes) { try { return repoIdClass.getMethod(methodName, parameterTypes); } catch (final NoSuchMethodException e) { return null; } catch (final SecurityException e) { throw new RuntimeException(e); } } private static RuntimeException mkEx(final String msg, final Throwable cause) { final RuntimeException ex = Check.newException(msg); if (cause != null) { ex.initCause(cause); } return ex; } private static final ConcurrentHashMap<Class<? extends RepoIdAware>, RepoIdAwareDescriptor> repoIdAwareDescriptors = new ConcurrentHashMap<>();
@Value @Builder @VisibleForTesting static class RepoIdAwareDescriptor { @NonNull IntFunction<RepoIdAware> ofRepoIdFunction; @NonNull IntFunction<RepoIdAware> ofRepoIdOrNullFunction; } public static <T, R extends RepoIdAware> Comparator<T> comparingNullsLast(@NonNull final Function<T, R> keyMapper) { return Comparator.comparing(keyMapper, Comparator.nullsLast(Comparator.naturalOrder())); } public static <T extends RepoIdAware> boolean equals(@Nullable final T id1, @Nullable final T id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\RepoIdAwares.java
1
请在Spring Boot框架中完成以下Java代码
public class RedisConfiguration extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); //创建一个json的序列化对象 GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); //设置value的序列化方式json redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //设置key序列化方式String redisTemplate.setKeySerializer(new StringRedisSerializer()); //设置hash key序列化方式String redisTemplate.setHashKeySerializer(new StringRedisSerializer()); //设置hash value序列化json redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
// 设置支持事务 redisTemplate.setEnableTransactionSupport(true); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public RedisSerializer<Object> redisSerializer() { //创建JSON序列化器 ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //必须设置,否则无法将JSON转化为对象,会转化成Map类型 objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL); return new GenericJackson2JsonRedisSerializer(objectMapper); } }
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-redis\src\main\java\cn\lanqiao\springboot3\redis\RedisConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class Demo13Producer { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private RabbitTemplate rabbitTemplate; public void syncSend(Integer id) { // 创建 Demo13Message 消息 Demo13Message message = new Demo13Message(); message.setId(id); // 同步发送消息 rabbitTemplate.invoke(new RabbitOperations.OperationsCallback<Object>() { @Override public Object doInRabbit(RabbitOperations operations) { // 同步发送消息 operations.convertAndSend(Demo13Message.EXCHANGE, Demo13Message.ROUTING_KEY, message); logger.info("[doInRabbit][发送消息完成]"); // 等待确认 operations.waitForConfirms(0); // timeout 参数,如果传递 0 ,表示无限等待 logger.info("[doInRabbit][等待 Confirm 完成]"); return null; } }, new ConfirmCallback() {
@Override public void handle(long deliveryTag, boolean multiple) throws IOException { logger.info("[handle][Confirm 成功]"); } }, new ConfirmCallback() { @Override public void handle(long deliveryTag, boolean multiple) throws IOException { logger.info("[handle][Confirm 失败]"); } }); } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-confirm\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\producer\Demo13Producer.java
2
请在Spring Boot框架中完成以下Java代码
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return delegate.prepareStatement(customizeSql(sql), columnIndexes); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return delegate.prepareStatement(customizeSql(sql), columnNames); } @Override public Clob createClob() throws SQLException { return delegate.createClob(); } @Override public Blob createBlob() throws SQLException { return delegate.createBlob(); } @Override public NClob createNClob() throws SQLException { return delegate.createNClob(); } @Override public SQLXML createSQLXML() throws SQLException { return delegate.createSQLXML(); } @Override public boolean isValid(int timeout) throws SQLException { return delegate.isValid(timeout); } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { delegate.setClientInfo(name, value); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { delegate.setClientInfo(properties); } @Override
public String getClientInfo(String name) throws SQLException { return delegate.getClientInfo(name); } @Override public Properties getClientInfo() throws SQLException { return delegate.getClientInfo(); } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return delegate.createArrayOf(typeName, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return delegate.createStruct(typeName, attributes); } @Override public void setSchema(String schema) throws SQLException { delegate.setSchema(schema); } @Override public String getSchema() throws SQLException { return delegate.getSchema(); } @Override public void abort(Executor executor) throws SQLException { delegate.abort(executor); } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { delegate.setNetworkTimeout(executor, milliseconds); } @Override public int getNetworkTimeout() throws SQLException { return delegate.getNetworkTimeout(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java
2
请完成以下Java代码
protected void doHealthCheck(Health.Builder builder) { if (getGemFireCache().filter(CacheUtils::isPeer).isPresent()) { AtomicInteger globalIndex = new AtomicInteger(0); Set<GatewayReceiver> gatewayReceivers = getGemFireCache() .map(Cache.class::cast) .map(Cache::getGatewayReceivers) .orElseGet(Collections::emptySet); builder.withDetail("geode.gateway-receiver.count", gatewayReceivers.size()); gatewayReceivers.stream() .filter(Objects::nonNull) .forEach(gatewayReceiver -> { int index = globalIndex.getAndIncrement(); builder.withDetail(gatewayReceiverKey(index, "bind-address"), gatewayReceiver.getBindAddress())
.withDetail(gatewayReceiverKey(index, "end-port"), gatewayReceiver.getEndPort()) .withDetail(gatewayReceiverKey(index, "host"), gatewayReceiver.getHost()) .withDetail(gatewayReceiverKey(index, "max-time-between-pings"), gatewayReceiver.getMaximumTimeBetweenPings()) .withDetail(gatewayReceiverKey(index, "port"), gatewayReceiver.getPort()) .withDetail(gatewayReceiverKey(index, "running"), toYesNoString(gatewayReceiver.isRunning())) .withDetail(gatewayReceiverKey(index, "socket-buffer-size"), gatewayReceiver.getSocketBufferSize()) .withDetail(gatewayReceiverKey(index, "start-port"), gatewayReceiver.getStartPort()); }); builder.up(); return; } builder.unknown(); } private String gatewayReceiverKey(int index, String suffix) { return String.format("geode.gateway-receiver.%d.%s", index, suffix); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\GeodeGatewayReceiversHealthIndicator.java
1
请在Spring Boot框架中完成以下Java代码
public class EdgeEventInsertRepository { private static final String INSERT = "INSERT INTO edge_event (id, created_time, edge_id, edge_event_type, edge_event_uid, entity_id, edge_event_action, body, tenant_id, ts) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT DO NOTHING;"; @Autowired protected JdbcTemplate jdbcTemplate; @Autowired private TransactionTemplate transactionTemplate; protected void save(List<EdgeEventEntity> entities) { transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.batchUpdate(INSERT, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { EdgeEventEntity edgeEvent = entities.get(i); ps.setObject(1, edgeEvent.getId()); ps.setLong(2, edgeEvent.getCreatedTime()); ps.setObject(3, edgeEvent.getEdgeId()); ps.setString(4, edgeEvent.getEdgeEventType().name()); ps.setString(5, edgeEvent.getEdgeEventUid()); ps.setObject(6, edgeEvent.getEntityId()); ps.setString(7, edgeEvent.getEdgeEventAction().name()); ps.setString(8, edgeEvent.getEntityBody() != null
? edgeEvent.getEntityBody().toString() : null); ps.setObject(9, edgeEvent.getTenantId()); ps.setLong(10, edgeEvent.getTs()); } @Override public int getBatchSize() { return entities.size(); } }); } }); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\EdgeEventInsertRepository.java
2
请完成以下Java代码
class WrongVoucher extends Money { private String store; WrongVoucher(int amount, String currencyCode, String store) { super(amount, currencyCode); this.store = store; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof WrongVoucher)) return false; WrongVoucher other = (WrongVoucher)o; boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); boolean storeEquals = (this.store == null && other.store == null) || (this.store != null && this.store.equals(other.store)); return this.amount == other.amount && currencyCodeEquals && storeEquals;
} @Override public int hashCode() { int result = 17; result = 31 * result + amount; if (this.currencyCode != null) { result = 31 * result + currencyCode.hashCode(); } if (this.store != null) { result = 31 * result + store.hashCode(); } return result; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods\src\main\java\com\baeldung\equalshashcode\WrongVoucher.java
1
请在Spring Boot框架中完成以下Java代码
private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); engine.setTemplateEngineMessageSource(messageSource()); return engine; } private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } private ITemplateResolver javascriptTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/js/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.JAVASCRIPT); return resolver; } private ITemplateResolver plainTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/txt/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.TEXT); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
public @NonNull ProductId getProductId() {return packageable.getProductId();} public @NonNull String getProductName() {return packageable.getProductName();} public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();} public @NonNull Quantity getQtyToDeliver() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToDeliver(); } public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} public @NonNull Quantity getQtyToPick() { return schedule != null
? schedule.getQtyToPick() : packageable.getQtyToPick(); } public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();} public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();} public @Nullable ShipperId getShipperId() {return packageable.getShipperId();} public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();} public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();} public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
1
请完成以下Java代码
public class RedirectServerAuthenticationFailureHandler implements ServerAuthenticationFailureHandler { private final URI location; private ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); /** * Creates an instance * @param location the location to redirect to (i.e. "/login?failed") */ public RedirectServerAuthenticationFailureHandler(String location) { Assert.notNull(location, "location cannot be null"); this.location = URI.create(location); }
/** * Sets the RedirectStrategy to use. * @param redirectStrategy the strategy to use. Default is DefaultRedirectStrategy. */ public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } @Override public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) { return this.redirectStrategy.sendRedirect(webFilterExchange.getExchange(), this.location); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\RedirectServerAuthenticationFailureHandler.java
1
请完成以下Spring Boot application配置
server.port=8080 # datasource config spring.datasource.url=jdbc:mysql://localhost:3306/springboot3_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password= spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.maximum-pool-size=15 spring.datasource.hikari.auto-commit=true spring.datasource.hikari.idle-timeout=30000 spring.datasource.hikari.pool-name=hikariCP
spring.datasource.hikari.max-lifetime=1800000 spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.connection-test-query=SELECT 1 # mybatis config mybatis.mapper-locations=classpath:mapper/*Dao.xml
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\resources\application.properties
2