instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public List<Dashboard> findByTenantIdAndTitle(UUID tenantId, String title) { return DaoUtil.convertDataList(dashboardRepository.findByTenantIdAndTitle(tenantId, title)); } @Override public PageData<DashboardId> findIdsByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.pageToPageData(dashboardRepository.findIdsByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)).map(DashboardId::new)); } @Override public PageData<DashboardId> findAllIds(PageLink pageLink) { return DaoUtil.pageToPageData(dashboardRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(DashboardId::new)); } @Override
public PageData<Dashboard> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<DashboardFields> findNextBatch(UUID id, int batchSize) { return dashboardRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.DASHBOARD; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\dashboard\JpaDashboardDao.java
1
请完成以下Java代码
final class ADElementOrADMessageTranslatableString implements ITranslatableString { private final String text; ADElementOrADMessageTranslatableString(@NonNull final String text) { this.text = text; } @Override public String toString() { return text; } @Override public String translate(final String adLanguage) { final boolean isSOTrx = true;
return Msg.translate(adLanguage, isSOTrx, text); } @Override public String getDefaultValue() { return "@" + text + "@"; } @Override public Set<String> getAD_Languages() { return Services.get(ILanguageBL.class).getAvailableLanguages().getAD_Languages(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\ADElementOrADMessageTranslatableString.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set IssueUser. @param R_IssueUser_ID User who reported issues */ public void setR_IssueUser_ID (int R_IssueUser_ID) { if (R_IssueUser_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueUser_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueUser_ID, Integer.valueOf(R_IssueUser_ID)); } /** Get IssueUser. @return User who reported issues */ public int getR_IssueUser_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueUser_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Registered EMail. @param UserName Email of the responsible for the System */ public void setUserName (String UserName) { set_ValueNoCheck (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ public String getUserName () { return (String)get_Value(COLUMNNAME_UserName); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getUserName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueUser.java
1
请在Spring Boot框架中完成以下Java代码
public Queue getQueueByName(@Parameter(description = QUEUE_NAME_PARAM_DESCRIPTION) @PathVariable("queueName") String queueName) throws ThingsboardException { checkParameter("queueName", queueName); return checkNotNull(queueService.findQueueByTenantIdAndName(getTenantId(), queueName)); } @ApiOperation(value = "Create Or Update Queue (saveQueue)", notes = "Create or update the Queue. When creating queue, platform generates Queue Id as " + UUID_WIKI_LINK + "Specify existing Queue id to update the queue. " + "Referencing non-existing Queue Id will cause 'Not Found' error." + "\n\nQueue name is unique in the scope of sysadmin. " + "Remove 'id', 'tenantId' from the request body example (below) to create new Queue entity. " + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @RequestMapping(value = "/queues", params = {"serviceType"}, method = RequestMethod.POST) @ResponseBody public Queue saveQueue(@Parameter(description = "A JSON value representing the queue.") @RequestBody Queue queue, @Parameter(description = QUEUE_SERVICE_TYPE_DESCRIPTION, schema = @Schema(allowableValues = {"TB-RULE-ENGINE", "TB-CORE", "TB-TRANSPORT", "JS-EXECUTOR"}, requiredMode = Schema.RequiredMode.REQUIRED)) @RequestParam String serviceType) throws ThingsboardException { checkParameter("serviceType", serviceType); queue.setTenantId(getCurrentUser().getTenantId()); checkEntity(queue.getId(), queue, Resource.QUEUE); ServiceType type = ServiceType.of(serviceType); switch (type) { case TB_RULE_ENGINE:
queue.setTenantId(getTenantId()); Queue savedQueue = tbQueueService.saveQueue(queue); checkNotNull(savedQueue); return savedQueue; default: return null; } } @ApiOperation(value = "Delete Queue (deleteQueue)", notes = "Deletes the Queue. " + SYSTEM_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @RequestMapping(value = "/queues/{queueId}", method = RequestMethod.DELETE) @ResponseBody public void deleteQueue(@Parameter(description = QUEUE_ID_PARAM_DESCRIPTION) @PathVariable("queueId") String queueIdStr) throws ThingsboardException { checkParameter("queueId", queueIdStr); QueueId queueId = new QueueId(toUUID(queueIdStr)); checkQueueId(queueId, Operation.DELETE); tbQueueService.deleteQueue(getTenantId(), queueId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\QueueController.java
2
请完成以下Java代码
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { consumer.accept(huContext, loadResults); } }); } public void removeListener(final IHUTrxListener listener) { if (listener == null) { return; } listeners.remove(listener); } /** * * @param listener * @return true if given listener was already registered */ public boolean hasListener(final IHUTrxListener listener) { return listeners.contains(listener); } public List<IHUTrxListener> asList() { return new ArrayList<>(listeners); } public CompositeHUTrxListener copy() { final CompositeHUTrxListener copy = new CompositeHUTrxListener(); copy.listeners.addAll(listeners); return copy; } @Override public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine) { for (final IHUTrxListener listener : listeners) { listener.trxLineProcessed(huContext, trxLine); } } @Override public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { for (final IHUTrxListener listener : listeners) { listener.huParentChanged(hu, parentHUItemOld); } } @Override public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines) { for (final IHUTrxListener listener : listeners) { listener.afterTrxProcessed(trxHdrRef, trxLines); } } @Override
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } } @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请完成以下Java代码
public long getSkippedTimeoutMillis() { return skippedTimeoutMillis; } /** * @param skippedTimeoutMillis the skippedTimeoutMillis to set */ public void setSkippedTimeoutMillis(final long skippedTimeoutMillis) { Check.assume(skippedTimeoutMillis >= 0, "skippedTimeoutMillis >= 0"); this.skippedTimeoutMillis = skippedTimeoutMillis; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPackageProcessorIds() */ @Override @Nullable public Set<QueuePackageProcessorId> getPackageProcessorIds() { return packageProcessorIds; } /** * @param packageProcessorIds the packageProcessorIds to set */ public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds) { if (packageProcessorIds != null) { Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!"); } this.packageProcessorIds = packageProcessorIds; } /* * (non-Javadoc) * * @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom() */
@Override public String getPriorityFrom() { return priorityFrom; } /** * @param priorityFrom the priorityFrom to set */ public void setPriorityFrom(final String priorityFrom) { this.priorityFrom = priorityFrom; } @Override public String toString() { return "WorkPackageQuery [" + "processed=" + processed + ", readyForProcessing=" + readyForProcessing + ", error=" + error + ", skippedTimeoutMillis=" + skippedTimeoutMillis + ", packageProcessorIds=" + packageProcessorIds + ", priorityFrom=" + priorityFrom + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java
1
请完成以下Java代码
public void setCarrier_Config_ID (final int Carrier_Config_ID) { if (Carrier_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_Carrier_Config_ID, Carrier_Config_ID); } @Override public int getCarrier_Config_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_Config_ID); } @Override public void setClient_Id (final @Nullable java.lang.String Client_Id) { set_Value (COLUMNNAME_Client_Id, Client_Id); } @Override public java.lang.String getClient_Id() { return get_ValueAsString(COLUMNNAME_Client_Id); } @Override public void setClient_Secret (final @Nullable java.lang.String Client_Secret) { set_Value (COLUMNNAME_Client_Secret, Client_Secret); } @Override public java.lang.String getClient_Secret() { return get_ValueAsString(COLUMNNAME_Client_Secret); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); }
@Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setPassword (final @Nullable java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public java.lang.String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setServiceLevel (final @Nullable java.lang.String ServiceLevel) { set_Value (COLUMNNAME_ServiceLevel, ServiceLevel); } @Override public java.lang.String getServiceLevel() { return get_ValueAsString(COLUMNNAME_ServiceLevel); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Config.java
1
请在Spring Boot框架中完成以下Java代码
public class SettlementInvoiceCandidateService { private final CommissionSettlementShareRepository commissionSettlementShareRepository; private final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); public SettlementInvoiceCandidateService( @NonNull final CommissionSettlementShareRepository commissionSettlementShareRepository) { this.commissionSettlementShareRepository = commissionSettlementShareRepository; } public void syncSettlementICToCommissionInstance( @NonNull final InvoiceCandidateId invoiceCandidateId, final boolean candidateDeleted) { final I_C_Invoice_Candidate settlementICRecord = invoiceCandDAO.getById(invoiceCandidateId); final CommissionSettlementShare settlementShare = commissionSettlementShareRepository.getByInvoiceCandidateId(invoiceCandidateId); // // pointsToSettle fact final CommissionPoints newPointsToSettle = CommissionPoints.of(candidateDeleted ? ZERO : settlementICRecord.getQtyToInvoice()); final CommissionPoints pointsToSettleDelta = newPointsToSettle.subtract(settlementShare.getPointsToSettleSum()); if (!pointsToSettleDelta.isZero()) {
final CommissionSettlementFact fact = CommissionSettlementFact.builder() .settlementInvoiceCandidateId(invoiceCandidateId) .timestamp(TimeUtil.asInstant(settlementICRecord.getUpdated())) .state(CommissionSettlementState.TO_SETTLE) .points(pointsToSettleDelta) .build(); settlementShare.addFact(fact); } // // settledPoints fact final CommissionPoints settledPoints = CommissionPoints.of(candidateDeleted ? ZERO : settlementICRecord.getQtyInvoiced()); final CommissionPoints settledPointsDelta = settledPoints.subtract(settlementShare.getSettledPointsSum()); if (!settledPointsDelta.isZero()) { final CommissionSettlementFact fact = CommissionSettlementFact.builder() .settlementInvoiceCandidateId(invoiceCandidateId) .timestamp(TimeUtil.asInstant(settlementICRecord.getUpdated())) .state(CommissionSettlementState.SETTLED) .points(settledPointsDelta) .build(); settlementShare.addFact(fact); } commissionSettlementShareRepository.save(settlementShare); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\SettlementInvoiceCandidateService.java
2
请完成以下Java代码
synchronized public long getNextReconnectDelay() { final long currentNanoTime = getNanoTime(); final long coolDownSpentNanos = currentNanoTime - lastDisconnectNanoTime; lastDisconnectNanoTime = currentNanoTime; if (isCooledDown(coolDownSpentNanos)) { retryCount = 0; return reconnectIntervalMinSeconds; } return calculateNextReconnectDelay() + calculateJitter(); } long calculateJitter() { return ThreadLocalRandom.current().nextInt() >= 0 ? JITTER_MAX : 0; } long calculateNextReconnectDelay() { return Math.min(reconnectIntervalMaxSeconds, reconnectIntervalMinSeconds + calculateExp(retryCount++));
} long calculateExp(long e) { return 1L << Math.min(e, EXP_MAX); } boolean isCooledDown(long coolDownSpentNanos) { return TimeUnit.NANOSECONDS.toSeconds(coolDownSpentNanos) > reconnectIntervalMaxSeconds + reconnectIntervalMinSeconds; } long getNanoTime() { return System.nanoTime(); } }
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\ReconnectStrategyExponential.java
1
请完成以下Java代码
public class Sanitizer { private final List<SanitizingFunction> sanitizingFunctions = new ArrayList<>(); /** * Create a new {@link Sanitizer} instance. */ public Sanitizer() { this(Collections.emptyList()); } /** * Create a new {@link Sanitizer} instance with sanitizing functions. * @param sanitizingFunctions the sanitizing functions to apply * @since 2.6.0 */ public Sanitizer(Iterable<SanitizingFunction> sanitizingFunctions) { sanitizingFunctions.forEach(this.sanitizingFunctions::add); } /** * Sanitize the value from the given {@link SanitizableData} using the available * {@link SanitizingFunction}s. * @param data the sanitizable data * @param showUnsanitized whether to show the unsanitized values or not * @return the potentially updated data
* @since 3.0.0 */ public @Nullable Object sanitize(SanitizableData data, boolean showUnsanitized) { Object value = data.getValue(); if (value == null) { return null; } if (!showUnsanitized) { return SanitizableData.SANITIZED_VALUE; } for (SanitizingFunction sanitizingFunction : this.sanitizingFunctions) { data = sanitizingFunction.applyUnlessFiltered(data); Object sanitizedValue = data.getValue(); if (!value.equals(sanitizedValue)) { return sanitizedValue; } } return value; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\Sanitizer.java
1
请完成以下Java代码
private List<I_AD_WF_Node> retrieveNodes(@NonNull final I_AD_Workflow routingRecord) { final PPRoutingId routingId = PPRoutingId.ofRepoId(routingRecord.getAD_Workflow_ID()); return queryBL .createQueryBuilder(I_AD_WF_Node.class, routingRecord) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_WF_Node.COLUMNNAME_AD_Workflow_ID, routingId) .addNotNull(I_AD_WF_Node.COLUMN_S_Resource_ID) // in the context of production and product-planning, we can't work with a resource-less AD_WF_Node .orderBy(I_AD_WF_Node.COLUMNNAME_AD_WF_Node_ID) .create() .list(); } private List<I_PP_WF_Node_Product> retrieveProducts(final Set<PPRoutingActivityId> activityIds) { if (Check.isEmpty(activityIds)) { return Collections.emptyList(); } return queryBL .createQueryBuilder(I_PP_WF_Node_Product.class) .addOnlyActiveRecordsFilter() //.addOnlyContextClient() // not needed .addInArrayFilter(I_PP_WF_Node_Product.COLUMNNAME_AD_WF_Node_ID, activityIds) .create() .list(); } @Override public Optional<PPRoutingId> getDefaultRoutingIdByType(@NonNull final PPRoutingType type) { return queryBL .createQueryBuilderOutOfTrx(I_AD_Workflow.class) .addEqualsFilter(I_AD_Workflow.COLUMNNAME_WorkflowType, type) .addEqualsFilter(I_AD_Workflow.COLUMNNAME_IsDefault, true) .create() .firstIdOnlyOptional(PPRoutingId::ofRepoIdOrNull);
} @Override public void setFirstNodeToWorkflow(@NonNull final PPRoutingActivityId ppRoutingActivityId) { final I_AD_Workflow workflow = load(ppRoutingActivityId.getRoutingId(), I_AD_Workflow.class); workflow.setAD_WF_Node_ID(ppRoutingActivityId.getRepoId()); save(workflow); } @Override public SeqNo getActivityProductNextSeqNo(@NonNull final PPRoutingActivityId activityId) { final int lastSeqNoInt = queryBL .createQueryBuilder(I_PP_WF_Node_Product.class) //.addOnlyActiveRecordsFilter() // let's include non active ones too .addEqualsFilter(I_PP_WF_Node_Product.COLUMNNAME_AD_WF_Node_ID, activityId) .create() .maxInt(I_PP_WF_Node_Product.COLUMNNAME_SeqNo); return SeqNo.ofInt(Math.max(lastSeqNoInt, 0)).next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPRoutingRepository.java
1
请完成以下Java代码
public void setdocument (java.lang.String document) { set_Value (COLUMNNAME_document, document); } @Override public java.lang.String getdocument() { return (java.lang.String)get_Value(COLUMNNAME_document); } @Override public void setDocumentNo (java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } @Override public void setFirstname (java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return (java.lang.String)get_Value(COLUMNNAME_Firstname); } @Override public void setGrandTotal (java.math.BigDecimal GrandTotal) { set_Value (COLUMNNAME_GrandTotal, GrandTotal); } @Override public java.math.BigDecimal getGrandTotal() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLastname (java.lang.String Lastname)
{ set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } @Override public void setprintjob (java.lang.String printjob) { set_Value (COLUMNNAME_printjob, printjob); } @Override public java.lang.String getprintjob() { return (java.lang.String)get_Value(COLUMNNAME_printjob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Printing_Bericht_List_Per_Print_Job.java
1
请完成以下Java代码
public org.eevolution.model.I_PP_MRP getPP_MRP_Demand() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_MRP_Demand_ID, org.eevolution.model.I_PP_MRP.class); } @Override public void setPP_MRP_Demand(org.eevolution.model.I_PP_MRP PP_MRP_Demand) { set_ValueFromPO(COLUMNNAME_PP_MRP_Demand_ID, org.eevolution.model.I_PP_MRP.class, PP_MRP_Demand); } /** Set MRP Demand. @param PP_MRP_Demand_ID MRP Demand */ @Override public void setPP_MRP_Demand_ID (int PP_MRP_Demand_ID) { if (PP_MRP_Demand_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Demand_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_Demand_ID, Integer.valueOf(PP_MRP_Demand_ID)); } /** Get MRP Demand. @return MRP Demand */ @Override public int getPP_MRP_Demand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Demand_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_MRP getPP_MRP_Supply() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class); } @Override public void setPP_MRP_Supply(org.eevolution.model.I_PP_MRP PP_MRP_Supply) { set_ValueFromPO(COLUMNNAME_PP_MRP_Supply_ID, org.eevolution.model.I_PP_MRP.class, PP_MRP_Supply); }
/** Set MRP Supply. @param PP_MRP_Supply_ID MRP Supply */ @Override public void setPP_MRP_Supply_ID (int PP_MRP_Supply_ID) { if (PP_MRP_Supply_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_MRP_Supply_ID, Integer.valueOf(PP_MRP_Supply_ID)); } /** Get MRP Supply. @return MRP Supply */ @Override public int getPP_MRP_Supply_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_MRP_Supply_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zugewiesene Menge. @param QtyAllocated Zugewiesene Menge */ @Override public void setQtyAllocated (java.math.BigDecimal QtyAllocated) { set_Value (COLUMNNAME_QtyAllocated, QtyAllocated); } /** Get Zugewiesene Menge. @return Zugewiesene Menge */ @Override public java.math.BigDecimal getQtyAllocated () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyAllocated); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alloc.java
1
请完成以下Java代码
public void updateForwardPPOrderByIds(@NonNull final Set<DDOrderId> ddOrderIds, @Nullable final PPOrderId newPPOrderId) { if (ddOrderIds.isEmpty()) { return; } queryBL.createQueryBuilder(I_DD_Order.class) .addInArrayFilter(I_DD_Order.COLUMNNAME_DD_Order_ID, ddOrderIds) .addNotEqualsFilter(I_DD_Order.COLUMNNAME_Forward_PP_Order_ID, newPPOrderId) .create() .update(ddOrder -> { ddOrder.setForward_PP_Order_ID(PPOrderId.toRepoId(newPPOrderId)); return IQueryUpdater.MODEL_UPDATED; }); } public Set<ProductId> getProductIdsByDDOrderIds(final Collection<DDOrderId> ddOrderIds) {
if (ddOrderIds.isEmpty()) { return ImmutableSet.of(); } final List<ProductId> productIds = queryBL.createQueryBuilder(I_DD_OrderLine.class) .addInArrayFilter(I_DD_Order.COLUMNNAME_DD_Order_ID, ddOrderIds) .addOnlyActiveRecordsFilter() .create() .listDistinct(I_DD_OrderLine.COLUMNNAME_M_Product_ID, ProductId.class); return ImmutableSet.copyOf(productIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DDOrderLowLevelDAO.java
1
请完成以下Java代码
private boolean isSelectedRecordProcessed(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return bankStatementImportFileService.getById(bankStatementImportFileId) .isProcessed(); } private boolean isMissingAttachmentEntryForRecordId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { return !getSingleAttachmentEntryId(bankStatementImportFileId).isPresent(); } @NonNull private Optional<AttachmentEntryId> getSingleAttachmentEntryId(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final List<AttachmentEntry> attachments = attachmentEntryService .getByReferencedRecord(TableRecordReference.of(I_C_BankStatement_Import_File.Table_Name, bankStatementImportFileId)); if (attachments.isEmpty()) { return Optional.empty(); } if (attachments.size() != 1) { throw new AdempiereException(MSG_MULTIPLE_ATTACHMENTS)
.markAsUserValidationError(); } return Optional.of(attachments.get(0).getId()); } @NonNull private AttachmentEntryDataResource retrieveAttachmentResource(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final AttachmentEntryId attachmentEntryId = getSingleAttachmentEntryId(bankStatementImportFileId) .orElseThrow(() -> new AdempiereException(MSG_NO_ATTACHMENT) .markAsUserValidationError()); return attachmentEntryService.retrieveDataResource(attachmentEntryId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\process\C_BankStatement_Import_File_Camt53_ImportAttachment.java
1
请完成以下Java代码
public class AdhocSubProcess extends SubProcess { public static final String ORDERING_PARALLEL = "Parallel"; public static final String ORDERING_SEQUENTIALL = "Sequential"; protected String completionCondition; protected String ordering = ORDERING_PARALLEL; protected boolean cancelRemainingInstances = true; public String getCompletionCondition() { return completionCondition; } public void setCompletionCondition(String completionCondition) { this.completionCondition = completionCondition; } public String getOrdering() { return ordering; } public void setOrdering(String ordering) { this.ordering = ordering; }
public boolean hasParallelOrdering() { return !ORDERING_SEQUENTIALL.equals(ordering); } public boolean hasSequentialOrdering() { return ORDERING_SEQUENTIALL.equals(ordering); } public boolean isCancelRemainingInstances() { return cancelRemainingInstances; } public void setCancelRemainingInstances(boolean cancelRemainingInstances) { this.cancelRemainingInstances = cancelRemainingInstances; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\AdhocSubProcess.java
1
请完成以下Java代码
public boolean isInboundTrx() { return getStmtAmt().signum() >= 0; } private I_C_BankStatementLine getC_BankStatementLine() { return getModel(I_C_BankStatementLine.class); } CurrencyConversionContext getCurrencyConversionCtxForBankAsset() { CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankAsset; if (currencyConversionContext == null) { currencyConversionContext = this._currencyConversionContextForBankAsset = createCurrencyConversionCtxForBankAsset(); } return currencyConversionContext; } private CurrencyConversionContext createCurrencyConversionCtxForBankAsset() { final I_C_BankStatementLine line = getC_BankStatementLine(); final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID()); // IMPORTANT for Bank Asset Account booking, // * we shall NOT consider the fixed Currency Rate because we want to compute currency gain/loss // * use default conversion types return services.createCurrencyConversionContext( LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone), null, ClientId.ofRepoId(line.getAD_Client_ID())); } CurrencyConversionContext getCurrencyConversionCtxForBankInTransit() { CurrencyConversionContext currencyConversionContext = this._currencyConversionContextForBankInTransit; if (currencyConversionContext == null) { currencyConversionContext = this._currencyConversionContextForBankInTransit = createCurrencyConversionCtxForBankInTransit(); } return currencyConversionContext; }
private CurrencyConversionContext createCurrencyConversionCtxForBankInTransit() { final I_C_Payment payment = getC_Payment(); if (payment != null) { return paymentBL.extractCurrencyConversionContext(payment); } else { final I_C_BankStatementLine line = getC_BankStatementLine(); final PaymentCurrencyContext paymentCurrencyContext = bankStatementBL.getPaymentCurrencyContext(line); final OrgId orgId = OrgId.ofRepoId(line.getAD_Org_ID()); CurrencyConversionContext conversionCtx = services.createCurrencyConversionContext( LocalDateAndOrgId.ofTimestamp(line.getDateAcct(), orgId, services::getTimeZone), paymentCurrencyContext.getCurrencyConversionTypeId(), ClientId.ofRepoId(line.getAD_Client_ID())); final FixedConversionRate fixedCurrencyRate = paymentCurrencyContext.toFixedConversionRateOrNull(); if (fixedCurrencyRate != null) { conversionCtx = conversionCtx.withFixedConversionRate(fixedCurrencyRate); } return conversionCtx; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\DocLine_BankStatement.java
1
请在Spring Boot框架中完成以下Java代码
public String getShippingBPLocationExternalIdNotNull() { if (shippingBPLocationExternalId == null) { throw new RuntimeException("shippingBPLocationExternalId cannot be null at this stage!"); } return shippingBPLocationExternalId; } public void setOrder(@NonNull final Order order) { this.order = order; importedExternalHeaderIds.add(order.getOrderId()); } @NonNull public Optional<Instant> getNextImportStartingTimestamp() { if (nextImportStartingTimestamp == null) { return Optional.empty(); } return Optional.of(nextImportStartingTimestamp.getTimestamp()); } /** * Update next import timestamp to the most current one. */ public void setNextImportStartingTimestamp(@NonNull final DateAndImportStatus dateAndImportStatus) { if (this.nextImportStartingTimestamp == null) { this.nextImportStartingTimestamp = dateAndImportStatus; return; }
if (this.nextImportStartingTimestamp.isOkToImport()) { if (dateAndImportStatus.isOkToImport() && dateAndImportStatus.getTimestamp().isAfter(this.nextImportStartingTimestamp.getTimestamp())) { this.nextImportStartingTimestamp = dateAndImportStatus; return; } if (!dateAndImportStatus.isOkToImport()) { this.nextImportStartingTimestamp = dateAndImportStatus; return; } } if (!this.nextImportStartingTimestamp.isOkToImport() && !dateAndImportStatus.isOkToImport() && dateAndImportStatus.getTimestamp().isBefore(this.nextImportStartingTimestamp.getTimestamp())) { this.nextImportStartingTimestamp = dateAndImportStatus; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\EbayImportOrdersRouteContext.java
2
请完成以下Java代码
public long getCleanableDecisionInstanceCount() { return cleanableDecisionInstanceCount; } public void setCleanableDecisionInstanceCount(long cleanableDecisionInstanceCount) { this.cleanableDecisionInstanceCount = cleanableDecisionInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public static List<CleanableHistoricDecisionInstanceReportResultDto> convert(List<CleanableHistoricDecisionInstanceReportResult> reportResult) { List<CleanableHistoricDecisionInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricDecisionInstanceReportResultDto>();
for (CleanableHistoricDecisionInstanceReportResult current : reportResult) { CleanableHistoricDecisionInstanceReportResultDto dto = new CleanableHistoricDecisionInstanceReportResultDto(); dto.setDecisionDefinitionId(current.getDecisionDefinitionId()); dto.setDecisionDefinitionKey(current.getDecisionDefinitionKey()); dto.setDecisionDefinitionName(current.getDecisionDefinitionName()); dto.setDecisionDefinitionVersion(current.getDecisionDefinitionVersion()); dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); dto.setFinishedDecisionInstanceCount(current.getFinishedDecisionInstanceCount()); dto.setCleanableDecisionInstanceCount(current.getCleanableDecisionInstanceCount()); dto.setTenantId(current.getTenantId()); dtos.add(dto); } return dtos; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportResultDto.java
1
请完成以下Java代码
public InvoiceCandidatesAmtSelectionSummary build() { return new InvoiceCandidatesAmtSelectionSummary(this); } public Builder addTotalNetAmt(final BigDecimal amtToAdd, final boolean approved, final boolean isPackingMaterial) { if (approved) { totalNetAmtApproved = totalNetAmtApproved.add(amtToAdd); if (isPackingMaterial) { huNetAmtApproved = huNetAmtApproved.add(amtToAdd); } else { cuNetAmtApproved = cuNetAmtApproved.add(amtToAdd); } } else { totalNetAmtNotApproved = totalNetAmtNotApproved.add(amtToAdd); if (isPackingMaterial) { huNetAmtNotApproved = huNetAmtNotApproved.add(amtToAdd); } else { cuNetAmtNotApproved = cuNetAmtNotApproved.add(amtToAdd); } } return this; } @SuppressWarnings("UnusedReturnValue") public Builder addCurrencySymbol(final String currencySymbol) {
if (Check.isEmpty(currencySymbol, true)) { // NOTE: prevent adding null values because ImmutableSet.Builder will fail in this case currencySymbols.add("?"); } else { currencySymbols.add(currencySymbol); } return this; } public void addCountToRecompute(final int countToRecomputeToAdd) { Check.assume(countToRecomputeToAdd > 0, "countToRecomputeToAdd > 0"); countTotalToRecompute += countToRecomputeToAdd; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesAmtSelectionSummary.java
1
请完成以下Java代码
public class ProcessingType { @XmlElement(required = true) protected TransportType transport; /** * Gets the value of the transport property. * * @return * possible object is * {@link TransportType } * */ public TransportType getTransport() { return transport;
} /** * Sets the value of the transport property. * * @param value * allowed object is * {@link TransportType } * */ public void setTransport(TransportType value) { this.transport = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ProcessingType.java
1
请在Spring Boot框架中完成以下Java代码
public Job retryExceptionJob() { return jobBuilderFactory.get("retryExceptionJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<String, String>chunk(2) .reader(listItemReader()) .processor(myProcessor()) .writer(list -> list.forEach(System.out::println)) .faultTolerant() // 配置错误容忍 .retry(MyJobExecutionException.class) // 配置重试的异常类型 .retryLimit(3) // 重试3次,三次过后还是异常的话,则任务会结束, // 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常重试 .build(); } private ListItemReader<String> listItemReader() { ArrayList<String> datas = new ArrayList<>(); IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i))); return new ListItemReader<>(datas);
} private ItemProcessor<String, String> myProcessor() { return new ItemProcessor<String, String>() { private int count; @Override public String process(String item) throws Exception { System.out.println("当前处理的数据:" + item); if (count >= 2) { return item; } else { count++; throw new MyJobExecutionException("任务处理出错"); } } }; } }
repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\RetryExceptionJobDemo.java
2
请完成以下Java代码
public int getC_Payment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Discount Amount. @param DiscountAmt Calculated amount of discount */ @Override public void setDiscountAmt (java.math.BigDecimal DiscountAmt) { set_Value (COLUMNNAME_DiscountAmt, DiscountAmt); } /** Get Discount Amount. @return Calculated amount of discount */ @Override public java.math.BigDecimal getDiscountAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Generated. @param IsGenerated This Line is generated */ @Override public void setIsGenerated (boolean IsGenerated) { set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated)); } /** Get Generated. @return This Line is generated */ @Override public boolean isGenerated () { Object oo = get_Value(COLUMNNAME_IsGenerated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () {
Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override 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 Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请完成以下Java代码
public class SignalEventDefinitionParseHandler extends AbstractBpmnParseHandler<SignalEventDefinition> { public Class<? extends BaseElement> getHandledType() { return SignalEventDefinition.class; } protected void executeParse(BpmnParse bpmnParse, SignalEventDefinition signalDefinition) { Signal signal = null; if (bpmnParse.getBpmnModel().containsSignalId(signalDefinition.getSignalRef())) { signal = bpmnParse.getBpmnModel().getSignal(signalDefinition.getSignalRef()); } if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent) { IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement(); intermediateCatchEvent.setBehavior( bpmnParse .getActivityBehaviorFactory() .createIntermediateCatchSignalEventActivityBehavior( intermediateCatchEvent, signalDefinition,
signal ) ); } else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) { BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement(); boundaryEvent.setBehavior( bpmnParse .getActivityBehaviorFactory() .createBoundarySignalEventActivityBehavior( boundaryEvent, signalDefinition, signal, boundaryEvent.isCancelActivity() ) ); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SignalEventDefinitionParseHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class StockService { private static final BigDecimal UP = BigDecimal.valueOf(1.05f); private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f); List<String> stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO"); List<Stock> stocksDB = new ArrayList<>(); private AtomicInteger counter = new AtomicInteger(0); public void init(@Observes @Initialized(ApplicationScoped.class) Object init) { //Open price System.out.println("@Start Init ..."); stockNames.forEach(stockName -> { stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now())); }); Runnable runnable = new Runnable() { @Override public void run() { //Simulate Change price and put every x seconds while (true) { int indx = new Random().nextInt(stockNames.size()); String stockName = stockNames.get(indx); BigDecimal price = getLastPrice(stockName); BigDecimal newprice = changePrice(price); Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now()); stocksDB.add(stock); int r = new Random().nextInt(30); try { Thread.currentThread().sleep(r*1000); } catch (InterruptedException ex) { // ... } } } }; new Thread(runnable).start(); System.out.println("@End Init ...");
} public Stock getNextTransaction(Integer lastEventId) { return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null); } BigDecimal generateOpenPrice() { float min = 70; float max = 120; return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING); } BigDecimal changePrice(BigDecimal price) { return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING); } private BigDecimal getLastPrice(String stockName) { return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice(); } }
repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-server\src\main\java\com\baeldung\sse\jaxrs\StockService.java
2
请在Spring Boot框架中完成以下Java代码
public class PasswordChangeDTO { private String currentPassword; private String newPassword; public PasswordChangeDTO() { // Empty constructor needed for Jackson. } public PasswordChangeDTO(String currentPassword, String newPassword) { this.currentPassword = currentPassword; this.newPassword = newPassword; } public String getCurrentPassword() {
return currentPassword; } public void setCurrentPassword(String currentPassword) { this.currentPassword = currentPassword; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\PasswordChangeDTO.java
2
请在Spring Boot框架中完成以下Java代码
public Executor asyncExecutor1() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); // 核心线程数10:线程池创建时候初始化的线程数 executor.setMaxPoolSize(20); // 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 executor.setQueueCapacity(200); // 缓冲队列200:用来缓冲执行任务的队列 executor.setKeepAliveSeconds(60); // 允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁 executor.setThreadNamePrefix("asyncExecutor1-"); // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 /** * 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } @Bean("asyncExecutor2")
public Executor asyncExecutor2() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); // 核心线程数10:线程池创建时候初始化的线程数 executor.setMaxPoolSize(20); // 最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 executor.setQueueCapacity(200); // 缓冲队列200:用来缓冲执行任务的队列 executor.setKeepAliveSeconds(60); // 允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁 executor.setThreadNamePrefix("asyncExecutor2-"); // 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 /** * 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
repos\spring-boot-quick-master\quick-async\src\main\java\com\async\config\ThreadConfig.java
2
请在Spring Boot框架中完成以下Java代码
private static MaterialDescriptorQuery buildMaterialDescriptorQueryForReplacingOld(@NonNull final I_MD_Candidate oldCandidateRecord) { final Instant endOfTheDay = oldCandidateRecord.getDateProjected() .toInstant() .plus(1, ChronoUnit.DAYS) .truncatedTo(ChronoUnit.DAYS); return MaterialDescriptorQuery .builder() .warehouseId(WarehouseId.ofRepoId(oldCandidateRecord.getM_Warehouse_ID())) .productId(oldCandidateRecord.getM_Product_ID()) .storageAttributesKey(AttributesKey.ofString(oldCandidateRecord.getStorageAttributesKey())) .customer(BPartnerClassifier.specificOrAny(BPartnerId.ofRepoIdOrNull(oldCandidateRecord.getC_BPartner_Customer_ID()))) .customerIdOperator(MaterialDescriptorQuery.CustomerIdOperator.GIVEN_ID_ONLY) .timeRangeEnd(DateAndSeqNo.builder() .date(endOfTheDay) .operator(DateAndSeqNo.Operator.EXCLUSIVE) .build()) .build(); } private static boolean isMaterialDescriptorChanged( @NonNull final I_MD_Candidate oldCandidateRecord, @NonNull final I_MD_Candidate candidateRecord) { return !candidateRecord.getDateProjected().equals(oldCandidateRecord.getDateProjected()) || !candidateRecord.getStorageAttributesKey().equals(oldCandidateRecord.getStorageAttributesKey())
|| oldCandidateRecord.getM_Warehouse_ID() != candidateRecord.getM_Warehouse_ID() || oldCandidateRecord.getM_Product_ID() != candidateRecord.getM_Product_ID(); } private static boolean isUpdateOldStockRequired( @NonNull final ModelChangeType timingType, @NonNull final I_MD_Candidate oldCandidateRecord, @NonNull final I_MD_Candidate candidate) { return timingType.isDelete() || (timingType.isChange() && isMaterialDescriptorChanged(oldCandidateRecord, candidate)); } private static boolean isUpdateCurrentStockRequired(@NonNull final ModelChangeType timingType) { return !timingType.isDelete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\interceptor\MD_Candidate.java
2
请完成以下Java代码
public void setMfaEnabled(boolean mfaEnabled) { this.mfaEnabled = mfaEnabled; } /** * The session handling strategy which will be invoked immediately after an * authentication request is successfully processed by the * <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the * session identifier to prevent session fixation attacks. * @param sessionStrategy the implementation to use. If not set a null implementation * is used. */ public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) { this.sessionStrategy = sessionStrategy; } /** * Sets the strategy used to handle a successful authentication. By default a * {@link SavedRequestAwareAuthenticationSuccessHandler} is used. */ public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) { Assert.notNull(successHandler, "successHandler cannot be null"); this.successHandler = successHandler; } public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { Assert.notNull(failureHandler, "failureHandler cannot be null"); this.failureHandler = failureHandler; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } protected AuthenticationSuccessHandler getSuccessHandler() { return this.successHandler; } protected AuthenticationFailureHandler getFailureHandler() { return this.failureHandler; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AbstractAuthenticationProcessingFilter.java
1
请完成以下Spring Boot application配置
spring: # Spring Security 配置项,对应 SecurityProperties 配置类 security: # 配置默认的 InMemoryUserDetailsManager 的用户账号与密码。 user: name:
user # 账号 password: user # 密码 roles: ADMIN # 拥有角色
repos\SpringBoot-Labs-master\lab-01-spring-security\lab-01-springsecurity-demo\src\main\resources\application.yaml
2
请完成以下Java代码
public TUMergeBuilder setCUUOM(final I_C_UOM uom) { cuUOM = uom; return this; } @Override public TUMergeBuilder setCUTrxReferencedModel(final Object trxReferencedModel) { cuTrxReferencedModel = trxReferencedModel; return this; } @Override public void mergeTUs() { huTrxBL.createHUContextProcessorExecutor(huContextInitial).run((IHUContextProcessor)huContext0 -> { // Make a copy of the processing context, we will need to modify it final IMutableHUContext huContext = huContext0.copyAsMutable(); // Register our split HUTrxListener because this "merge" operation is similar with a split // More, this will allow our listeners to execute on-split operations (e.g. linking the newly created VHU to same document as the source VHU). huContext.getTrxListeners().addListener(HUSplitBuilderTrxListener.instance); mergeTUs0(huContext); return IHUContextProcessor.NULL_RESULT; // we don't care about the result }); } private void mergeTUs0(final IHUContext huContext) { final IAllocationRequest allocationRequest = createMergeAllocationRequest(huContext); // // Source: Selected handling units final IAllocationSource source = HUListAllocationSourceDestination.of(sourceHUs); // // Destination: Handling unit we want to merge on
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU); // // Perform allocation HULoader.of(source, destination) .setAllowPartialUnloads(true) // force allow partial unloads when merging .setAllowPartialLoads(true) // force allow partial loads when merging .load(allocationRequest); // execute it; we don't care about the result // // Destroy HUs which had their storage emptied for (final I_M_HU sourceHU : sourceHUs) { handlingUnitsBL.destroyIfEmptyStorage(huContext, sourceHU); } } /** * Create an allocation request for the cuQty of the builder * * @param huContext * @param referencedModel referenced model to be used in created request * @return created request */ private IAllocationRequest createMergeAllocationRequest(final IHUContext huContext) { final ZonedDateTime date = SystemTime.asZonedDateTime(); return AllocationUtils.createQtyRequest( huContext, cuProductId, // Product Quantity.of(cuQty, cuUOM), // quantity date, // Date cuTrxReferencedModel, // Referenced model false // force allocation ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\TUMergeBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws"); } @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.setApplicationDestinationPrefixes("/app"); config.enableSimpleBroker("/topic"); } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registry) { // TODO Auto-generated method stub } @Override public void configureClientInboundChannel(ChannelRegistration registration) { // TODO Auto-generated method stub } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { // TODO Auto-generated method stub } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// TODO Auto-generated method stub } @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { // TODO Auto-generated method stub } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { // TODO Auto-generated method stub return false; } }
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsockets\config\WebSocketMessageBrokerConfig.java
2
请完成以下Java代码
public final class TsKvEntity extends AbstractTsKvEntity { public TsKvEntity() { } public TsKvEntity(String strValue, Long aggValuesLastTs) { super(aggValuesLastTs); this.strValue = strValue; } public TsKvEntity(Long longValue, Double doubleValue, Long longCountValue, Long doubleCountValue, String aggType, Long aggValuesLastTs) { super(aggValuesLastTs); if (!isAllNull(longValue, doubleValue, longCountValue, doubleCountValue)) { switch (aggType) { case AVG: double sum = 0.0; if (longValue != null) { sum += longValue; } if (doubleValue != null) { sum += doubleValue; } long totalCount = longCountValue + doubleCountValue; if (totalCount > 0) { this.doubleValue = sum / (longCountValue + doubleCountValue); } else { this.doubleValue = 0.0; } this.aggValuesCount = totalCount; break; case SUM: if (doubleCountValue > 0) { this.doubleValue = doubleValue + (longValue != null ? longValue.doubleValue() : 0.0); } else { this.longValue = longValue;
} break; case MIN: case MAX: if (longCountValue > 0 && doubleCountValue > 0) { this.doubleValue = MAX.equals(aggType) ? Math.max(doubleValue, longValue.doubleValue()) : Math.min(doubleValue, longValue.doubleValue()); } else if (doubleCountValue > 0) { this.doubleValue = doubleValue; } else if (longCountValue > 0) { this.longValue = longValue; } break; } } } public TsKvEntity(Long booleanValueCount, Long strValueCount, Long longValueCount, Long doubleValueCount, Long jsonValueCount, Long aggValuesLastTs) { super(aggValuesLastTs); if (!isAllNull(booleanValueCount, strValueCount, longValueCount, doubleValueCount)) { if (booleanValueCount != 0) { this.longValue = booleanValueCount; } else if (strValueCount != 0) { this.longValue = strValueCount; } else if (jsonValueCount != 0) { this.longValue = jsonValueCount; } else { this.longValue = longValueCount + doubleValueCount; } } } @Override public boolean isNotEmpty() { return strValue != null || longValue != null || doubleValue != null || booleanValue != null; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sqlts\ts\TsKvEntity.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getCashBeginningBalance() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CashBeginningBalance); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setCashEndingBalance (final BigDecimal CashEndingBalance) { set_Value (COLUMNNAME_CashEndingBalance, CashEndingBalance); } @Override public BigDecimal getCashEndingBalance() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CashEndingBalance); return bd != null ? bd : BigDecimal.ZERO; } @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 setClosingNote (final @Nullable java.lang.String ClosingNote) { set_Value (COLUMNNAME_ClosingNote, ClosingNote); } @Override public java.lang.String getClosingNote() { return get_ValueAsString(COLUMNNAME_ClosingNote); } @Override public org.compiere.model.I_C_POS getC_POS() { return get_ValueAsPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class); } @Override public void setC_POS(final org.compiere.model.I_C_POS C_POS) { set_ValueFromPO(COLUMNNAME_C_POS_ID, org.compiere.model.I_C_POS.class, C_POS); } @Override public void setC_POS_ID (final int C_POS_ID) { if (C_POS_ID < 1) set_Value (COLUMNNAME_C_POS_ID, null); else set_Value (COLUMNNAME_C_POS_ID, C_POS_ID); } @Override public int getC_POS_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_ID); } @Override public void setC_POS_Journal_ID (final int C_POS_Journal_ID) { if (C_POS_Journal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_POS_Journal_ID, C_POS_Journal_ID); }
@Override public int getC_POS_Journal_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_Journal_ID); } @Override public void setDateTrx (final java.sql.Timestamp DateTrx) { set_Value (COLUMNNAME_DateTrx, DateTrx); } @Override public java.sql.Timestamp getDateTrx() { return get_ValueAsTimestamp(COLUMNNAME_DateTrx); } @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 setIsClosed (final boolean IsClosed) { set_Value (COLUMNNAME_IsClosed, IsClosed); } @Override public boolean isClosed() { return get_ValueAsBoolean(COLUMNNAME_IsClosed); } @Override public void setOpeningNote (final @Nullable java.lang.String OpeningNote) { set_Value (COLUMNNAME_OpeningNote, OpeningNote); } @Override public java.lang.String getOpeningNote() { return get_ValueAsString(COLUMNNAME_OpeningNote); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java
2
请在Spring Boot框架中完成以下Java代码
public class RetryAspect { private static final Logger logger = LoggerFactory.getLogger(RetryAspect.class); @Pointcut("@annotation(com.xiaolyuh.annotation.Retryable)") public void pointcut() { } @Around("pointcut()") public Object retry(ProceedingJoinPoint joinPoint) throws Exception { // 获取注解 Retryable retryable = AnnotationUtils.findAnnotation(getSpecificmethod(joinPoint), Retryable.class); // 声明Callable Callable<Object> task = () -> getTask(joinPoint); // 声明guava retry对象 Retryer<Object> retryer = null; try { retryer = RetryerBuilder.newBuilder() // 指定触发重试的条件 .retryIfResult(Predicates.isNull()) // 指定触发重试的异常 .retryIfExceptionOfType(retryable.exception())// 抛出Exception异常时重试 // 尝试次数 .withStopStrategy(StopStrategies.stopAfterAttempt(retryable.attemptNumber())) // 重调策略 .withWaitStrategy(WaitStrategies.fixedWait(retryable.sleepTime(), retryable.timeUnit()))// 等待300毫秒 // 指定监听器RetryListener .withRetryListener(retryable.retryListener().newInstance()) .build(); } catch (Exception e) { logger.error(e.getMessage(), e); throw e; } try { // 执行方法 return retryer.call(task); } catch (ExecutionException e) { logger.error(e.getMessage(), e); } catch (RetryException e) {
logger.error(e.getMessage(), e); } return null; } private Object getTask(ProceedingJoinPoint joinPoint) { // 执行方法,并获取返回值 try { return joinPoint.proceed(); } catch (Throwable throwable) { logger.error(throwable.getMessage(), throwable); throw new RuntimeException("执行任务异常"); } } private Method getSpecificmethod(ProceedingJoinPoint pjp) { MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // The method may be on an interface, but we need attributes from the // target class. If the target class is null, the method will be // unchanged. Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget()); if (targetClass == null && pjp.getTarget() != null) { targetClass = pjp.getTarget().getClass(); } Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the // original method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); return specificMethod; } }
repos\spring-boot-student-master\spring-boot-student-guava-retrying\src\main\java\com\xiaolyuh\aspect\RetryAspect.java
2
请在Spring Boot框架中完成以下Java代码
public class LogBookConfig { @Bean public Logbook logbook() { Logbook logbook = Logbook.builder() .condition(Conditions.exclude(Conditions.requestTo("/api/welcome"), Conditions.contentType( "application/octet-stream"), Conditions.header("X-Secret", "true"))) .sink(new DefaultSink(new DefaultHttpLogFormatter(), new DefaultHttpLogWriter())) .build(); return logbook; } //@Bean public Logbook chunkSink() { Logbook logbook = Logbook.builder() .sink(new ChunkingSink(new CommonsLogFormatSink(new DefaultHttpLogWriter()), 1000)) .build(); return logbook; } //@Bean public Logbook compositesink() { CompositeSink comsink = new CompositeSink(Arrays.asList(new CommonsLogFormatSink(new DefaultHttpLogWriter()), new ExtendedLogFormatSink( new DefaultHttpLogWriter()))); Logbook logbook = Logbook.builder() .sink(comsink) .build(); return logbook; } // to run logstash example set spring.profiles.active=logbooklogstash in application.properties and enable following bean disabling all others //@Bean public Logbook logstashsink() {
HttpLogFormatter formatter = new JsonHttpLogFormatter(); LogstashLogbackSink logstashsink = new LogstashLogbackSink(formatter, Level.INFO); Logbook logbook = Logbook.builder() .sink(logstashsink) .build(); return logbook; } //@Bean public Logbook commonLogFormat() { Logbook logbook = Logbook.builder() .sink(new CommonsLogFormatSink(new DefaultHttpLogWriter())) .build(); return logbook; } //@Bean public Logbook extendedLogFormat() { Logbook logbook = Logbook.builder() .sink(new ExtendedLogFormatSink(new DefaultHttpLogWriter())) .build(); return logbook; } }
repos\tutorials-master\spring-boot-modules\spring-boot-logging-logback\src\main\java\com\baeldung\logbookconfig\LogBookConfig.java
2
请在Spring Boot框架中完成以下Java代码
private IHUQRCode getHUQRCode() { if (_huQRCode == null) { _huQRCode = huService.parsePickFromScannedCode(request.getHuScannedCode()); log("Parsed QR code: " + _huQRCode.getAsString()); } return _huQRCode; } private ExplainedOptional<HUInfo> resolvePickFromHUQRCode(@NonNull final PickingJobLine line) { return resolvedHUInfos.computeIfAbsent( line.getId(), k -> huService.resolvePickFromHUQRCode( getHUQRCode(), line.getProductId(), getCustomerId(line), getWarehouseId(line) )); } @NonNull private BPartnerId getCustomerId(@NonNull final PickingJobLine line) { return CoalesceUtil.coalesceSuppliersNotNull( line::getCustomerId, () -> getJob().getCustomerId() ); } @NonNull private WarehouseId getWarehouseId(@NonNull final PickingJobLine line) { final ShipmentScheduleId shipmentScheduleId = line.getScheduleId().getShipmentScheduleId(); return shipmentSchedules.getById(shipmentScheduleId).getWarehouseId(); }
private void log(@NonNull String message) { log(null, message); } private void log(@Nullable final PickingJobLine line, @NonNull String message) { final StringBuilder sb = new StringBuilder(); if (line != null) { sb.append("Line: ").append(line.getId().getRepoId()).append(" - "); } sb.append(message); String messageFinal = sb.toString(); logger.debug(messageFinal); logs.add(messageFinal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\get_next_eligible_line\GetNextEligibleLineToPackCommand.java
2
请在Spring Boot框架中完成以下Java代码
public class PurchaseOrderProjectListenerDispatcher { private static final Topic TOPIC = Topic.localAndAsync("de.metas.order.PurchaseOrderProjectListenerDispatcher.events"); @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); @NonNull private final IEventBus eventBus; @NonNull private final ImmutableList<PurchaseOrderProjectListener> listeners; public PurchaseOrderProjectListenerDispatcher( @NonNull final Optional<List<PurchaseOrderProjectListener>> listeners, @NonNull final IEventBusFactory eventBusFactory) { this.listeners = listeners.map(ImmutableList::copyOf).orElseGet(ImmutableList::of); this.eventBus = eventBusFactory.getEventBus(TOPIC); } @PostConstruct public void postConstruct() { this.eventBus.subscribeOn(ProjectCreatedEvent.class, this::handleEvent); } public void fireProjectCreatedEvent(@NonNull ProjectCreatedEvent event) { trxManager.accumulateAndProcessAfterCommit( TOPIC.getName(),
ImmutableList.of(event), this::fireProjectCreatedEventsNow ); } private void fireProjectCreatedEventsNow(@NonNull List<ProjectCreatedEvent> events) { final ImmutableSet<ProjectCreatedEvent> uniqueEvents = ImmutableSet.copyOf(events); eventBus.enqueueObjectsCollection(uniqueEvents); } private void handleEvent(@NonNull ProjectCreatedEvent event) { listeners.forEach(listener -> listener.onCreated(event)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\PurchaseOrderProjectListenerDispatcher.java
2
请完成以下Java代码
private boolean isUserInPolicy(SecurityPolicy ssp, String userId) { return (ssp.getUsers() != null && !ssp.getUsers().isEmpty() && ssp.getUsers().contains(userId)); } private boolean isGroupInPolicy(SecurityPolicy ssp, List<String> groups) { if (ssp.getGroups() != null && groups != null) { for (String g : ssp.getGroups()) { if (groups.contains(g)) { return true; } } } return false; } @Override public boolean canRead(String processDefinitionKey, String appName) { return hasPermission(processDefinitionKey, SecurityPolicyAccess.READ, appName); } @Override public boolean canWrite(String processDefinitionKey, String appName) { return hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, appName); } public boolean hasPermission( String processDefinitionKey, SecurityPolicyAccess securityPolicyAccess, String appName ) { // No security policies defined, allowed to see everything if (securityPoliciesProperties.getPolicies().isEmpty()) { return true; } // If you are an admin you can see everything , @TODO: make it more flexible if (securityManager.getAuthenticatedUserRoles().contains("ACTIVITI_ADMIN")) { return true;
} Set<String> keys = new HashSet<>(); Map<String, Set<String>> policiesMap = getAllowedKeys(securityPolicyAccess); if (policiesMap.get(appName) != null) { keys.addAll(policiesMap.get(appName)); } //also factor for case sensitivity and hyphens (which are stripped when specified through env var) if (appName != null && policiesMap.get(appName.replaceAll("-", "").toLowerCase()) != null) { keys.addAll(policiesMap.get(appName.replaceAll("-", "").toLowerCase())); } return ( anEntryInSetStartsKey(keys, processDefinitionKey) || keys.contains(securityPoliciesProperties.getWildcard()) ); } //startsWith logic supports the case of audit where only definition id might be available and it would start with the key //protected scope means we can override where exact matching more appropriate (consider keys ProcessWithVariables and ProcessWithVariables2) //even for audit would be better if we had a known separator which cant be part of key - this seems best we can do for now protected boolean anEntryInSetStartsKey(Set<String> keys, String processDefinitionKey) { for (String key : keys) { if (processDefinitionKey.startsWith(key)) { return true; } } return false; } protected SecurityPoliciesProperties getSecurityPoliciesProperties() { return securityPoliciesProperties; } }
repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\BaseSecurityPoliciesManagerImpl.java
1
请完成以下Java代码
public class UnlockCommand implements IUnlockCommand { // services private final transient ILockDatabase lockDatabase; // Lock parameters private LockOwner owner = null; // Records to lock private final LockRecords _recordsToUnlock = new LockRecords(); UnlockCommand(final ILockDatabase lockDatabase) { super(); Check.assumeNotNull(lockDatabase, "lockDatabase not null"); this.lockDatabase = lockDatabase; } @Override public String toString() { return ObjectUtils.toString(this); } @Override public int release() { return lockDatabase.unlock(this); } @Override public Future<Integer> releaseAfterTrxCommit(final String trxName) { final FutureValue<Integer> countUnlockedFuture = new FutureValue<>(); final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.getTrxListenerManagerOrAutoCommit(trxName) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> { try { final int countUnlocked = release(); countUnlockedFuture.set(countUnlocked); } catch (Exception e) { countUnlockedFuture.setError(e); } }); return countUnlockedFuture; } @Override public IUnlockCommand setOwner(final LockOwner owner) { this.owner = owner; return this; } @Override public final LockOwner getOwner() { Check.assumeNotNull(owner, UnlockFailedException.class, "owner not null"); return this.owner; } @Override 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
请完成以下Java代码
public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); }
@Override public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
public boolean isValidate() { if (validate == null) { return false; } else { return validate; } } /** * Sets the value of the validate property. * * @param value * allowed object is * {@link Boolean } * */ public void setValidate(Boolean value) { this.validate = value; } /** * Gets the value of the obligation property. * * @return * possible object is * {@link Boolean } * */ public boolean isObligation() { if (obligation == null) { return true; } else { return obligation; } } /** * Sets the value of the obligation property. * * @param value * allowed object is * {@link Boolean } * */ public void setObligation(Boolean value) { this.obligation = value; } /** * Gets the value of the sectionCode property. * * @return * possible object is * {@link String } * */ public String getSectionCode() { return sectionCode; } /** * Sets the value of the sectionCode property.
* * @param value * allowed object is * {@link String } * */ public void setSectionCode(String value) { this.sectionCode = value; } /** * Gets the value of the remark property. * * @return * possible object is * {@link String } * */ public String getRemark() { return remark; } /** * Sets the value of the remark property. * * @param value * allowed object is * {@link String } * */ public void setRemark(String value) { this.remark = value; } /** * Gets the value of the serviceAttributes property. * * @return * possible object is * {@link Long } * */ public long getServiceAttributes() { if (serviceAttributes == null) { return 0L; } else { return serviceAttributes; } } /** * Sets the value of the serviceAttributes property. * * @param value * allowed object is * {@link Long } * */ public void setServiceAttributes(Long value) { this.serviceAttributes = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordServiceType.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } public boolean hasTransientVariables() { return transientVariables != null && transientVariables.size() > 0; } public Map<String, Object> getTransientVariables() { return transientVariables; } @Override public CaseReactivationBuilder addTerminatedPlanItemInstanceForPlanItemDefinition(String planItemDefinitionId) { this.terminatedPlanItemDefinitionIds.add(planItemDefinitionId); return this; } @Override public CaseReactivationBuilder variable(String name, Object value) { if (variables == null) { variables = new HashMap<>(); } variables.put(name, value); return this; } @Override public CaseReactivationBuilder variables(Map<String, Object> variables) { if (this.variables == null) { this.variables = new HashMap<>(); } this.variables.putAll(variables); return this;
} @Override public CaseReactivationBuilder transientVariable(String name, Object value) { if (transientVariables == null) { transientVariables = new HashMap<>(); } transientVariables.put(name, value); return this; } @Override public CaseReactivationBuilder transientVariables(Map<String, Object> variables) { if (transientVariables == null) { transientVariables = new HashMap<>(); } transientVariables.putAll(variables); return this; } @Override public CaseInstance reactivate() { return commandExecutor.execute(new ReactivateHistoricCaseInstanceCmd(this)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\reactivation\CaseReactivationBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2Properties { public static final String PREFIX = CamundaBpmProperties.PREFIX + ".oauth2"; /** * OAuth2 SSO logout properties. */ @NestedConfigurationProperty private OAuth2SSOLogoutProperties ssoLogout = new OAuth2SSOLogoutProperties(); /** * OAuth2 identity provider properties. */ @NestedConfigurationProperty private OAuth2IdentityProviderProperties identityProvider = new OAuth2IdentityProviderProperties(); public static class OAuth2SSOLogoutProperties { /** * Enable SSO Logout. Default {@code false}. */ private boolean enabled = false; /** * URI the user is redirected after SSO logout from the provider. Default {@code {baseUrl}}. */ private String postLogoutRedirectUri = "{baseUrl}"; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getPostLogoutRedirectUri() { return postLogoutRedirectUri; } public void setPostLogoutRedirectUri(String postLogoutRedirectUri) { this.postLogoutRedirectUri = postLogoutRedirectUri; } } public static class OAuth2IdentityProviderProperties { /** * Enable {@link OAuth2IdentityProvider}. Default {@code true}. */ private boolean enabled = true; /** * Name of the attribute (claim) that holds the groups. */ private String groupNameAttribute; /** * Group name attribute delimiter. Only used if the {@link #groupNameAttribute} is a {@link String}.
*/ private String groupNameDelimiter = ","; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getGroupNameAttribute() { return groupNameAttribute; } public void setGroupNameAttribute(String groupNameAttribute) { this.groupNameAttribute = groupNameAttribute; } public String getGroupNameDelimiter() { return groupNameDelimiter; } public void setGroupNameDelimiter(String groupNameDelimiter) { this.groupNameDelimiter = groupNameDelimiter; } } public OAuth2SSOLogoutProperties getSsoLogout() { return ssoLogout; } public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) { this.ssoLogout = ssoLogout; } public OAuth2IdentityProviderProperties getIdentityProvider() { return identityProvider; } public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) { this.identityProvider = identityProvider; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
2
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (email == null ? 0 : email.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false;
} final User user = (User) obj; if (!email.equals(user.email)) { return false; } return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", email=").append(email).append(", roles=").append(roles).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\model\User.java
1
请完成以下Java代码
public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Steuerbetrag. @param TaxAmt Tax Amount for a document */ @Override public void setTaxAmt (java.math.BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
} /** Get Steuerbetrag. @return Tax Amount for a document */ @Override public java.math.BigDecimal getTaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Bezugswert. @param TaxBaseAmt Base for calculating the tax amount */ @Override public void setTaxBaseAmt (java.math.BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } /** Get Bezugswert. @return Base for calculating the tax amount */ @Override public java.math.BigDecimal getTaxBaseAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxBaseAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationLine.java
1
请完成以下Java代码
public boolean isLoading() { if (m_worker == null) { return false; } // Check for override. if (ignoreLoading) { return false; } return m_worker.isAlive(); } // metas: end
public void setIgnoreLoading(final boolean ignoreLoading) { this.ignoreLoading = ignoreLoading; } private static final Properties getCtx() { return Env.getCtx(); } private static final int getCtxAD_Client_ID() { return Env.getAD_Client_ID(getCtx()); } } // Info
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\Info.java
1
请在Spring Boot框架中完成以下Java代码
public I_AD_ClientInfo retrieveClientInfo(@CacheCtx final Properties ctx, final int adClientId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_ClientInfo.class, ctx, ITrx.TRXNAME_None) .addEqualsFilter(I_AD_ClientInfo.COLUMN_AD_Client_ID, adClientId) .create() .firstOnlyNotNull(I_AD_ClientInfo.class); } // get @Override public I_AD_ClientInfo retrieveClientInfo(final Properties ctx) { final int adClientId = Env.getAD_Client_ID(ctx); return retrieveClientInfo(ctx, adClientId); } // get @Override public ClientEMailConfig getEMailConfigById(@NonNull final ClientId clientId) { return emailConfigCache.getOrLoad(clientId, this::retrieveEMailConfigById); } private ClientEMailConfig retrieveEMailConfigById(final @NonNull ClientId clientId) { final I_AD_Client record = getById(clientId); return toClientEMailConfig(record); } public static ClientEMailConfig toClientEMailConfig(@NonNull final I_AD_Client client) { return ClientEMailConfig.builder() .clientId(ClientId.ofRepoId(client.getAD_Client_ID())) .mailbox(extractMailbox(client)) .build(); } private static ExplainedOptional<Mailbox> extractMailbox(@NonNull final I_AD_Client client) { final EMailAddress email = EMailAddress.ofNullableString(client.getRequestEMail()); if (email == null) { return ExplainedOptional.emptyBecause("AD_Client.RequestEMail not set"); } return ExplainedOptional.of( Mailbox.builder() .type(MailboxType.SMTP) .email(email) .smtpConfig(extractSMTPConfig(client)) .build() ); } private static SMTPConfig extractSMTPConfig(@NonNull final I_AD_Client client) { return SMTPConfig.builder() .smtpHost(client.getSMTPHost())
.smtpPort(client.getSMTPPort()) .smtpAuthorization(client.isSmtpAuthorization()) .username(client.getRequestUser()) .password(client.getRequestUserPW()) .startTLS(client.isStartTLS()) .build(); } @Override public ClientMailTemplates getClientMailTemplatesById(final ClientId clientId) { return emailTemplatesCache.getOrLoad(clientId, this::retrieveClientMailTemplatesById); } private ClientMailTemplates retrieveClientMailTemplatesById(final ClientId clientId) { final I_AD_Client record = getById(clientId); return toClientMailTemplates(record); } private static ClientMailTemplates toClientMailTemplates(@NonNull final I_AD_Client record) { return ClientMailTemplates.builder() .passwordResetMailTemplateId(MailTemplateId.optionalOfRepoId(record.getPasswordReset_MailText_ID())) .build(); } @Override public boolean isMultilingualDocumentsEnabled(@NonNull final ClientId adClientId) { final I_AD_Client client = getById(adClientId); return client.isMultiLingualDocument(); } @Override public String getClientNameById(@NonNull final ClientId clientId) { return getById(clientId).getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ClientDAO.java
2
请完成以下Java代码
public void setDocBaseType (java.lang.String DocBaseType) { set_Value (COLUMNNAME_DocBaseType, DocBaseType); } /** Get Document BaseType. @return Logical type of document */ @Override public java.lang.String getDocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_DocBaseType); } @Override public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class); } @Override public void setM_Warehouse(org.compiere.model.I_M_Warehouse M_Warehouse) { set_ValueFromPO(COLUMNNAME_M_Warehouse_ID, org.compiere.model.I_M_Warehouse.class, M_Warehouse); } /** Set Lager. @param M_Warehouse_ID Lager oder Ort für Dienstleistung */ @Override public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } /** Get Lager. @return Lager oder Ort für Dienstleistung */ @Override
public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Lagerzuordnung. @param M_Warehouse_Routing_ID Lagerzuordnung */ @Override public void setM_Warehouse_Routing_ID (int M_Warehouse_Routing_ID) { if (M_Warehouse_Routing_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_Routing_ID, Integer.valueOf(M_Warehouse_Routing_ID)); } /** Get Lagerzuordnung. @return Lagerzuordnung */ @Override public int getM_Warehouse_Routing_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Routing_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\eevolution\model\X_M_Warehouse_Routing.java
1
请完成以下Java代码
public final class HUPIItemProductRetainOnePerPIFilter implements IQueryFilter<I_M_HU_PI_Item_Product> { private final boolean allowDifferentCapacities; private final Set<ArrayKey> seenSet = new HashSet<>(); public HUPIItemProductRetainOnePerPIFilter(final boolean allowDifferentCapacities) { super(); this.allowDifferentCapacities = allowDifferentCapacities; } public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public boolean accept(final I_M_HU_PI_Item_Product itemProduct) { final Object capacityKey = createCapacityKey(itemProduct); final int piItemId = itemProduct.getM_HU_PI_Item_ID(); if (!seenSet.add(Util.mkKey(I_M_HU_PI_Item.Table_Name, piItemId, capacityKey))) { // already added return false; } final I_M_HU_PI_Item piItem = itemProduct.getM_HU_PI_Item(); if (!piItem.isActive()) { return false; } final int piVersionId = piItem.getM_HU_PI_Version_ID(); if (!seenSet.add(Util.mkKey(I_M_HU_PI_Version.Table_Name, piVersionId, capacityKey))) { // already added return false; } final I_M_HU_PI_Version piVersion = piItem.getM_HU_PI_Version(); if (!piVersion.isActive())
{ return false; } if (!piVersion.isCurrent()) { return false; } final int piId = piVersion.getM_HU_PI_ID(); if (!seenSet.add(Util.mkKey(I_M_HU_PI.Table_Name, piId, capacityKey))) { // already added return false; } // if (!Services.get(IHandlingUnitsBL.class).isConcretePI(piId)) // { // // skip Virtual PIs, No HU PIs // return false; // } return true; } private Object createCapacityKey(final I_M_HU_PI_Item_Product itemProduct) { if (!allowDifferentCapacities) { return null; } else if (itemProduct.isInfiniteCapacity()) { return "INFINITE"; } else { return itemProduct.getQty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductRetainOnePerPIFilter.java
1
请完成以下Java代码
public void setIsConfirmed (boolean IsConfirmed) { set_ValueNoCheck (COLUMNNAME_IsConfirmed, Boolean.valueOf(IsConfirmed)); } /** Get Confirmed. @return Assignment is confirmed */ public boolean isConfirmed () { Object oo = get_Value(COLUMNNAME_IsConfirmed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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 Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Resource Assignment. @param S_ResourceAssignment_ID Resource Assignment */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{ if (S_ResourceAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Resource Assignment. @return Resource Assignment */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Resource getS_Resource() throws RuntimeException { return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name) .getPO(getS_Resource_ID(), get_TrxName()); } /** Set Resource. @param S_Resource_ID Resource */ public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Resource. @return Resource */ public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceAssignment.java
1
请在Spring Boot框架中完成以下Java代码
ActiveMQConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { return createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails); } private static ActiveMQConnectionFactory createJmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(), connectionDetails.getPassword(), connectionDetails.getBrokerUrl()); new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList()) .configure(connectionFactory); return connectionFactory; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true) static class CachingConnectionFactoryConfiguration { @Bean CachingConnectionFactory jmsConnectionFactory(JmsProperties jmsProperties, ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory( createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails)); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); return connectionFactory; } } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class })
static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") @ConditionalOnBooleanProperty("spring.activemq.pool.enabled") JmsPoolConnectionFactory jmsConnectionFactory(ActiveMQProperties properties, ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers, ActiveMQConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(), connectionDetails.getPassword(), connectionDetails.getBrokerUrl()); new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList()) .configure(connectionFactory); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQConnectionFactoryConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class MigratorService implements IMigratorService { private static final transient Logger logger = LogManager.getLogger(MigratorService.class); @Override public void testMigratePartition(final Partition partition) { final ITrxManager trxManager = Services.get(ITrxManager.class); final String localTrxName = trxManager.createTrxName("testMigratePartition", false); final int initialDLMLevelBkp = partition.getCurrentDLMLevel(); if (initialDLMLevelBkp >= DLM_Level_TEST) { Loggables.withLogger(logger, Level.WARN).addLog( "testMigratePartition can't test partition because its DLM level is already {}; partition={}", initialDLMLevelBkp, partition); return; // do nothing } ITrx localTrx = null; try { localTrx = trxManager.get(localTrxName, OnTrxMissingPolicy.CreateNew); final PlainContextAware ctxAware = PlainContextAware.newWithTrxName(Env.getCtx(), localTrxName); localTrx.start(); updateDLMLevel0(partition, DLM_Level_TEST, ctxAware); localTrx.commit(true); logger.info("Update of all records with DLM_Partition_ID={} to DLM_Level={} succeeeded!", partition.getDLM_Partition_ID(), DLM_Level_TEST); localTrx.start(); updateDLMLevel0(partition, initialDLMLevelBkp, ctxAware); localTrx.commit(true); } catch (final SQLException e) { throw DBException.wrapIfNeeded(e); }
finally { localTrx.close(); } // if we got here without a DLMException, then the partition can be migrated } @Override public Partition migratePartition(final Partition partition) { final int targetDlmLevel = partition.getTargetDLMLevel(); return updateDLMLevel0(partition, targetDlmLevel, PlainContextAware.newWithThreadInheritedTrx(Env.getCtx())); } private Partition updateDLMLevel0(final Partition partition, final int targetDlmLevel, final IContextAware ctxAware) { // wed need to partition-ID, otherwise we can't identifiey the DB-records to update Check.errorIf(partition.getDLM_Partition_ID() <= 0, "Partition={} has no DLM_Partition_ID", partition); final IDLMService dlmService = Services.get(IDLMService.class); dlmService.directUpdateDLMColumn(ctxAware, partition.getDLM_Partition_ID(), IDLMAware.COLUMNNAME_DLM_Level, targetDlmLevel); return partition.withCurrentDLMLevel(targetDlmLevel); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\migrator\impl\MigratorService.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isMember(String name) { return this.members.test(name); } @Override public boolean showComponents(SecurityContext securityContext) { Show show = (this.showComponents != null) ? this.showComponents : this.showDetails; return show.isShown(securityContext, this.roles); } @Override public boolean showDetails(SecurityContext securityContext) { return this.showDetails.isShown(securityContext, this.roles); }
@Override public StatusAggregator getStatusAggregator() { return this.statusAggregator; } @Override public HttpCodeStatusMapper getHttpCodeStatusMapper() { return this.httpCodeStatusMapper; } @Override public @Nullable AdditionalHealthEndpointPath getAdditionalPath() { return this.additionalPath; } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\AutoConfiguredHealthEndpointGroup.java
2
请完成以下Java代码
public boolean isInternal () { Object oo = get_Value(COLUMNNAME_IsInternal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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 Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Seller.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; } public String getPlanItemInstanceId() { return planItemInstanceId; } public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java
2
请完成以下Java代码
class CompatibleOnEnabledEndpointCondition implements Condition { static String[] CONDITION_CLASS_NAMES = { "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition", // 2.2.0+ "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition" // [2.0.0 , 2.2.x] }; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { ClassLoader classLoader = context.getClassLoader(); Condition condition = Stream.of(CONDITION_CLASS_NAMES) // Iterate class names .filter(className -> ClassUtils.isPresent(className, classLoader)) // Search class existing or not by name .findFirst() // Find the first candidate .map(className -> ClassUtils.resolveClassName(className, classLoader)) // Resolve class name to Class .filter(Condition.class::isAssignableFrom) // Accept the Condition implementation
.map(BeanUtils::instantiateClass) // Instantiate Class to be instance .map(Condition.class::cast) // Cast the instance to be Condition one .orElse(NegativeCondition.INSTANCE); // Or else get a negative condition return condition.matches(context, metadata); } private static class NegativeCondition implements Condition { static final NegativeCondition INSTANCE = new NegativeCondition(); @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return false; } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\condition\CompatibleOnEnabledEndpointCondition.java
1
请完成以下Java代码
public Boolean execute(CommandContext commandContext) { AbstractEngineConfiguration engineConfiguration = commandContext.getEngineConfigurations().get(engineType); PropertyEntityManager propertyEntityManager = engineConfiguration.getPropertyEntityManager(); PropertyEntity property = propertyEntityManager.findById(lockName); if (property == null) { property = propertyEntityManager.create(); property.setName(lockName); // The format of the value is the current time in ISO8601 - hostName(hostAddress) property.setValue(Instant.now().toString() + hostLockDescription); propertyEntityManager.insert(property); return true; } else if (property.getValue() == null) { property.setValue(Instant.now().toString() + hostLockDescription); return true; } else if (forceAcquireAfter != null) { // If the lock is held longer than the force acquire duration we have to force the lock acquire
// e.g. if the lock was acquired at 17:00 // When the forceAcquireAfter is 10 minutes it means that the lock should be force acquired // when the time is after 17:10, i.e. acquireLock + forceAcquire < now (17:10) String value = property.getValue(); Instant lockAcquireTime = Instant.parse(value.substring(0, value.indexOf('Z') + 1)); if (lockAcquireTime.plus(forceAcquireAfter).isBefore(Instant.now())) { property.setValue(Instant.now().toString() + hostLockDescription); return true; } return false; } else { return false; } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cmd\LockCmd.java
1
请完成以下Java代码
public RemotePurchaseOrderCreated placePurchaseOrder(@NonNull final PurchaseOrderRequest request) { final BPartnerId vendorId = BPartnerId.ofRepoId(request.getVendorId()); final MSV3ClientConfig config = configRepo.getByVendorId(vendorId); final MSV3PurchaseOrderClient client = getClientFactory(config.getVersion()) .newPurchaseOrderClient(config); return client.prepare(request).placeOrder(); } @Override public void associateLocalWithRemotePurchaseOrderId( @NonNull final LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated) { final RemotePurchaseOrderCreatedItem item = localPurchaseOrderForRemoteOrderCreated.getRemotePurchaseOrderCreatedItem();
final I_MSV3_BestellungAnteil anteilRecord = Services.get(IQueryBL.class).createQueryBuilder(I_MSV3_BestellungAnteil.class) .addEqualsFilter(I_MSV3_BestellungAnteil.COLUMN_MSV3_BestellungAnteil_ID, item.getInternalItemId()) .create() .firstOnlyNotNull(I_MSV3_BestellungAnteil.class); anteilRecord.setC_OrderLinePO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderLineId()); save(anteilRecord); final I_MSV3_BestellungAntwortAuftrag bestellungAntwortAuftrag = anteilRecord .getMSV3_BestellungAntwortPosition() .getMSV3_BestellungAntwortAuftrag(); bestellungAntwortAuftrag.setC_OrderPO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderId()); save(bestellungAntwortAuftrag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3VendorGatewayService.java
1
请完成以下Java代码
public static int toOrderLineRepoId(@Nullable final OrderAndLineId orderAndLineId) { return getOrderLineRepoIdOr(orderAndLineId, -1); } public static int getOrderLineRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue) { return orderAndLineId != null ? orderAndLineId.getOrderLineRepoId() : defaultValue; } public static Set<Integer> getOrderLineRepoIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineRepoId).collect(ImmutableSet.toImmutableSet()); } public static Set<OrderId> getOrderIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderId).collect(ImmutableSet.toImmutableSet()); } public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds) { return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet()); } OrderId orderId; OrderLineId orderLineId; private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId) { this.orderId = orderId; this.orderLineId = orderLineId; } public int getOrderRepoId() { return orderId.getRepoId();
} public int getOrderLineRepoId() { return orderLineId.getRepoId(); } public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2) { return Objects.equals(o1, o2); } @JsonValue public String toJson() { return orderId.getRepoId() + "_" + orderLineId.getRepoId(); } @JsonCreator public static OrderAndLineId ofJson(@NonNull String json) { try { final int idx = json.indexOf("_"); return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1))); } catch (Exception ex) { throw new AdempiereException("Invalid JSON: " + json, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipperId implements RepoIdAware { int repoId; private ShipperId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_Shipper_ID"); } @JsonCreator public static ShipperId ofRepoId(final int repoId) { return new ShipperId(repoId); } @Nullable public static ShipperId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new ShipperId(repoId) : null; } public static Optional<ShipperId> optionalOfRepoId(final int repoId)
{ return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final ShipperId shipperId) { return shipperId != null ? shipperId.getRepoId() : -1; } public static boolean equals(@Nullable final ShipperId id1, @Nullable final ShipperId id2) {return Objects.equals(id1, id2);} @JsonValue public int toJson() { return getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\shipping\ShipperId.java
2
请在Spring Boot框架中完成以下Java代码
public XmlService withMod(@Nullable final ServiceModWithSelector.ServiceMod serviceMod) { if (serviceMod == null) { return this; } return withModNonNull(serviceMod); } @Override public String getName() { return name; } public XMLGregorianCalendar getDateBegin() { return dateBegin; } public BigDecimal getAmount() { return amount;
} public BigDecimal getExternalFactor() { return externalFactor; } @Override public XmlService withModNonNull(final ServiceModWithSelector.ServiceMod serviceMod) { return toBuilder() .amount(serviceMod.getAmount()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\body\service\XmlRecordServiceType.java
2
请完成以下Java代码
private AbstractScriptsApplierTemplate createDummyScriptsApplier(final IDatabase db, final CreateDBFromTemplateScript dbScript) { final AbstractScriptsApplierTemplate prepareNewDBCopy = new AbstractScriptsApplierTemplate() { @Override protected IScriptFactory createScriptFactory() { return new RolloutDirScriptFactory(); } @Override protected void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory) { scriptExecutorFactory.setDryRunMode(false); } @Override protected IScriptScanner createScriptScanner(final IScriptScannerFactory scriptScannerFactory) { final IScriptScanner result = new SingletonScriptScanner(dbScript);
return result; } @Override protected IScriptsApplierListener createScriptsApplierListener() { return NullScriptsApplierListener.instance; } @Override protected IDatabase createDatabase() { return db; }; }; return prepareNewDBCopy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBCopyMaker.java
1
请完成以下Java代码
public void preventChangesIfContractActive(final I_PMM_Product pmmProduct) { if (Services.get(IPMMContractsDAO.class).hasRunningContracts(pmmProduct)) { throw new AdempiereException("@" + MSG_ProductChangeNotAllowedForRunningContracts + "@"); } } // NOTE: Always allow deactivating an PMM_Product even if it has a running contract. // See: https://github.com/metasfresh/metasfresh/issues/1817 // @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_PMM_Product.COLUMNNAME_IsActive }) // public void preventDeactivateIfContractActive(final I_PMM_Product pmmProduct) // { // if (!pmmProduct.isActive() && Services.get(IPMMContractsDAO.class).hasRunningContracts(pmmProduct)) // { // throw new AdempiereException("@" + MSG_ProductChangeNotAllowedForRunningContracts + "@"); // } // } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_PMM_Product.COLUMNNAME_M_Product_ID, I_PMM_Product.COLUMNNAME_M_AttributeSetInstance_ID, I_PMM_Product.COLUMNNAME_M_HU_PI_Item_Product_ID }) public void updateReadOnlyFields(final I_PMM_Product pmmProduct) { Services.get(IPMMProductBL.class).update(pmmProduct);
} @CalloutMethod(columnNames = { I_PMM_Product.COLUMNNAME_M_Product_ID, I_PMM_Product.COLUMNNAME_M_AttributeSetInstance_ID, I_PMM_Product.COLUMNNAME_M_HU_PI_Item_Product_ID }) public void updateReadOnlyFields(final I_PMM_Product pmmProduct, final ICalloutField unused) { Services.get(IPMMProductBL.class).update(pmmProduct); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_NEW }, // ifColumnsChanged = { I_PMM_Product.COLUMNNAME_IsActive, I_PMM_Product.COLUMNNAME_M_Product_ID, I_PMM_Product.COLUMNNAME_M_AttributeSetInstance_ID, I_PMM_Product.COLUMNNAME_M_HU_PI_Item_Product_ID, I_PMM_Product.COLUMNNAME_M_Warehouse_ID, } // , afterCommit = true) public void pushToWebUI(final I_PMM_Product pmmProduct) { Services.get(IWebuiPush.class).pushProduct(pmmProduct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\model\interceptor\PMM_Product.java
1
请在Spring Boot框架中完成以下Java代码
public BPartnerId getBpartnerId() { return purchaseInvoicePayableDoc.getBpartnerId(); } @Override public String getDocumentNo() { return purchaseInvoicePayableDoc.getDocumentNo(); } @Override public TableRecordReference getReference() { return purchaseInvoicePayableDoc.getReference(); } @Override public Money getAmountToAllocateInitial() { return purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getPayAmt().negate(); } @Override public Money getAmountToAllocate() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().negate(); } @Override public void addAllocatedAmt(final Money allocatedAmtToAdd) { purchaseInvoicePayableDoc.addAllocatedAmounts(AllocationAmounts.ofPayAmt(allocatedAmtToAdd.negate())); } /** * Check only the payAmt as that's the only value we are allocating. see {@link PurchaseInvoiceAsInboundPaymentDocumentWrapper#addAllocatedAmt(Money)} */ @Override public boolean isFullyAllocated() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().isZero(); } /** * Computes projected over under amt taking into account discount. * * @implNote for purchase invoices used as inbound payment, the discount needs to be subtracted from the open amount. */ @Override public Money calculateProjectedOverUnderAmt(final Money amountToAllocate) { final Money discountAmt = purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getDiscountAmt(); final Money openAmtWithDiscount = purchaseInvoicePayableDoc.getOpenAmtInitial().subtract(discountAmt); final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(purchaseInvoicePayableDoc.getTotalAllocatedAmount()); final Money adjustedAmountToAllocate = amountToAllocate.negate(); return remainingOpenAmtWithDiscount.subtract(adjustedAmountToAllocate); } @Override public boolean canPay(@NonNull final PayableDocument payable) { // A purchase invoice can compensate only on a sales invoice if (payable.getType() != PayableDocumentType.Invoice) { return false; } if (!payable.getSoTrx().isSales()) { return false;
} // if currency differs, do not allow payment return CurrencyId.equals(payable.getCurrencyId(), purchaseInvoicePayableDoc.getCurrencyId()); } @Override public CurrencyId getCurrencyId() { return purchaseInvoicePayableDoc.getCurrencyId(); } @Override public LocalDate getDate() { return purchaseInvoicePayableDoc.getDate(); } @Override public PaymentCurrencyContext getPaymentCurrencyContext() { return PaymentCurrencyContext.builder() .paymentCurrencyId(purchaseInvoicePayableDoc.getCurrencyId()) .currencyConversionTypeId(purchaseInvoicePayableDoc.getCurrencyConversionTypeId()) .build(); } @Override public Money getPaymentDiscountAmt() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getDiscountAmt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PurchaseInvoiceAsInboundPaymentDocumentWrapper.java
2
请完成以下Java代码
public FilterQuery filterOwner(String owner) { ensureNotNull("owner", owner); this.owner = owner; return this; } public FilterQuery orderByFilterId() { return orderBy(FilterQueryProperty.FILTER_ID); } public FilterQuery orderByFilterResourceType() { return orderBy(FilterQueryProperty.RESOURCE_TYPE); } public FilterQuery orderByFilterName() { return orderBy(FilterQueryProperty.NAME); }
public FilterQuery orderByFilterOwner() { return orderBy(FilterQueryProperty.OWNER); } public List<Filter> executeList(CommandContext commandContext, Page page) { return commandContext .getFilterManager() .findFiltersByQueryCriteria(this); } public long executeCount(CommandContext commandContext) { return commandContext .getFilterManager() .findFilterCountByQueryCriteria(this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\filter\FilterQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class PricingConditionsBreakMatchCriteria { @NonNull BigDecimal breakValue; ProductId productId; ProductCategoryId productCategoryId; BPartnerId productManufacturerId; AttributeValueId attributeValueId; public boolean breakValueMatches(final BigDecimal value) { return value.compareTo(breakValue) >= 0; } public boolean productMatchesAnyOf(@NonNull final Set<ProductAndCategoryAndManufacturerId> products) { Check.assumeNotEmpty(products, "products is not empty"); return products.stream().anyMatch(this::productMatches); } public boolean productMatches(@NonNull final ProductAndCategoryAndManufacturerId product) { return productMatches(product.getProductId()) && productCategoryMatches(product.getProductCategoryId()) && productManufacturerMatches(product.getProductManufacturerId()); } private boolean productMatches(final ProductId productId) { if (this.productId == null) { return true; } return Objects.equals(this.productId, productId); } private boolean productCategoryMatches(final ProductCategoryId productCategoryId) { if (this.productCategoryId == null) { return true; } return Objects.equals(this.productCategoryId, productCategoryId); } private boolean productManufacturerMatches(final BPartnerId productManufacturerId) { if (this.productManufacturerId == null)
{ return true; } if (productManufacturerId == null) { return false; } return Objects.equals(this.productManufacturerId, productManufacturerId); } public boolean attributeMatches(@NonNull final ImmutableAttributeSet attributes) { final AttributeValueId breakAttributeValueId = this.attributeValueId; if (breakAttributeValueId == null) { return true; } return attributes.hasAttributeValueId(breakAttributeValueId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakMatchCriteria.java
2
请完成以下Java代码
protected final BigDecimal extractAmountFromString(final String trxType, final String amountStringWithPosibleSpaces, final List<String> collectedErrors) { final String amountString = Util.replaceNonDigitCharsWithZero(amountStringWithPosibleSpaces); // 04551 BigDecimal amount = BigDecimal.ZERO; try { amount = new BigDecimal(amountString) .divide(Env.ONEHUNDRED, 2, RoundingMode.UNNECESSARY); if (trxType.endsWith(ESRConstants.ESRTRXTYPE_REVERSE_LAST_DIGIT)) { amount = amount.negate(); } // Important: the imported amount doesn't need to match the invoices' amounts } catch (final NumberFormatException e) { final String wrongNumberFormatAmount = msgBL.getMsg(Env.getCtx(), ERR_WRONG_NUMBER_FORMAT_AMOUNT, new Object[] { amountString }); collectedErrors.add(wrongNumberFormatAmount); } return amount; } protected final BigDecimal extractAmountFromString(final String amountString, final List<String> collectedErrors) { BigDecimal amount = BigDecimal.ZERO; try { amount = NumberUtils.asBigDecimal(amountString); } catch (final NumberFormatException e) { final String wrongNumberFormatAmount = msgBL.getMsg(Env.getCtx(), ERR_WRONG_NUMBER_FORMAT_AMOUNT, new Object[] { amountString }); collectedErrors.add(wrongNumberFormatAmount); } return amount; } /**
* * @param dateStr date string in format yyMMdd * @param collectedErrors * @return */ protected final Timestamp extractTimestampFromString(final String dateStr, final AdMessageKey failMessage, final List<String> collectedErrors) { final DateFormat df = new SimpleDateFormat("yyMMdd"); final Date date; try { date = df.parse(dateStr); return TimeUtil.asTimestamp(date); } catch (final ParseException e) { final String wrongDate = msgBL.getMsg(Env.getCtx(), failMessage, new Object[] { dateStr }); collectedErrors.add(wrongDate); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\spi\impl\AbstractESRPaymentStringParser.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractHttpConfigurer<T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, B> { private SecurityContextHolderStrategy securityContextHolderStrategy; /** * Disables the {@link AbstractHttpConfigurer} by removing it. After doing so a fresh * version of the configuration can be applied. * @return the {@link HttpSecurityBuilder} for additional customizations */ @SuppressWarnings("unchecked") public B disable() { getBuilder().removeConfigurer(getClass()); return getBuilder(); } @SuppressWarnings("unchecked") public T withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) { addObjectPostProcessor(objectPostProcessor); return (T) this; }
protected SecurityContextHolderStrategy getSecurityContextHolderStrategy() { if (this.securityContextHolderStrategy != null) { return this.securityContextHolderStrategy; } ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); this.securityContextHolderStrategy = context.getBeanProvider(SecurityContextHolderStrategy.class) .getIfUnique(SecurityContextHolder::getContextHolderStrategy); return this.securityContextHolderStrategy; } protected PathPatternRequestMatcher.Builder getRequestMatcherBuilder() { return getBuilder().getSharedObject(PathPatternRequestMatcher.Builder.class); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractHttpConfigurer.java
2
请完成以下Java代码
public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @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 setName_Invoice (final @Nullable java.lang.String Name_Invoice) { set_Value (COLUMNNAME_Name_Invoice, Name_Invoice); } @Override public java.lang.String getName_Invoice() { return get_ValueAsString(COLUMNNAME_Name_Invoice); } /** * NetDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int NETDAY_AD_Reference_ID=167; /** Sunday = 7 */ public static final String NETDAY_Sunday = "7"; /** Monday = 1 */ public static final String NETDAY_Monday = "1"; /** Tuesday = 2 */ public static final String NETDAY_Tuesday = "2"; /** Wednesday = 3 */ public static final String NETDAY_Wednesday = "3"; /** Thursday = 4 */ public static final String NETDAY_Thursday = "4"; /** Friday = 5 */ public static final String NETDAY_Friday = "5"; /** Saturday = 6 */ public static final String NETDAY_Saturday = "6"; @Override public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay()
{ return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setValue (final 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_PaymentTerm.java
1
请完成以下Java代码
protected boolean doProcess(TbActorMsg msg) { log.debug("Received message: {}", msg); if (msg.getMsgType().equals(MsgType.STATS_PERSIST_MSG)) { onStatsPersistMsg((StatsPersistMsg) msg); return true; } else { return false; } } public void onStatsPersistMsg(StatsPersistMsg msg) { if (msg.isEmpty()) { return; } systemContext.getEventService().saveAsync(StatisticsEvent.builder() .tenantId(msg.getTenantId()) .entityId(msg.getEntityId().getId()) .serviceId(systemContext.getServiceInfoProvider().getServiceId()) .messagesProcessed(msg.getMessagesProcessed()) .errorsOccurred(msg.getErrorsOccurred()) .build() ); } private JsonNode toBodyJson(String serviceId, long messagesProcessed, long errorsOccurred) { return JacksonUtil.newObjectNode().put("server", serviceId).put("messagesProcessed", messagesProcessed).put("errorsOccurred", errorsOccurred); }
public static class ActorCreator extends ContextBasedCreator { private final String actorId; public ActorCreator(ActorSystemContext context, String actorId) { super(context); this.actorId = actorId; } @Override public TbActorId createActorId() { return new TbStringActorId(actorId); } @Override public TbActor createActor() { return new StatsActor(context); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\stats\StatsActor.java
1
请在Spring Boot框架中完成以下Java代码
InitializingBean initRepositoryServiceForDeploymentResourceLoader( RepositoryService repositoryService, DeploymentResourceLoader deploymentResourceLoader ) { return () -> deploymentResourceLoader.setRepositoryService(repositoryService); } @Bean @ConditionalOnMissingBean(name = "variableTypeMap") public Map<String, VariableType> variableTypeMap( ObjectMapper objectMapper, DateFormatterProvider dateFormatterProvider ) { Map<String, VariableType> variableTypeMap = new HashMap<>(); variableTypeMap.put("boolean", new JavaObjectVariableType(Boolean.class)); variableTypeMap.put("string", new JavaObjectVariableType(String.class)); variableTypeMap.put("integer", new JavaObjectVariableType(Integer.class)); variableTypeMap.put("bigdecimal", new BigDecimalVariableType()); variableTypeMap.put("json", new JsonObjectVariableType(objectMapper)); variableTypeMap.put("file", new JsonObjectVariableType(objectMapper)); variableTypeMap.put("folder", new JsonObjectVariableType(objectMapper)); variableTypeMap.put("content", new JsonObjectVariableType(objectMapper)); variableTypeMap.put("date", new DateVariableType(Date.class, dateFormatterProvider)); variableTypeMap.put("datetime", new DateVariableType(Date.class, dateFormatterProvider)); variableTypeMap.put("array", new JsonObjectVariableType(objectMapper));
return variableTypeMap; } @Bean public VariableValidationService variableValidationService(Map<String, VariableType> variableTypeMap) { return new VariableValidationService(variableTypeMap); } @Bean public VariableParsingService variableParsingService(Map<String, VariableType> variableTypeMap) { return new VariableParsingService(variableTypeMap); } @Bean @ConditionalOnMissingBean public CachingProcessExtensionService cachingProcessExtensionService( ProcessExtensionService processExtensionService ) { return new CachingProcessExtensionService(processExtensionService); } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\conf\ProcessExtensionsAutoConfiguration.java
2
请完成以下Java代码
public TbLwM2MSecurityInfo getTbLwM2MSecurityInfoByEndpoint(String endpoint) { Lock lock = null; try (var connection = connectionFactory.getConnection()) { lock = redisLock.obtain(endpoint); lock.lock(); byte[] data = connection.get((SEC_EP + endpoint).getBytes()); if (data != null && data.length > 0) { return JavaSerDesUtil.decode(data); } else { return null; } } finally { if (lock != null) { lock.unlock(); } } } @Override public void remove(String endpoint) { Lock lock = null; try (var connection = connectionFactory.getConnection()) { lock = redisLock.obtain(endpoint); lock.lock(); byte[] data = connection.get((SEC_EP + endpoint).getBytes()); if (data != null && data.length > 0) { SecurityInfo info = ((TbLwM2MSecurityInfo) JavaSerDesUtil.decode(data)).getSecurityInfo(); if (info != null && info.getPskIdentity() != null) { connection.hDel(PSKID_SEC.getBytes(), info.getPskIdentity().getBytes()); } connection.del((SEC_EP + endpoint).getBytes()); } } finally { if (lock != null) {
lock.unlock(); } } } private String toLockKey(String endpoint) { return LOCK_EP + endpoint; } private SecurityMode getSecurityModeByRegistration (RedisConnection connection, String endpoint) { try { byte[] data = connection.get((REG_EP + endpoint).getBytes()); JsonNode registrationNode = JacksonUtil.fromString(new String(data != null ? data : new byte[0]), JsonNode.class); String typeModeStr = registrationNode.get("transportdata").get("identity").get("type").asText(); return "unsecure".equals(typeModeStr) ? SecurityMode.NO_SEC : null; } catch (Exception e) { log.error("Redis: Failed get SecurityMode by Registration, endpoint: [{}]", endpoint, e); return null; } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mRedisSecurityStore.java
1
请完成以下Java代码
public java.lang.String getOrgValue() { return get_ValueAsString(COLUMNNAME_OrgValue); } @Override public org.compiere.model.I_C_ElementValue getParentElementValue() { return get_ValueAsPO(COLUMNNAME_ParentElementValue_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setParentElementValue(final org.compiere.model.I_C_ElementValue ParentElementValue) { set_ValueFromPO(COLUMNNAME_ParentElementValue_ID, org.compiere.model.I_C_ElementValue.class, ParentElementValue); } @Override public void setParentElementValue_ID (final int ParentElementValue_ID) { if (ParentElementValue_ID < 1) set_Value (COLUMNNAME_ParentElementValue_ID, null); else set_Value (COLUMNNAME_ParentElementValue_ID, ParentElementValue_ID); } @Override public int getParentElementValue_ID() { return get_ValueAsInt(COLUMNNAME_ParentElementValue_ID); } @Override public void setParentValue (final @Nullable java.lang.String ParentValue) { set_Value (COLUMNNAME_ParentValue, ParentValue); } @Override public java.lang.String getParentValue() { return get_ValueAsString(COLUMNNAME_ParentValue); } @Override public void setPostActual (final boolean PostActual) { set_Value (COLUMNNAME_PostActual, PostActual); } @Override public boolean isPostActual() { return get_ValueAsBoolean(COLUMNNAME_PostActual); } @Override public void setPostBudget (final boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, PostBudget); } @Override public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance);
} @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void 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_I_ElementValue.java
1
请完成以下Java代码
public final void setBusyMessage (final String AD_Message) { m_glassPane.setMessage(AD_Message); } /** * Sets given busy message directly. No transaction or any other processing will be performed. * * @param message plain message to be set directly. */ public final void setBusyMessagePlain(final String message) { m_glassPane.setMessagePlain(message); } /** * Set and start Busy Counter * @param time in seconds */ public void setBusyTimer (int time) { m_glassPane.setBusyTimer (time); } // setBusyTimer /** * Set Maximize Window * @param max maximize */ public void setMaximize (boolean max) { m_maximize = max; } // setMaximize /** * Form Window Opened. * Maximize window if required * @param evt event */ private void formWindowOpened(java.awt.event.WindowEvent evt) { if (m_maximize == true) { super.setVisible(true); super.setExtendedState(JFrame.MAXIMIZED_BOTH); } } // formWindowOpened // Add window and tab no called from public void setProcessInfo(ProcessInfo pi) { m_pi = pi; } public ProcessInfo getProcessInfo() { return m_pi; } // End /** * Start Batch * @param process * @return running thread */ public Thread startBatch (final Runnable process) { Thread worker = new Thread() { @Override public void run() {
setBusy(true); process.run(); setBusy(false); } }; worker.start(); return worker; } // startBatch /** * @return Returns the AD_Form_ID. */ public int getAD_Form_ID () { return p_AD_Form_ID; } // getAD_Window_ID public int getWindowNo() { return m_WindowNo; } /** * @return Returns the manuBar */ public JMenuBar getMenu() { return menuBar; } public void showFormWindow() { if (m_panel instanceof FormPanel2) { ((FormPanel2)m_panel).showFormWindow(m_WindowNo, this); } else { AEnv.showCenterScreenOrMaximized(this); } } } // FormFrame
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java
1
请完成以下Java代码
public void onQtyTU_Set_Intercept(final I_DD_OrderLine ddOrderLine) { // Make sure the QtyCU is not changed for the second time if the QtyTU change was triggered by the QtyCU setting in the first place final boolean qtyCUChanged = InterfaceWrapperHelper.isValueChanged(ddOrderLine, I_DD_OrderLine.COLUMNNAME_QtyEntered); if (!qtyCUChanged) { updateQtyCU(ddOrderLine); } } @CalloutMethod(columnNames = { I_DD_OrderLine.COLUMNNAME_QtyEnteredTU }) public void onQtyTU_Set_Callout(final I_DD_OrderLine ddOrderLine) { // update QtyCU updateQtyCU(ddOrderLine); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_DD_OrderLine.COLUMNNAME_QtyEntered }) public void onQtyCU_Set_Intercept(final I_DD_OrderLine ddOrderLine) { // Make sure the QtyTU is not changed for the second time if the QtyCU change was triggered by the QtyTU setting in the first place final boolean qtyTUChanged = InterfaceWrapperHelper.isValueChanged(ddOrderLine, I_DD_OrderLine.COLUMNNAME_QtyEnteredTU); if (!qtyTUChanged) { updateQtyPacks(ddOrderLine); } } @CalloutMethod(columnNames = { I_DD_OrderLine.COLUMNNAME_QtyEntered }) public void onQtyCU_Set_Callout(final I_DD_OrderLine ddOrderLine)
{ // update QtyTU updateQtyPacks(ddOrderLine); } private void updateQtyPacks(final I_DD_OrderLine ddOrderLine) { final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware); } private void updateQtyCU(final I_DD_OrderLine ddOrderLine) { final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); // if the QtyTU was set to 0 or deleted, do nothing if (packingAware.getQtyTU().signum() <= 0) { return; } // if the QtyTU was changed but there is no M_HU_PI_Item_Product set, do nothing if (packingAware.getM_HU_PI_Item_Product_ID() <= 0) { return; } // update the QtyCU only if the QtyTU requires it. If the QtyCU is already fine and fits the QtyTU and M_HU_PI_Item_Product, leave it like it is. final QtyTU qtyPacks = QtyTU.ofBigDecimal(packingAware.getQtyTU()); final Quantity qtyCU = Quantitys.of(packingAware.getQty(), UomId.ofRepoId(packingAware.getC_UOM_ID())); Services.get(IHUPackingAwareBL.class).updateQtyIfNeeded(packingAware, qtyPacks.toInt(), qtyCU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\interceptor\DD_OrderLine.java
1
请完成以下Java代码
protected String getImportOrderBySql() { return I_I_BPartner_GlobalID.COLUMNNAME_GlobalId; } @Override public I_I_BPartner_GlobalID retrieveImportRecord(Properties ctx, ResultSet rs) throws SQLException { return new X_I_BPartner_GlobalID(ctx, rs, ITrx.TRXNAME_ThreadInherited); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override protected ImportRecordResult importRecord(@NonNull IMutable<Object> state,
@NonNull I_I_BPartner_GlobalID importRecord, final boolean isInsertOnly) { final IBPartnerDAO partnerDAO = Services.get(IBPartnerDAO.class); if (importRecord.getC_BPartner_ID() > 0 && !Check.isEmpty(importRecord.getURL3(), true)) { final I_C_BPartner bpartner = partnerDAO.getById(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID())); bpartner.setURL3(importRecord.getURL3()); InterfaceWrapperHelper.save(bpartner); return ImportRecordResult.Updated; } return ImportRecordResult.Nothing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\globalid\impexp\BPartnerGlobalIDImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public void persistTwoBooks() { Book ar = new Book(); ar.setIsbn("001-AR"); ar.setTitle("Ancient Rome"); ar.setPrice(25); // ar.setSku(1L); Book rh = new Book(); rh.setIsbn("001-RH"); rh.setTitle("Rush Hour"); rh.setPrice(31); // rh.setSku(2L); bookRepository.save(ar); bookRepository.save(rh); }
public Book fetchFirstBookByNaturalId() { // find the first book by a single natural id Optional<Book> foundArBook = bookNaturalRepository.findBySimpleNaturalId("001-AR"); // find first book by two natural ids (for running this code simply // uncomment the "sku" field in the Book entity and the below lines; comment lines 44 and 45) // Map<String, Object> ids = new HashMap<>(); // ids.put("sku", 1L); // ids.put("isbn", "001-AR"); // Optional<Book> foundArBook = bookNaturalRepository.findByNaturalId(ids); return foundArBook.orElseThrow(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalId\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
Response cancelSubscription(String subscriptionId) { boolean status = stripeService.cancelSubscription(subscriptionId); if (!status) { return new Response(false, "Failed to cancel the subscription. Please, try later."); } return new Response(true, "Subscription cancelled successfully."); } @PostMapping("/coupon-validator") public @ResponseBody Response couponValidator(String code) { Coupon coupon = stripeService.retrieveCoupon(code); if (coupon != null && coupon.getValid()) { String details = (coupon.getPercentOff() == null ? "$" + (coupon.getAmountOff() / 100) : coupon.getPercentOff() + "%") + " OFF " + coupon.getDuration(); return new Response(true, details); } else { return new Response(false, "This coupon code is not available. This may be because it has expired or has " + "already been applied to your account."); } }
@PostMapping("/create-charge") public @ResponseBody Response createCharge(String email, String token) { //validate data if (token == null) { return new Response(false, "Stripe payment token is missing. Please, try again later."); } //create charge String chargeId = stripeService.createCharge(email, token, 999); //$9.99 USD if (chargeId == null) { return new Response(false, "An error occurred while trying to create a charge."); } // You may want to store charge id along with order information return new Response(true, "Success! Your charge id is " + chargeId); } }
repos\springboot-demo-master\stripe\src\main\java\com\et\stripe\controller\PaymentController.java
2
请在Spring Boot框架中完成以下Java代码
public int getAccessTokenValidityInSeconds() { return accessTokenValidityInSeconds; } public void setAccessTokenValidityInSeconds(int accessTokenValidityInSeconds) { this.accessTokenValidityInSeconds = accessTokenValidityInSeconds; } public int getRefreshTokenValidityInSecondsForRememberMe() { return refreshTokenValidityInSecondsForRememberMe; } public void setRefreshTokenValidityInSecondsForRememberMe(int refreshTokenValidityInSecondsForRememberMe) { this.refreshTokenValidityInSecondsForRememberMe = refreshTokenValidityInSecondsForRememberMe; } public String getClientId() {
return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaProperties.java
2
请完成以下Java代码
public class ProprietaryQuantity1 { @XmlElement(name = "Tp", required = true) protected String tp; @XmlElement(name = "Qty", required = true) protected String qty; /** * Gets the value of the tp property. * * @return * possible object is * {@link String } * */ public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value; }
/** * Gets the value of the qty property. * * @return * possible object is * {@link String } * */ public String getQty() { return qty; } /** * Sets the value of the qty property. * * @param value * allowed object is * {@link String } * */ public void setQty(String value) { this.qty = 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\ProprietaryQuantity1.java
1
请在Spring Boot框架中完成以下Java代码
public Object createAscendingIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field)); } /** * 创建降序索引 * * @return 索引信息 */ public Object createDescendingIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.descending(field)); } /** * 创建升序复合索引 * * @return 索引信息 */ public Object createCompositeIndex() { // 设置字段名称 String field1 = "name"; String field2 = "age"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field1, field2)); } /** * 创建文字索引 * * @return 索引信息 */ public Object createTextIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.text(field)); } /** * 创建哈希索引 * * @return 索引信息 */
public Object createHashIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.hashed(field)); } /** * 创建升序唯一索引 * * @return 索引信息 */ public Object createUniqueIndex() { // 设置字段名称 String indexName = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置为唯一索引 options.unique(true); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(indexName), options); } /** * 创建局部索引 * * @return 索引信息 */ public Object createPartialIndex() { // 设置字段名称 String field = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置过滤条件 options.partialFilterExpression(Filters.exists("name", true)); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field), options); } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\CreateIndexService.java
2
请完成以下Java代码
public static ImmutableList<SqlViewRowFieldBinding> createViewFieldBindings( @NonNull final SqlDocumentEntityDataBindingDescriptor entityBinding, @NonNull final Collection<String> availableDisplayColumnNames) { return entityBinding.getFields() .stream() .map(documentField -> createViewFieldBinding(documentField, availableDisplayColumnNames)) .collect(ImmutableList.toImmutableList()); } public static SqlViewRowFieldBinding createViewFieldBinding( @NonNull final SqlDocumentFieldDataBindingDescriptor documentField, @NonNull final Collection<String> availableDisplayColumnNames) { final String fieldName = documentField.getFieldName(); final boolean isDisplayColumnAvailable = documentField.getSqlSelectDisplayValue() != null && availableDisplayColumnNames.contains(fieldName); return SqlViewRowFieldBinding.builder() .fieldName(fieldName) .columnName(documentField.getColumnName()) .keyColumn(documentField.isKeyColumn()) .widgetType(documentField.getWidgetType()) .virtualColumn(documentField.isVirtualColumn()) .mandatory(documentField.isMandatory()) .hideGridColumnIfEmpty(documentField.isHideGridColumnIfEmpty()) // .sqlValueClass(documentField.getSqlValueClass()) .sqlSelectValue(documentField.getSqlSelectValue()) .sqlSelectDisplayValue(isDisplayColumnAvailable ? documentField.getSqlSelectDisplayValue() : null) // .sqlOrderBy(documentField.getSqlOrderBy()) // .fieldLoader(createSqlViewRowFieldLoader(documentField, isDisplayColumnAvailable)) // .build(); } private static SqlViewRowFieldLoader createSqlViewRowFieldLoader( @NonNull final SqlDocumentFieldDataBindingDescriptor documentField, final boolean isDisplayColumnAvailable) { return new DocumentFieldValueLoaderAsSqlViewRowFieldLoader( documentField.getDocumentFieldValueLoader(), documentField.getLookupDescriptor(), isDisplayColumnAvailable); } private IViewInvalidationAdvisor getViewInvalidationAdvisor(final WindowId windowId) { return viewInvalidationAdvisorsByWindowId.getOrDefault(windowId, DefaultViewInvalidationAdvisor.instance); } @Value private static class DocumentFieldValueLoaderAsSqlViewRowFieldLoader implements SqlViewRowFieldLoader {
@NonNull DocumentFieldValueLoader fieldValueLoader; @Nullable LookupDescriptor lookupDescriptor; boolean isDisplayColumnAvailable; @Override @Nullable public Object retrieveValue(@NonNull final ResultSet rs, final String adLanguage) throws SQLException { return fieldValueLoader.retrieveFieldValue( rs, isDisplayColumnAvailable, adLanguage, lookupDescriptor); } } @Value private static class SqlViewBindingKey { @NonNull WindowId windowId; @Nullable Characteristic requiredFieldCharacteristic; @Nullable ViewProfileId profileId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBindingFactory.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<SysPositionSelectTreeVo>> getRankRelation(@RequestParam(name = "departId") String departId){ List<SysPositionSelectTreeVo> list = sysDepartService.getRankRelation(departId); return Result.ok(list); } /** * 根据部门code获取当前和上级部门名称 * * @param orgCode * @param depId * @return String 部门名称 */ @GetMapping("/getDepartPathNameByOrgCode") public Result<String> getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode, @RequestParam(name = "depId", required = false) String depId) { String departName = sysDepartService.getDepartPathNameByOrgCode(orgCode, depId); return Result.OK(departName); } /** * 根据部门id获取部门下的岗位id * * @param depIds 当前选择的公司、子公司、部门id * @return */ @GetMapping("/getDepPostIdByDepId") public Result<Map<String, String>> getDepPostIdByDepId(@RequestParam(name = "depIds") String depIds) { String departIds = sysDepartService.getDepPostIdByDepId(depIds); return Result.OK(departIds); } /** * 更新改变后的部门数据 * * @param changeDepartVo
* @return */ @PutMapping("/updateChangeDepart") @RequiresPermissions("system:depart:updateChange") @RequiresRoles({"admin"}) public Result<String> updateChangeDepart(@RequestBody SysChangeDepartVo changeDepartVo) { sysDepartService.updateChangeDepart(changeDepartVo); return Result.ok("调整部门位置成功!"); } /** * 获取部门负责人 * * @param departId * @return */ @GetMapping("/getDepartmentHead") public Result<IPage<SysUser>> getDepartmentHead(@RequestParam(name = "departId") String departId, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){ Page<SysUser> page = new Page<>(pageNo, pageSize); IPage<SysUser> pageList = sysDepartService.getDepartmentHead(departId,page); return Result.OK(pageList); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDepartController.java
2
请完成以下Java代码
public static BankStatementAndLineAndRefId ofRepoIds( final int bankStatementRepoId, final int bankStatementLineRepoId, final int bankStatementLineRefRepoId) { return of( BankStatementId.ofRepoId(bankStatementRepoId), BankStatementLineId.ofRepoId(bankStatementLineRepoId), BankStatementLineRefId.ofRepoId(bankStatementLineRefRepoId)); } public static BankStatementAndLineAndRefId of( final BankStatementId bankStatementId, final BankStatementLineId bankStatementLineId, final BankStatementLineRefId bankStatementLineRefId) { return new BankStatementAndLineAndRefId(bankStatementId, bankStatementLineId, bankStatementLineRefId); } BankStatementId bankStatementId; BankStatementLineId bankStatementLineId; BankStatementLineRefId bankStatementLineRefId;
private BankStatementAndLineAndRefId( @NonNull final BankStatementId bankStatementId, @NonNull final BankStatementLineId bankStatementLineId, @NonNull final BankStatementLineRefId bankStatementLineRefId) { this.bankStatementId = bankStatementId; this.bankStatementLineId = bankStatementLineId; this.bankStatementLineRefId = bankStatementLineRefId; } public static boolean equals(final BankStatementAndLineAndRefId o1, final BankStatementAndLineAndRefId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankStatementAndLineAndRefId.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PrescriptionRequest {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" patientBirthday: ").append(toIndentedString(patientBirthday)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" prescriptionType: ").append(toIndentedString(prescriptionType)).append("\n"); sb.append(" creationDate: ").append(toIndentedString(creationDate)).append("\n"); sb.append(" deliveryDate: ").append(toIndentedString(deliveryDate)).append("\n"); sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n"); sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n"); sb.append(" accountingMonths: ").append(toIndentedString(accountingMonths)).append("\n"); sb.append(" doctorId: ").append(toIndentedString(doctorId)).append("\n"); sb.append(" pharmacyId: ").append(toIndentedString(pharmacyId)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeIds: ").append(toIndentedString(therapyTypeIds)).append("\n"); sb.append(" prescriptedArticleLines: ").append(toIndentedString(prescriptedArticleLines)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).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\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\PrescriptionRequest.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * AD_Language AD_Reference_ID=106 * Reference name: AD_Language */ public static final int AD_LANGUAGE_AD_Reference_ID=106; @Override public void setAD_Language (final java.lang.String AD_Language) { set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language); } @Override public java.lang.String getAD_Language() { return get_ValueAsString(COLUMNNAME_AD_Language); } @Override public void setAD_Message_ID (final int AD_Message_ID) { if (AD_Message_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Message_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Message_ID, AD_Message_ID); } @Override public int getAD_Message_ID() { return get_ValueAsInt(COLUMNNAME_AD_Message_ID); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
} @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setMsgTip (final @Nullable java.lang.String MsgTip) { set_Value (COLUMNNAME_MsgTip, MsgTip); } @Override public java.lang.String getMsgTip() { return get_ValueAsString(COLUMNNAME_MsgTip); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message_Trl.java
1
请在Spring Boot框架中完成以下Java代码
public List<URL> getJarFileUrls() { return Collections.emptyList(); } @Override public URL getPersistenceUnitRootUrl() { return null; } @Override public List<String> getManagedClassNames() { return managedClassNames; } @Override public boolean excludeUnlistedClasses() { return false; } @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.UNSPECIFIED; } @Override public ValidationMode getValidationMode() { return ValidationMode.AUTO; } public Properties getProperties() { return properties; } @Override public String getPersistenceXMLSchemaVersion() { return JPA_VERSION;
} @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public void addTransformer(ClassTransformer transformer) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ClassLoader getNewTempClassLoader() { return null; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java
2
请完成以下Java代码
public List<HuId> getClosedLUs( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { final Set<HuId> pickedHuIds = pickingJob.getPickedHuIds(lineId); if (pickedHuIds.isEmpty()) { return ImmutableList.of(); } final HuId currentlyOpenedLUId = pickingJob.getLuPickingTarget(lineId) .map(LUPickingTarget::getLuId) .orElse(null); return handlingUnitsBL.getTopLevelHUs(IHandlingUnitsBL.TopLevelHusQuery.builder() .hus(handlingUnitsBL.getByIds(pickedHuIds)) .build()) .stream() .filter(handlingUnitsBL::isLoadingUnit) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .filter(huId -> !HuId.equals(huId, currentlyOpenedLUId)) .collect(ImmutableList.toImmutableList()); }
public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final PickingJob pickingJob) { return pickingJobService.getPickingSlotsSuggestions(pickingJob); } public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.pickAll(pickingJobId, callerId); } public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.getQtyAvailable(pickingJobId, callerId); } public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(final @NonNull GetNextEligibleLineToPackRequest request) { return pickingJobService.getNextEligibleLineToPack(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\PickingJobRestService.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoicePayScheduleRepository { @NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class); @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); private InvoicePayScheduleLoaderAndSaver newLoaderAndSaver() { return InvoicePayScheduleLoaderAndSaver.builder() .queryBL(queryBL) .trxManager(trxManager) .build(); } public void create(@NonNull final InvoicePayScheduleCreateRequest request) { request.getLines().forEach(line -> createLine(line, request.getInvoiceId())); } private void createLine(@NonNull final InvoicePayScheduleCreateRequest.Line request, @NonNull final InvoiceId invoiceId) { final I_C_InvoicePaySchedule record = newInstance(I_C_InvoicePaySchedule.class); record.setC_Invoice_ID(invoiceId.getRepoId()); InvoicePayScheduleConverter.updateRecord(record, request); saveRecord(record); } public void deleteByInvoiceId(@NonNull final InvoiceId invoiceId) { queryBL.createQueryBuilder(I_C_InvoicePaySchedule.class) .addEqualsFilter(I_C_InvoicePaySchedule.COLUMNNAME_C_Invoice_ID, invoiceId) .create() .delete(); }
public void updateById(@NonNull final InvoiceId invoiceId, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateById(invoiceId, updater); } public void updateByIds(@NonNull final Set<InvoiceId> invoiceIds, @NonNull final Consumer<InvoicePaySchedule> updater) { newLoaderAndSaver().updateByIds(invoiceIds, updater); } public Optional<InvoicePaySchedule> getByInvoiceId(@NonNull final InvoiceId invoiceId) { return newLoaderAndSaver().loadByInvoiceId(invoiceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\repository\InvoicePayScheduleRepository.java
2
请完成以下Java代码
public String getId() { return deployment.getId(); } public String getName() { return deployment.getName(); } public Date getDeploymentTime() { return deployment.getDeploymentTime(); } public String getSource() { return deployment.getSource(); } public String getTenantId() { return deployment.getTenantId(); } public ProcessApplicationRegistration getProcessApplicationRegistration() { return registration; } @Override
public List<ProcessDefinition> getDeployedProcessDefinitions() { return deployment.getDeployedProcessDefinitions(); } @Override public List<CaseDefinition> getDeployedCaseDefinitions() { return deployment.getDeployedCaseDefinitions(); } @Override public List<DecisionDefinition> getDeployedDecisionDefinitions() { return deployment.getDeployedDecisionDefinitions(); } @Override public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() { return deployment.getDeployedDecisionRequirementsDefinitions(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessApplicationDeploymentImpl.java
1
请完成以下Java代码
private String getModelTrxName() { return InterfaceWrapperHelper.getTrxName(model); } private int getModelTableId() { return modelTableId; } private int getModelRecordId() { return modelRecordId; } private final <RT> RT loadModel(final Properties ctx, final int adTableId, final int recordId, final Class<RT> modelClass, final String trxName) { final String tableName = Services.get(IADTableDAO.class).retrieveTableName(adTableId); final RT modelCasted = InterfaceWrapperHelper.create(ctx, tableName, recordId, modelClass, trxName); setModel(modelCasted, modelTableId, modelRecordId); return modelCasted;
} private final void setModel(final Object model, int adTableId, int recordId) { this.model = model; this.modelTableId = adTableId; this.modelRecordId = recordId; } private final void resetModel() { this.model = null; this.modelTableId = -1; this.modelRecordId = -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableRecordCacheLocal.java
1
请完成以下Java代码
public class NameResolverRegistration implements DisposableBean { private final List<NameResolverRegistry> registries = new ArrayList<>(1); private final List<NameResolverProvider> providers; /** * Creates a new NameResolverRegistration with the given list of providers. * * @param providers The providers that should be managed. */ public NameResolverRegistration(List<NameResolverProvider> providers) { this.providers = providers == null ? ImmutableList.of() : ImmutableList.copyOf(providers); } /** * Register all NameResolverProviders in the given registry and store a reference to it for later de-registration. * * @param registry The registry to add the providers to. */ public void register(NameResolverRegistry registry) { this.registries.add(registry); for (NameResolverProvider provider : this.providers) { try { registry.register(provider); log.debug("{} is available -> Added to the NameResolverRegistry", provider);
} catch (IllegalArgumentException e) { log.debug("{} is not available -> Not added to the NameResolverRegistry", provider); } } } @Override public void destroy() { for (NameResolverRegistry registry : this.registries) { for (NameResolverProvider provider : this.providers) { registry.deregister(provider); log.debug("{} was removed from the NameResolverRegistry", provider); } } this.registries.clear(); } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\nameresolver\NameResolverRegistration.java
1
请在Spring Boot框架中完成以下Java代码
public Region<K, V> getRegion() { return getDelegate().getRegion(); } @Override public CacheStatistics getStatistics() { return getDelegate().getStatistics(); } @Override public Object setUserAttribute(Object userAttribute) { return getDelegate().setUserAttribute(userAttribute); } @Override public Object getUserAttribute() {
return getDelegate().getUserAttribute(); } @Override public V setValue(V value) { return getDelegate().setValue(value); } @Override @SuppressWarnings("unchecked") public V getValue() { return (V) PdxInstanceWrapper.from(getDelegate().getValue()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java
2
请完成以下Java代码
public class MybatisPropertyDataManager extends AbstractDataManager<PropertyEntity> implements PropertyDataManager { protected IdGenerator idGenerator; public MybatisPropertyDataManager(IdGenerator idGenerator) { this.idGenerator = idGenerator; } @Override public Class<? extends PropertyEntity> getManagedEntityClass() { return PropertyEntityImpl.class; } @Override public PropertyEntity create() { return new PropertyEntityImpl(); } @Override public void directInsertProperty(String name, String value) { HashMap<String, Object> params = new HashMap<>(); params.put("name", name);
params.put("value", value); getDbSqlSession().directInsert("insertPropertyWithMap", params); } @Override @SuppressWarnings("unchecked") public List<PropertyEntity> findAll() { return getDbSqlSession().selectList("selectProperties"); } @Override protected IdGenerator getIdGenerator() { return idGenerator; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\data\impl\MybatisPropertyDataManager.java
1
请完成以下Java代码
public ClientSetup setPhone(final String phone) { if (!Check.isEmpty(phone, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setPhone(phone.trim()); } return this; } public final String getPhone() { return orgContact.getPhone(); } public ClientSetup setFax(final String fax) { if (!Check.isEmpty(fax, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setFax(fax.trim()); } return this; } public final String getFax() { return orgContact.getFax(); } public ClientSetup setEMail(final String email) { if (!Check.isEmpty(email, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setEMail(email.trim()); } return this;
} public final String getEMail() { return orgContact.getEMail(); } public ClientSetup setBPartnerDescription(final String bpartnerDescription) { if (Check.isEmpty(bpartnerDescription, true)) { return this; } orgBPartner.setDescription(bpartnerDescription.trim()); return this; } public String getBPartnerDescription() { return orgBPartner.getDescription(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
1
请在Spring Boot框架中完成以下Java代码
public AsyncReporter<Span> spanReporter() { return AsyncReporter.create(sender()); } /** * Controls aspects of tracing such as the service name that shows up in the UI */ @Bean public Tracing tracing(@Value("${spring.application.name}") String serviceName) { return Tracing.newBuilder() .localServiceName(serviceName) // .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder() // .addScopeDecorator(MDCScopeDecorator.create()) // puts trace IDs into logs // .build() // ) .spanReporter(spanReporter()).build(); } /** * Allows someone to add tags to a span if a trace is in progress */ @Bean public SpanCustomizer spanCustomizer(Tracing tracing) { return CurrentSpanCustomizer.create(tracing); } // ==================== HTTP 相关 ==================== /** * Decides how to name and tag spans. By default they are named the same as the http method */ @Bean public HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.create(tracing); } /** * Creates server spans for http requests */ @Bean public Filter tracingFilter(HttpTracing httpTracing) { return TracingFilter.create(httpTracing); } // ==================== SpringMVC 相关 ==================== // @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) // ==================== HttpClient 相关 ==================== @Bean public RestTemplateCustomizer useTracedHttpClient(HttpTracing httpTracing) { // 创建 CloseableHttpClient 对象,内置 HttpTracing 进行 HTTP 链路追踪。 final CloseableHttpClient httpClient = TracingHttpClientBuilder.create(httpTracing).build(); // 创建 RestTemplateCustomizer 对象 return new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient)); } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-demo\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请完成以下Java代码
public void collect(final I_DD_Order ddOrder) { final DDOrderId ddOrderId = extractDDOrderId(ddOrder); if (!seenDDOrderIds.add(ddOrderId)) { return; } collectedDDOrders.add(ddOrder); } @Override public List<DDOrderReference> getCollectedItems() { processPendingRequests(); return _result; } @NonNull private DistributionJobLoader newLoader() { return new DistributionJobLoader(loadingSupportServices); } private void processPendingRequests() { if (collectedDDOrders.isEmpty()) {return;} newLoader() .loadByRecords(collectedDDOrders) .stream() .map(DDOrderReferenceCollector::toDDOrderReference) .forEach(_result::add); collectedDDOrders.clear(); } @NonNull
private static DDOrderReference toDDOrderReference(final DistributionJob job) { return DDOrderReference.builder() .ddOrderId(job.getDdOrderId()) .documentNo(job.getDocumentNo()) .seqNo(job.getSeqNo()) .datePromised(job.getDateRequired()) .pickDate(job.getPickDate()) .fromWarehouseId(job.getPickFromWarehouse().getWarehouseId()) .toWarehouseId(job.getDropToWarehouse().getWarehouseId()) .salesOrderId(job.getSalesOrderRef() != null ? job.getSalesOrderRef().getId() : null) .ppOrderId(job.getManufacturingOrderRef() != null ? job.getManufacturingOrderRef().getId() : null) .isJobStarted(job.isJobAssigned()) .plantId(job.getPlantInfo() != null ? job.getPlantInfo().getResourceId() : null) .priority(job.getPriority()) .fromLocatorId(job.getSinglePickFromLocatorIdOrNull()) .toLocatorId(job.getSingleDropToLocatorIdOrNull()) .productId(job.getSingleProductIdOrNull()) .qty(job.getSingleUnitQuantityOrNull()) .isInTransit(job.isInTransit()) .build(); } @NonNull private static DDOrderId extractDDOrderId(final I_DD_Order ddOrder) {return DDOrderId.ofRepoId(ddOrder.getDD_Order_ID());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DDOrderReferenceCollector.java
1
请完成以下Java代码
public Stream<InetAddress> getAddressesfromHost(String host) throws UnknownHostException { LOGGER.info("Performing Forward Lookup for HOST : " + host); if (!registry.containsKey(host)) { throw new UnknownHostException("Missing Host information in Resolver"); } return registry.get(host) .stream() .map(add -> constructInetAddress(host, add)) .filter(Objects::nonNull); } public String getHostFromAddress(byte[] arr) throws UnknownHostException { LOGGER.info("Performing Reverse Lookup for Address : " + Arrays.toString(arr)); for (Map.Entry<String, List<byte[]>> entry : registry.entrySet()) { if (entry.getValue() .stream() .anyMatch(ba -> Arrays.equals(ba, arr))) { return entry.getKey();
} } throw new UnknownHostException("Address Not Found"); } private Map<String, List<byte[]>> loadMapWithData() { return Map.of("baeldung-local.org", List.of(new byte[] { 1, 2, 3, 4 })); } private static InetAddress constructInetAddress(String host, byte[] address) { try { return InetAddress.getByAddress(host, address); } catch (UnknownHostException unknownHostException) { return null; } } }
repos\tutorials-master\core-java-modules\core-java-18\src\main\java\com\baeldung\inetspi\Registry.java
1
请完成以下Java代码
public void validate(final SSCC18 sscc18ToValidate) { final String manufactCode = sscc18ToValidate.getManufacturerCode().trim(); final String serialNumber = sscc18ToValidate.getSerialNumber().trim(); validateManufacturerCode(manufactCode); final int digitsAvailableForSerialNumber = validateSerialNumber(manufactCode, serialNumber); Check.errorIf(serialNumber.length() > digitsAvailableForSerialNumber, "With a {}-digit manufactoring code={}, the serial number={} may only have {} digits", manufactCode.length(), manufactCode, serialNumber, digitsAvailableForSerialNumber); final int computeCheckDigit = computeCheckDigit(sscc18ToValidate); Check.errorUnless(sscc18ToValidate.getCheckDigit() == computeCheckDigit, "The check digit of SSCC18={} is not valid; It needs to be={}", sscc18ToValidate.asString(), computeCheckDigit); Check.errorUnless(isCheckDigitValid(sscc18ToValidate), "Check digit is not valid"); } private int validateSerialNumber(final String manufactCode, final String serialNumber) { final int digitsAvailableForSerialNumber = computeLenghtOfSerialNumber(manufactCode); Check.errorUnless(StringUtils.isNumber(serialNumber), "The serial number " + serialNumber + " is not a number");
return digitsAvailableForSerialNumber; } private int computeLenghtOfSerialNumber(final String manufactCode) { return 18 - 1/* extension-digit */ - manufactCode.length() - 1; } private void validateManufacturerCode(@NonNull final String manufactCode) { Check.errorUnless(StringUtils.isNumber(manufactCode), "The manufacturer code " + manufactCode + " is not a number"); Check.errorIf(manufactCode.length() > 9, "The manufacturer code " + manufactCode + " is too long"); } @FunctionalInterface public interface NextSerialNumberProvider { int provideNextSerialNumber(OrgId orgId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\sscc18\impl\SSCC18CodeBL.java
1