instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setDocument_Acct_Log_ID (final int Document_Acct_Log_ID) { if (Document_Acct_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, null);
else set_ValueNoCheck (COLUMNNAME_Document_Acct_Log_ID, Document_Acct_Log_ID); } @Override public int getDocument_Acct_Log_ID() { return get_ValueAsInt(COLUMNNAME_Document_Acct_Log_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Type AD_Reference_ID=541967 * Reference name: Document_Acct_Log_Type */ public static final int TYPE_AD_Reference_ID=541967; /** Enqueued = enqueued */ public static final String TYPE_Enqueued = "enqueued"; /** Posting Done = posting_ok */ public static final String TYPE_PostingDone = "posting_ok"; /** Posting Error = posting_error */ public static final String TYPE_PostingError = "posting_error"; @Override public void setType (final @Nullable java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Document_Acct_Log.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonRequestComposite { // TODO if an org is given, then verify whether the current user has access to the given org @ApiModelProperty(position = 10) @JsonInclude(Include.NON_NULL) String orgCode; @ApiModelProperty(position = 20) JsonRequestBPartner bpartner; @ApiModelProperty(value = "The location's GLN can be used to lookup the whole bpartner; if multiple locations with GLN are provided, then only the first one is used", // position = 30) @JsonInclude(Include.NON_EMPTY) @JsonProperty("locations") @Getter(AccessLevel.PRIVATE) JsonRequestLocationUpsert locations; @ApiModelProperty(position = 40) @JsonInclude(Include.NON_EMPTY) @JsonProperty("contacts") @Getter(AccessLevel.PRIVATE) JsonRequestContactUpsert contacts; @ApiModelProperty(position = 50) @JsonInclude(Include.NON_EMPTY) @JsonProperty("bankAccounts") @Getter(AccessLevel.PRIVATE) JsonRequestBankAccountsUpsert bankAccounts; @ApiModelProperty(position = 60) @JsonInclude(Include.NON_EMPTY) @JsonProperty("compositeAlbertaBPartner") JsonCompositeAlbertaBPartner compositeAlbertaBPartner; @ApiModelProperty(value = "Ths advise is applied to this composite's bpartner or any of its contacts\n" + READ_ONLY_SYNC_ADVISE_DOC, position = 70) @JsonInclude(Include.NON_NULL) SyncAdvise syncAdvise; @Builder(toBuilder = true) @JsonCreator private JsonRequestComposite( @JsonProperty("orgCode") @Nullable final String orgCode, @JsonProperty("bpartner") @Nullable final JsonRequestBPartner bpartner, @JsonProperty("locations") @Nullable final JsonRequestLocationUpsert locations, @JsonProperty("contacts") @Nullable final JsonRequestContactUpsert contacts, @JsonProperty("bankAccounts") @Nullable final JsonRequestBankAccountsUpsert bankAccounts, @JsonProperty("compositeAlbertaBPartner") @Nullable final JsonCompositeAlbertaBPartner compositeAlbertaBPartner, @JsonProperty("syncAdvise") final SyncAdvise syncAdvise)
{ this.orgCode = orgCode; this.bpartner = bpartner; this.locations = locations; this.contacts = contacts; this.bankAccounts = bankAccounts; this.compositeAlbertaBPartner = compositeAlbertaBPartner; this.syncAdvise = syncAdvise; } @JsonIgnore public JsonRequestLocationUpsert getLocationsNotNull() { return coalesceNotNull(locations, JsonRequestLocationUpsert.builder().build()); } @JsonIgnore public JsonRequestContactUpsert getContactsNotNull() { return coalesceNotNull(contacts, JsonRequestContactUpsert.builder().build()); } @JsonIgnore public JsonRequestBankAccountsUpsert getBankAccountsNotNull() { return coalesceNotNull(bankAccounts, JsonRequestBankAccountsUpsert.NONE); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestComposite.java
2
请完成以下Java代码
public List<TbActorId> filterChildren(TbActorId parent, Predicate<TbActorId> childFilter) { Set<TbActorId> children = parentChildMap.get(parent); if (children != null) { return children.stream().filter(childFilter).collect(Collectors.toList()); } else { return Collections.emptyList(); } } @Override public void stop(TbActorRef actorRef) { stop(actorRef.getActorId()); } @Override public void stop(TbActorId actorId) { Set<TbActorId> children = parentChildMap.remove(actorId); if (children != null) { for (TbActorId child : children) { stop(child); } } parentChildMap.values().forEach(parentChildren -> parentChildren.remove(actorId)); TbActorMailbox mailbox = actors.remove(actorId); if (mailbox != null) {
mailbox.destroy(null); } } @Override public void stop() { dispatchers.values().forEach(dispatcher -> { dispatcher.getExecutor().shutdown(); try { dispatcher.getExecutor().awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { log.warn("[{}] Failed to stop dispatcher", dispatcher.getDispatcherId(), e); } }); if (scheduler != null) { scheduler.shutdownNow(); } actors.clear(); } }
repos\thingsboard-master\common\actor\src\main\java\org\thingsboard\server\actors\DefaultTbActorSystem.java
1
请完成以下Java代码
public String getBusinessKey() { return businessKey; } @CamundaQueryParam(value="businessKey") public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) public void setVariables(List<VariableQueryParameterDto> variables) { this.variables = variables; } public List<QueryVariableValue> getQueryVariableValues() { return queryVariableValues; } public void initQueryVariableValues(VariableSerializers variableTypes, String dbType) { queryVariableValues = createQueryVariableValues(variableTypes, variables, dbType); } @Override protected String getOrderByValue(String sortBy) { return super.getOrderBy(); } @Override protected boolean isValidSortByValue(String value) { return false; } private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) { List<QueryVariableValue> values = new ArrayList<QueryVariableValue>(); if (variables == null) {
return values; } for (VariableQueryParameterDto variable : variables) { QueryVariableValue value = new QueryVariableValue( variable.getName(), resolveVariableValue(variable.getValue()), ConditionQueryParameterDto.getQueryOperator(variable.getOperator()), false); value.initialize(variableTypes, dbType); values.add(value); } return values; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionQueryDto.java
1
请完成以下Java代码
public boolean isUseForPartnerRequestWindow () { Object oo = get_Value(COLUMNNAME_IsUseForPartnerRequestWindow); 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 */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ @Override public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ @Override public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class); } @Override public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory) { set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory); } /** Set Status Category. @param R_StatusCategory_ID Request Status Category */ @Override public void setR_StatusCategory_ID (int R_StatusCategory_ID) { if (R_StatusCategory_ID < 1) set_Value (COLUMNNAME_R_StatusCategory_ID, null); else set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID)); } /** Get Status Category. @return Request Status Category */ @Override public int getR_StatusCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestType.java
1
请在Spring Boot框架中完成以下Java代码
public class DeploymentResourceDto { protected String id; protected String name; protected String deploymentId; public DeploymentResourceDto() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public static DeploymentResourceDto fromResources(Resource resource) { DeploymentResourceDto dto = new DeploymentResourceDto(); dto.id = resource.getId(); dto.name = resource.getName(); dto.deploymentId = resource.getDeploymentId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentResourceDto.java
2
请完成以下Java代码
public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight) { set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight); } /** Set Produkt für Fracht. @param M_ProductFreight_ID Produkt für Fracht */ @Override public void setM_ProductFreight_ID (int M_ProductFreight_ID) { if (M_ProductFreight_ID < 1)
set_Value (COLUMNNAME_M_ProductFreight_ID, null); else set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID)); } /** Get Produkt für Fracht. @return Produkt für Fracht */ @Override public int getM_ProductFreight_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ClientInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn( name = "name", referencedColumnName = "name"), @JoinColumn( name = "age", referencedColumnName = "age") }) private Author author; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddable\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public boolean supports(Class<?> authentication) { return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication); } /** * Sets the {@link SessionRegistry} used to track OpenID Connect sessions. * @param sessionRegistry the {@link SessionRegistry} used to track OpenID Connect * sessions */ public void setSessionRegistry(SessionRegistry sessionRegistry) { Assert.notNull(sessionRegistry, "sessionRegistry cannot be null"); this.sessionRegistry = sessionRegistry; } private SessionInformation getSessionInformation(Authentication principal) { SessionInformation sessionInformation = null; if (this.sessionRegistry != null) { List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(principal.getPrincipal(), false); if (!CollectionUtils.isEmpty(sessions)) {
sessionInformation = sessions.get(0); if (sessions.size() > 1) { // Get the most recent session sessions = new ArrayList<>(sessions); sessions.sort(Comparator.comparing(SessionInformation::getLastRequest)); sessionInformation = sessions.get(sessions.size() - 1); } } } return sessionInformation; } private static String createHash(String value) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeAuthenticationProvider.java
1
请完成以下Java代码
public void parsingElement(String elementType, String elementId) { logDebug("001", "Parsing element from type '{}' with id '{}'", elementType, elementId); } public void ignoringNonExecutableProcess(String elementId) { logInfo("002", "Ignoring non-executable process with id '{}'. Set the attribute isExecutable=\"true\" to deploy " + "this process.", elementId); } public void missingIsExecutableAttribute(String elementId) { logInfo("003", "Process with id '{}' has no attribute isExecutable. Better set the attribute explicitly, " + "especially to be compatible with future engine versions which might change the default behavior.", elementId); } public void parsingFailure(Throwable cause) { logError("004", "Unexpected Exception with message: {} ", cause.getMessage()); } public void intermediateCatchTimerEventWithTimeCycleNotRecommended(String definitionKey, String elementId) { logInfo("005", "definitionKey: {}; It is not recommended to use an intermediate catch timer event with a time cycle, " + "element with id '{}'.", definitionKey, elementId); } // EXCEPTIONS public ProcessEngineException parsingProcessException(Exception cause) {
return new ProcessEngineException(exceptionMessage("009", "Error while parsing process. {}.", cause.getMessage()), cause); } public void exceptionWhileGeneratingProcessDiagram(Throwable t) { logError( "010", "Error while generating process diagram, image will not be stored in repository", t); } public ProcessEngineException messageEventSubscriptionWithSameNameExists(String resourceName, String eventName) { throw new ProcessEngineException(exceptionMessage( "011", "Cannot deploy process definition '{}': there already is a message event subscription for the message with name '{}'.", resourceName, eventName)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParseLogger.java
1
请完成以下Java代码
private void updateProfitPriceActual(final I_C_OrderLine orderLineRecord) { final OrderLineRepository orderLineRepository = SpringContextHolder.instance.getBean(OrderLineRepository.class); final ProfitPriceActualFactory profitPriceActualFactory = SpringContextHolder.instance.getBean(ProfitPriceActualFactory.class); final OrderLine orderLine = orderLineRepository.ofRecord(orderLineRecord); final CalculateProfitPriceActualRequest request = CalculateProfitPriceActualRequest.builder() .bPartnerId(orderLine.getBPartnerId()) .productId(orderLine.getProductId()) .date(orderLine.getDatePromised().toLocalDate()) .baseAmount(orderLine.getPriceActual().toMoney()) .paymentTermId(orderLine.getPaymentTermId()) .quantity(orderLine.getOrderedQty()) .build(); final Money profitBasePrice = profitPriceActualFactory.calculateProfitPriceActual(request); orderLineRecord.setProfitPriceActual(profitBasePrice.toBigDecimal()); } @Nullable private UomId extractPriceUomId(@NonNull final IPricingResult pricingResult) { final I_C_OrderLine orderLine = request.getOrderLine(); return UomId.optionalOfRepoId(orderLine.getPrice_UOM_ID()) .orElse(pricingResult.getPriceUomId()); } public TaxCategoryId computeTaxCategoryId() { final IPricingContext pricingCtx = createPricingContext() .setDisallowDiscount(true); // don't bother computing discounts; we know that the tax category is not related to them.
final IPricingResult pricingResult = pricingBL.calculatePrice(pricingCtx); if (!pricingResult.isCalculated()) { final I_C_OrderLine orderLine = request.getOrderLine(); throw new ProductNotOnPriceListException(pricingCtx, orderLine.getLine()) .setParameter("log", pricingResult.getLoggableMessages()); } return pricingResult.getTaxCategoryId(); } public IPricingResult computePrices() { final IEditablePricingContext pricingCtx = createPricingContext(); return pricingBL.calculatePrice(pricingCtx); } public PriceLimitRuleResult computePriceLimit() { final I_C_OrderLine orderLine = request.getOrderLine(); return pricingBL.computePriceLimit(PriceLimitRuleContext.builder() .pricingContext(createPricingContext()) .priceLimit(orderLine.getPriceLimit()) .priceActual(orderLine.getPriceActual()) .paymentTermId(orderLineBL.getPaymentTermId(orderLine)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePriceCalculator.java
1
请完成以下Java代码
private I_PP_Order_Qty createReceiptCandidateOrNull( @NonNull final IHUContext huContext, @NonNull final I_M_HU hu) { final IHUProductStorage productStorage = retrieveProductStorage(huContext, hu); if (productStorage == null) { return null; } // Actually create and save the candidate final I_PP_Order_Qty candidate = createReceiptCandidateOrNull(hu, productStorage); if (candidate == null) { return null; } return candidate; } @Nullable private IHUProductStorage retrieveProductStorage( @NonNull final IHUContext huContext, @NonNull final I_M_HU hu) { final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory() .getStorage(hu) .getProductStorages(); // Empty HU if (productStorages.isEmpty()) { logger.warn("{}: Skip {} from issuing because its storage is empty", this, hu); return null; // no candidate } return productStorages.get(0); } @Nullable private I_PP_Order_Qty createReceiptCandidateOrNull( @NonNull final I_M_HU hu, @NonNull final IHUProductStorage productStorage) { try { final ProductId productId = productStorage.getProductId(); final Quantity qtyPicked = substractQtyPicked(productStorage) .switchToSourceIfMorePrecise(); if (qtyPicked.isZero()) { return null; } final I_PP_Order_Qty candidate = huPPOrderQtyDAO.save(CreateReceiptCandidateRequest.builder() .orderId(orderId) .orgId(OrgId.ofRepoId(hu.getAD_Org_ID())) // .date(movementDate) // .locatorId(warehousesRepo.getLocatorIdByRepoIdOrNull(hu.getM_Locator_ID()))
.topLevelHUId(HuId.ofRepoId(hu.getM_HU_ID())) .productId(productId) // .qtyToReceive(qtyPicked) // .build()); return candidate; } catch (final RuntimeException rte) { throw AdempiereException.wrapIfNeeded(rte) .appendParametersToMessage() .setParameter("M_HU", hu); } } /** * @return how much quantity to take "from" */ private Quantity substractQtyPicked(@NonNull final IHUProductStorage from) { if (qtyPicked != null) { final Quantity huStorageQty = from.getQty(qtyPicked.getUOM()); final Quantity qtyToPick = huStorageQty.min(qtyPicked); qtyPicked = qtyPicked.subtract(qtyToPick); return qtyToPick; } return from.getQty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\hu_pporder_issue_producer\CreatePickedReceiptCommand.java
1
请完成以下Java代码
public void deleteDraftPickingCandidates(final List<PickingCandidate> draftCandidates) { draftCandidates.forEach(PickingCandidate::assertDraft); pickingCandidateRepository.deletePickingCandidates(draftCandidates); } public ADRefList getQtyRejectedReasons() { return adReferenceService.getRefListById(QtyRejectedReasonCode.REFERENCE_ID); } @NonNull public ImmutableMap<HuId, ImmutableSet<OrderId>> getOpenPickingOrderIdsByHuId(@NonNull final ImmutableSet<HuId> huIds) { final ImmutableList<PickingCandidate> openPickingCandidates = pickingCandidateRepository.getByHUIds(huIds) .stream() .filter(pickingCandidate -> !pickingCandidate.isProcessed()) .collect(ImmutableList.toImmutableList()); final ImmutableListMultimap<HuId, ShipmentScheduleId> huId2ShipmentScheduleIds = openPickingCandidates .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(pickingCandidate -> pickingCandidate.getPickFrom().getHuId(), PickingCandidate::getShipmentScheduleId)); final ImmutableMap<ShipmentScheduleId, OrderId> scheduleId2OrderId = shipmentSchedulePA.getByIds(ImmutableSet.copyOf(huId2ShipmentScheduleIds.values())) .values() .stream() .filter(shipmentSchedule -> shipmentSchedule.getC_Order_ID() > 0) .collect(ImmutableMap.toImmutableMap(shipSchedule -> ShipmentScheduleId.ofRepoId(shipSchedule.getM_ShipmentSchedule_ID()), shipSchedule -> OrderId.ofRepoId(shipSchedule.getC_Order_ID()))); return huIds.stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), huId -> { final ImmutableList<ShipmentScheduleId> scheduleIds = Optional .ofNullable(huId2ShipmentScheduleIds.get(huId)) .orElseGet(ImmutableList::of); return scheduleIds.stream() .map(scheduleId2OrderId::get) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); })); }
@Override public void beforeReleasePickingSlot(final @NonNull ReleasePickingSlotRequest request) { final boolean clearedAllUnprocessedHUs = clearPickingSlot(request.getPickingSlotId(), request.isRemoveUnprocessedHUsFromSlot()); if (!clearedAllUnprocessedHUs) { throw new AdempiereException(DRAFTED_PICKING_CANDIDATES_ERR_MSG).markAsUserValidationError(); } } /** * @return true, if all drafted picking candidates have been removed from the slot, false otherwise */ private boolean clearPickingSlot(@NonNull final PickingSlotId pickingSlotId, final boolean removeUnprocessedHUsFromSlot) { if (removeUnprocessedHUsFromSlot) { RemoveHUFromPickingSlotCommand.builder() .pickingCandidateRepository(pickingCandidateRepository) .pickingSlotId(pickingSlotId) .build() .perform(); } return !pickingCandidateRepository.hasDraftCandidatesForPickingSlot(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateService.java
1
请完成以下Java代码
protected IHUItemStorage getHUItemStorage( @NonNull final I_M_HU_Item item, @NonNull final IAllocationRequest request) { final IHUContext huContext = request.getHuContext(); final IHUStorageFactory huStorageFactory = huContext.getHUStorageFactory(); return huStorageFactory.getStorage(item); } /** * Creates the actual request for allocation/deallocation that shall be used on given HU Item. * The actual request is computed based on item's current capacity and load. * * @return actual request to use used for allocation/deallocation be the {@link #allocateOnVirtualMaterialItem(I_M_HU_Item, IAllocationRequest)}. */ private final IAllocationRequest createActualRequest( @NonNull final I_M_HU_Item item, @NonNull final IAllocationRequest request) { final IHUItemStorage storage = getHUItemStorage(item, request); return direction.isOutboundDeallocation() ? storage.requestQtyToDeallocate(request) : storage.requestQtyToAllocate(request); } private final IAllocationResult allocateOnVirtualMaterialItem( @NonNull final I_M_HU_Item vhuItem, @NonNull final IAllocationRequest request) { // // Create Actual Allocation Request depending on vhuItem's (remaining) capacity final IAllocationRequest requestActual = createActualRequest(vhuItem, request); if (requestActual.isZeroQty()) { return AllocationUtils.nullResult(); } final BigDecimal qtyToAllocate = request.getQty(); final BigDecimal qtyAllocated = requestActual.getQty(); // // Create HU Transaction Candidate final IHUTransactionCandidate trx = createHUTransaction(requestActual, vhuItem);
// // Create Allocation Result return AllocationUtils.createQtyAllocationResult( qtyToAllocate, qtyAllocated, Arrays.asList(trx), // trxs ImmutableList.of()); // attributeTrxs } /** * Create transaction candidate which when it will be processed it will change the storage quantity. * * @param requestActual request (used to get Product, UOM, Date, Qty etc) * @param vhuItem Virtual HU item on which we actually allocated/deallocated */ @NonNull private final IHUTransactionCandidate createHUTransaction( @NonNull final IAllocationRequest requestActual, @Nullable final I_M_HU_Item vhuItem) { final I_M_HU_Item itemFirstNotPureVirtual = services.getFirstNotPureVirtualItem(vhuItem); final Object referencedModel = AllocationUtils.getReferencedModel(requestActual); final Quantity qtyTrx = AllocationUtils.getQuantity(requestActual, direction); return new HUTransactionCandidate( referencedModel, itemFirstNotPureVirtual, // HU Item vhuItem, // VHU Item requestActual.getProductId(), // Product qtyTrx, // Qty/UOM requestActual.getDate()); // Date } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\strategy\AbstractAllocationStrategy.java
1
请完成以下Java代码
protected void addResultToVariableContext(DmnDecisionResult evaluatedResult, VariableMap variableMap, DmnDecision evaluatedDecision) { List<Map<String, Object>> resultList = evaluatedResult.getResultList(); if (resultList.isEmpty()) { return; } else if (resultList.size() == 1 && !isDecisionTableWithCollectOrRuleOrderHitPolicy(evaluatedDecision)) { variableMap.putAll(evaluatedResult.getSingleResult()); } else { Set<String> outputs = new HashSet<String>(); for (Map<String, Object> resultMap : resultList) { outputs.addAll(resultMap.keySet()); } for (String output : outputs) { List<Object> values = evaluatedResult.collectEntries(output); variableMap.put(output, values); } } } protected boolean isDecisionTableWithCollectOrRuleOrderHitPolicy(DmnDecision evaluatedDecision) { boolean isDecisionTableWithCollectHitPolicy = false; if (evaluatedDecision.isDecisionTable()) { DmnDecisionTableImpl decisionTable = (DmnDecisionTableImpl) evaluatedDecision.getDecisionLogic(); isDecisionTableWithCollectHitPolicy = COLLECT_HIT_POLICY.equals(decisionTable.getHitPolicyHandler().getHitPolicyEntry()) || RULE_ORDER_HIT_POLICY.equals(decisionTable.getHitPolicyHandler().getHitPolicyEntry()); } return isDecisionTableWithCollectHitPolicy; } protected void generateDecisionEvaluationEvent(List<DmnDecisionLogicEvaluationEvent> evaluatedEvents) { DmnDecisionLogicEvaluationEvent rootEvaluatedEvent = null;
DmnDecisionEvaluationEventImpl decisionEvaluationEvent = new DmnDecisionEvaluationEventImpl(); long executedDecisionElements = 0L; for(DmnDecisionLogicEvaluationEvent evaluatedEvent: evaluatedEvents) { executedDecisionElements += evaluatedEvent.getExecutedDecisionElements(); rootEvaluatedEvent = evaluatedEvent; } decisionEvaluationEvent.setDecisionResult(rootEvaluatedEvent); decisionEvaluationEvent.setExecutedDecisionInstances(evaluatedEvents.size()); decisionEvaluationEvent.setExecutedDecisionElements(executedDecisionElements); evaluatedEvents.remove(rootEvaluatedEvent); decisionEvaluationEvent.setRequiredDecisionResults(evaluatedEvents); for (DmnDecisionEvaluationListener evaluationListener : evaluationListeners) { evaluationListener.notify(decisionEvaluationEvent); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnDecisionContext.java
1
请完成以下Java代码
public static WorkflowLaunchersFacetId ofId(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final RepoIdAware id) { return ofString(groupId, String.valueOf(id.getRepoId())); } public static WorkflowLaunchersFacetId ofLocalDate(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final LocalDate localDate) { return ofString(groupId, localDate.toString()); } // NOTE: Quantity class is not accessible from this project :( public static WorkflowLaunchersFacetId ofQuantity(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final BigDecimal value, @NonNull final RepoIdAware uomId) { return ofString(groupId, value + QTY_SEPARATOR + uomId.getRepoId()); } @Override @Deprecated public String toString() {return toJsonString();} @JsonValue @NonNull public String toJsonString() {return groupId.getAsString() + SEPARATOR + value;} @NonNull public <T extends RepoIdAware> T getAsId(@NonNull final Class<T> type) {return RepoIdAwares.ofObject(value, type);} @NonNull public LocalDate getAsLocalDate() {return LocalDate.parse(value);} // NOTE: Quantity class is not accessible from this project :( @NonNull public ImmutablePair<BigDecimal, Integer> getAsQuantity() { try { final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value); if (parts.size() != 2)
{ throw new AdempiereException("Cannot get Quantity from " + this); } return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1))); } catch (AdempiereException ex) { throw ex; } catch (final Exception ex) { throw new AdempiereException("Cannot get Quantity from " + this, ex); } } @NonNull public String getAsString() {return value;} @NonNull public <T> T deserializeTo(@NonNull final Class<T> targetClass) { return JSONObjectMapper.forClass(targetClass).readValue(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringAsyncHistoryExecutor extends SpringAsyncExecutor { public SpringAsyncHistoryExecutor() { super(); init(); } public SpringAsyncHistoryExecutor(AsyncJobExecutorConfiguration configuration) { super(configuration); init(); } protected void init() { setTimerRunnableNeeded(false); if (configuration.getAcquireRunnableThreadName() == null) { setAcquireRunnableThreadName("flowable-acquire-history-jobs"); } if (configuration.getResetExpiredRunnableName() == null) {
setResetExpiredRunnableName("flowable-reset-expired-history-jobs"); } setAsyncRunnableExecutionExceptionHandler(new UnacquireAsyncHistoryJobExceptionHandler()); } @Override protected void initializeJobEntityManager() { if (jobEntityManager == null) { jobEntityManager = jobServiceConfiguration.getHistoryJobEntityManager(); } } @Override protected ResetExpiredJobsRunnable createResetExpiredJobsRunnable(String resetRunnableName) { return new ResetExpiredJobsRunnable(resetRunnableName, this, jobServiceConfiguration.getHistoryJobEntityManager()); } }
repos\flowable-engine-main\modules\flowable-job-spring-service\src\main\java\org\flowable\spring\job\service\SpringAsyncHistoryExecutor.java
2
请完成以下Java代码
public int getGO_Shipper_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GO_Shipper_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GO URL. @param GO_URL GO URL */ @Override public void setGO_URL (java.lang.String GO_URL) { set_Value (COLUMNNAME_GO_URL, GO_URL); } /** Get GO URL. @return GO URL */ @Override public java.lang.String getGO_URL () { return (java.lang.String)get_Value(COLUMNNAME_GO_URL); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ @Override
public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ @Override public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_Shipper_Config.java
1
请完成以下Java代码
public boolean hasNext() { if (fileRefs != null) { return fileRefs.hasNext(); } return scripts.hasNext(); } @Override public IScript next() { if (!hasNext()) { throw new NoSuchElementException(); } if (fileRefs != null) { return getScript(fileRefs.next());
} return scripts.next(); } private IScript getScript(final IFileRef fileRef) { final IScriptFactory scriptFactory = getScriptFactoryToUse(); return scriptFactory.createScript(fileRef); } @Override public String toString() { return "PlainListScriptScanner [fileRef=" + fileRefs + ", scripts= " + scripts + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\PlainListScriptScanner.java
1
请在Spring Boot框架中完成以下Java代码
public class SmsHomeRecommendSubjectController { @Autowired private SmsHomeRecommendSubjectService recommendSubjectService; @ApiOperation("添加首页专题推荐") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsHomeRecommendSubject> homeRecommendSubjectList) { int count = recommendSubjectService.create(homeRecommendSubjectList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改专题推荐排序") @RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateSort(@PathVariable Long id, Integer sort) { int count = recommendSubjectService.updateSort(id, sort); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除专题推荐") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = recommendSubjectService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); }
@ApiOperation("批量修改专题推荐状态") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) { int count = recommendSubjectService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询专题推荐") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeRecommendSubject>> list(@RequestParam(value = "subjectName", required = false) String subjectName, @RequestParam(value = "recommendStatus", required = false) Integer recommendStatus, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsHomeRecommendSubject> homeRecommendSubjectList = recommendSubjectService.list(subjectName, recommendStatus, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(homeRecommendSubjectList)); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsHomeRecommendSubjectController.java
2
请完成以下Java代码
public ProcessInfo getProcessInfo() { return pi; } public void setProcessInfo(ProcessInfo pi) { this.pi = pi; } public boolean isSelectionActive() { return m_selectionActive; } public void setSelectionActive(boolean active) { m_selectionActive = active; } public ArrayList<Integer> getSelection() { return selection; } public void setSelection(ArrayList<Integer> selection) { this.selection = selection; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getReportEngineType() { return reportEngineType; }
public void setReportEngineType(int reportEngineType) { this.reportEngineType = reportEngineType; } public MPrintFormat getPrintFormat() { return this.printFormat; } public void setPrintFormat(MPrintFormat printFormat) { this.printFormat = printFormat; } public String getAskPrintMsg() { return askPrintMsg; } public void setAskPrintMsg(String askPrintMsg) { this.askPrintMsg = askPrintMsg; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\GenForm.java
1
请完成以下Java代码
private TableColumnModelListener getColumnModelListener() { if (columnModelListener == null) { columnModelListener = createColumnModelListener(); } return columnModelListener; } /** * Creates the listener to columnModel. Subclasses are free to roll their own. * <p> * Implementation note: this listener reacts to "real" columnRemoved/-Added by populating the popups content from scratch. * * @return the <code>TableColumnModelListener</code> for use with the table's columnModel. */ private TableColumnModelListener createColumnModelListener() { return new TableColumnModelListener() { /** Tells listeners that a column was added to the model. */ @Override public void columnAdded(TableColumnModelEvent e) { markPopupStaled(); } /** Tells listeners that a column was removed from the model. */ @Override public void columnRemoved(TableColumnModelEvent e) { markPopupStaled(); } /** Tells listeners that a column was repositioned. */ @Override public void columnMoved(TableColumnModelEvent e) { if (e.getFromIndex() == e.getToIndex()) {
// not actually a change return; } // mark popup stalled because we want to have the same ordering there as we have in table column markPopupStaled(); } /** Tells listeners that a column was moved due to a margin change. */ @Override public void columnMarginChanged(ChangeEvent e) { // nothing to do } /** * Tells listeners that the selection model of the TableColumnModel changed. */ @Override public void columnSelectionChanged(ListSelectionEvent e) { // nothing to do } }; } } // end class ColumnControlButton
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CColumnControlButton.java
1
请在Spring Boot框架中完成以下Java代码
public class BatchConfiguration { @Bean @StepScope public ExpiresSoonMedicineReader expiresSoonMedicineReader(JdbcTemplate jdbcTemplate, @Value("#{jobParameters}") Map<String, Object> jobParameters) { ExpiresSoonMedicineReader medicineReader = new ExpiresSoonMedicineReader(jdbcTemplate); enrichWithJobParameters(jobParameters, medicineReader); return medicineReader; } @Bean @StepScope public MedicineProcessor medicineProcessor(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineProcessor medicineProcessor = new MedicineProcessor(); enrichWithJobParameters(jobParameters, medicineProcessor); return medicineProcessor; } @Bean @StepScope public MedicineWriter medicineWriter(@Value("#{jobParameters}") Map<String, Object> jobParameters) { MedicineWriter medicineWriter = new MedicineWriter(); enrichWithJobParameters(jobParameters, medicineWriter); return medicineWriter; } @Bean public Job medExpirationJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, MedicineWriter medicineWriter, MedicineProcessor medicineProcessor, ExpiresSoonMedicineReader expiresSoonMedicineReader) { Step notifyAboutExpiringMedicine = new StepBuilder("notifyAboutExpiringMedicine", jobRepository).<Medicine, Medicine>chunk(10)
.reader(expiresSoonMedicineReader) .processor(medicineProcessor) .writer(medicineWriter) .faultTolerant() .transactionManager(transactionManager) .build(); return new JobBuilder("medExpirationJob", jobRepository).incrementer(new RunIdIncrementer()) .start(notifyAboutExpiringMedicine) .build(); } private void enrichWithJobParameters(Map<String, Object> jobParameters, ContainsJobParameters container) { if (jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) != null) { container.setTriggeredDateTime(ZonedDateTime.parse(jobParameters.get(BatchConstants.TRIGGERED_DATE_TIME) .toString())); } if (jobParameters.get(BatchConstants.TRACE_ID) != null) { container.setTraceId(jobParameters.get(BatchConstants.TRACE_ID) .toString()); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchreaderproperties\BatchConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DetailDataRecordIdentifier { public static DetailDataRecordIdentifier createForShipmentSchedule( @NonNull final MainDataRecordIdentifier mainDataRecordIdentifier, final int shipmentScheduleId) { return new DetailDataRecordIdentifier(mainDataRecordIdentifier, shipmentScheduleId, 0); } public static DetailDataRecordIdentifier createForReceiptSchedule( @NonNull final MainDataRecordIdentifier mainDataRecordIdentifier, final int receiptScheduleId) { return new DetailDataRecordIdentifier(mainDataRecordIdentifier, 0, receiptScheduleId); } int shipmentScheduleId; int receiptScheduleId; MainDataRecordIdentifier mainDataRecordIdentifier; private DetailDataRecordIdentifier( @NonNull final MainDataRecordIdentifier mainDataRecordIdentifier, final int shipmentScheduleId, final int receiptScheduleId) { this.receiptScheduleId = receiptScheduleId; this.shipmentScheduleId = shipmentScheduleId;
this.mainDataRecordIdentifier = mainDataRecordIdentifier; final boolean shipmentScheduleIdSet = shipmentScheduleId > 0; final boolean receiptScheduleIdSet = receiptScheduleId > 0; Check.errorUnless(shipmentScheduleIdSet ^ receiptScheduleIdSet, "Either shipmentScheduleId or receipScheduleId (but not both!) needs to be < 0"); } public IQuery<I_MD_Cockpit_DocumentDetail> createQuery() { final IQueryBuilder<I_MD_Cockpit_DocumentDetail> queryBuilder = mainDataRecordIdentifier.createQueryBuilder() .andCollectChildren(I_MD_Cockpit_DocumentDetail.COLUMN_MD_Cockpit_ID); if (shipmentScheduleId > 0) { queryBuilder.addEqualsFilter(I_MD_Cockpit_DocumentDetail.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId); } if (receiptScheduleId > 0) { queryBuilder.addEqualsFilter(I_MD_Cockpit_DocumentDetail.COLUMN_M_ReceiptSchedule_ID, receiptScheduleId); } return queryBuilder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\DetailDataRecordIdentifier.java
2
请完成以下Java代码
public void create(final BusinessRuleLogEntryRequest request) { final I_AD_BusinessRule_Log record = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_BusinessRule_Log.class); record.setLevel(request.getLevel().toString()); record.setMsgText(request.getMessage()); record.setAD_Issue_ID(AdIssueId.toRepoId(request.getErrorId())); if (request.getDuration() != null) { record.setDurationMillis((int)request.getDuration().toMillis()); } record.setModule(request.getModuleName()); record.setAD_BusinessRule_ID(BusinessRuleId.toRepoId(request.getBusinessRuleId())); record.setAD_BusinessRule_Precondition_ID(BusinessRulePreconditionId.toRepoId(request.getPreconditionId()));
record.setAD_BusinessRule_Trigger_ID(BusinessRuleTriggerId.toRepoId(request.getTriggerId())); final TableRecordReference sourceRecordRef = request.getSourceRecordRef(); record.setSource_Table_ID(sourceRecordRef != null ? sourceRecordRef.getAD_Table_ID() : -1); record.setSource_Record_ID(sourceRecordRef != null ? sourceRecordRef.getRecord_ID() : -1); final TableRecordReference targetRecordRef = request.getTargetRecordRef(); record.setTarget_Table_ID(targetRecordRef != null ? targetRecordRef.getAD_Table_ID() : -1); record.setTarget_Record_ID(targetRecordRef != null ? targetRecordRef.getRecord_ID() : -1); record.setAD_BusinessRule_Event_ID(BusinessRuleEventId.toRepoId(request.getEventId())); InterfaceWrapperHelper.save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\log\BusinessRuleLogRepository.java
1
请在Spring Boot框架中完成以下Java代码
public static DeviceConfigException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } final Throwable cause = extractCause(throwable); if (cause instanceof DeviceConfigException) { return (DeviceConfigException)cause; } else { final String msg = extractMessage(cause); final boolean permanentFailure = false; return new DeviceConfigException(msg, cause, permanentFailure);
} } private final boolean permanentFailure; public DeviceConfigException(final String msg) { super(msg); permanentFailure = false; } private DeviceConfigException(final String msg, final Throwable cause, final boolean permanentFailure) { super(msg, cause); this.permanentFailure = permanentFailure; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfigException.java
2
请完成以下Java代码
protected ExecutionEntity getExecutionFromContext() { if(Context.getCommandContext() != null) { BpmnExecutionContext executionContext = Context.getBpmnExecutionContext(); if(executionContext != null) { return executionContext.getExecution(); } } return null; } public Task getTask() { ensureCommandContextNotActive(); return getScopedAssociation().getTask(); } public void setTask(Task task) { ensureCommandContextNotActive(); getScopedAssociation().setTask(task); } public VariableMap getCachedVariables() { ensureCommandContextNotActive(); return getScopedAssociation().getCachedVariables(); } public VariableMap getCachedLocalVariables() { ensureCommandContextNotActive();
return getScopedAssociation().getCachedVariablesLocal(); } public void flushVariableCache() { ensureCommandContextNotActive(); getScopedAssociation().flushVariableCache(); } protected void ensureCommandContextNotActive() { if(Context.getCommandContext() != null) { throw new ProcessEngineCdiException("Cannot work with scoped associations inside command context."); } } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\DefaultContextAssociationManager.java
1
请在Spring Boot框架中完成以下Java代码
public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) throws ParseException { if(!Objects.equals(id, postDto.getId())){ throw new IllegalArgumentException("IDs don't match"); } Post post = convertToEntity(postDto); postService.updatePost(post); } private PostDto convertToDto(Post post) { PostDto postDto = modelMapper.map(post, PostDto.class); postDto.setSubmissionDate(post.getSubmissionDate(), userService.getCurrentUser().getPreference().getTimezone()); return postDto;
} private Post convertToEntity(PostDto postDto) throws ParseException { Post post = modelMapper.map(postDto, Post.class); post.setSubmissionDate(postDto.getSubmissionDateConverted( userService.getCurrentUser().getPreference().getTimezone())); if (postDto.getId() != null) { Post oldPost = postService.getPostById(postDto.getId()); post.setRedditID(oldPost.getRedditID()); post.setSent(oldPost.isSent()); } return post; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\controller\PostRestController.java
2
请完成以下Java代码
private ExecutionInput registerDataLoaders(ExecutionInput executionInput) { if (this.hasDataLoaderRegistrations == null) { this.hasDataLoaderRegistrations = initHasDataLoaderRegistrations(); } if (this.hasDataLoaderRegistrations) { GraphQLContext graphQLContext = executionInput.getGraphQLContext(); DataLoaderRegistry existingRegistry = executionInput.getDataLoaderRegistry(); if (existingRegistry == EmptyDataLoaderRegistryInstance.EMPTY_DATALOADER_REGISTRY) { DataLoaderRegistry newRegistry = DataLoaderRegistry.newRegistry().build(); applyDataLoaderRegistrars(newRegistry, graphQLContext); executionInput = executionInput.transform((builder) -> builder.dataLoaderRegistry(newRegistry)); } else { applyDataLoaderRegistrars(existingRegistry, graphQLContext); } } return executionInput;
} private boolean initHasDataLoaderRegistrations() { for (DataLoaderRegistrar registrar : this.dataLoaderRegistrars) { if (registrar.hasRegistrations()) { return true; } } return false; } private void applyDataLoaderRegistrars(DataLoaderRegistry registry, GraphQLContext graphQLContext) { this.dataLoaderRegistrars.forEach((registrar) -> registrar.registerDataLoaders(registry, graphQLContext)); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DefaultExecutionGraphQlService.java
1
请在Spring Boot框架中完成以下Java代码
public class HigherInsurance { protected long amount; @XmlElement(required = true) protected String currency; /** * Gets the value of the amount property. * */ public long getAmount() { return amount; } /** * Sets the value of the amount property. * */ public void setAmount(long value) { this.amount = value; } /** * Gets the value of the currency property.
* * @return * possible object is * {@link String } * */ public String getCurrency() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCurrency(String value) { this.currency = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\HigherInsurance.java
2
请完成以下Java代码
public int getMatured_Product_ID() { return get_ValueAsInt(COLUMNNAME_Matured_Product_ID); } @Override public void setMaturityAge (final int MaturityAge) { set_Value (COLUMNNAME_MaturityAge, MaturityAge); } @Override public int getMaturityAge() { return get_ValueAsInt(COLUMNNAME_MaturityAge); } @Override public org.compiere.model.I_M_Maturing_Configuration getM_Maturing_Configuration() { return get_ValueAsPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class); } @Override public void setM_Maturing_Configuration(final org.compiere.model.I_M_Maturing_Configuration M_Maturing_Configuration) { set_ValueFromPO(COLUMNNAME_M_Maturing_Configuration_ID, org.compiere.model.I_M_Maturing_Configuration.class, M_Maturing_Configuration); } @Override public void setM_Maturing_Configuration_ID (final int M_Maturing_Configuration_ID) { if (M_Maturing_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_ID, M_Maturing_Configuration_ID); } @Override public int getM_Maturing_Configuration_ID() {
return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_ID); } @Override public void setM_Maturing_Configuration_Line_ID (final int M_Maturing_Configuration_Line_ID) { if (M_Maturing_Configuration_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Maturing_Configuration_Line_ID, M_Maturing_Configuration_Line_ID); } @Override public int getM_Maturing_Configuration_Line_ID() { return get_ValueAsInt(COLUMNNAME_M_Maturing_Configuration_Line_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Maturing_Configuration_Line.java
1
请完成以下Java代码
private final String applyConvertMap(String sqlStatement) { // Error Checks if (sqlStatement.toUpperCase().indexOf("EXCEPTION WHEN") != -1) { String error = "Exception clause needs to be converted: " + sqlStatement; log.info(error); m_conversionError = error; return sqlStatement; } // Carlos Ruiz - globalqss // Standard Statement -- change the keys in ConvertMap String retValue = sqlStatement; // for each iteration in the conversion map final ConvertMap convertMap = getConvertMap(); if (convertMap != null) { // final Iterator<Pattern> iter = convertMap.keySet().iterator(); for (final Map.Entry<Pattern, String> pattern2replacement : convertMap.getPattern2ReplacementEntries()) // while (iter.hasNext()) { // replace the key on convertmap (i.e.: number by numeric) final Pattern regex = pattern2replacement.getKey(); final String replacement = pattern2replacement.getValue(); try { final Matcher matcher = regex.matcher(retValue); retValue = matcher.replaceAll(replacement); } catch (Exception e) { String error = "Error expression: " + regex + " - " + e; log.info(error); m_conversionError = error; } } } return retValue; } // convertSimpleStatement /** * do convert map base conversion * @param sqlStatement * @return string */ protected final String convertWithConvertMap(String sqlStatement) { try { sqlStatement = applyConvertMap(cleanUpStatement(sqlStatement)); } catch (RuntimeException e) { log.warn("Failed converting {}", sqlStatement, e); } return sqlStatement; } /** * Get convert map for use in sql convertion * @return map
*/ protected ConvertMap getConvertMap() { return null; } /** * Convert single Statements. * - remove comments * - process FUNCTION/TRIGGER/PROCEDURE * - process Statement * @param sqlStatement * @return converted statement */ protected abstract List<String> convertStatement (String sqlStatement); /** * Mark given keyword as native. * * Some prefixes/suffixes can be added, but this depends on implementation. * * @param keyword * @return keyword with some prefix/suffix markers. */ public String markNative(String keyword) { return keyword; } } // Convert
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Convert.java
1
请完成以下Java代码
public static PackageableList ofCollection(final Collection<Packageable> list) { return !list.isEmpty() ? new PackageableList(list) : EMPTY; } public static PackageableList of(final Packageable... arr) { return ofCollection(ImmutableList.copyOf(arr)); } public static Collector<Packageable, ?, PackageableList> collect() { return GuavaCollectors.collectUsingListAccumulator(PackageableList::ofCollection); } public boolean isEmpty() {return list.isEmpty();} public int size() {return list.size();} public Stream<Packageable> stream() {return list.stream();} @Override public @NonNull Iterator<Packageable> iterator() {return list.iterator();} public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds() { return list.stream().map(Packageable::getShipmentScheduleId).sorted().collect(ImmutableSet.toImmutableSet()); } public Optional<BPartnerId> getSingleCustomerId() {return getSingleValue(Packageable::getCustomerId);} public <T> Optional<T> getSingleValue(@NonNull final Function<Packageable, T> mapper) { if (list.isEmpty()) { return Optional.empty(); } final ImmutableList<T> values = list.stream() .map(mapper) .filter(Objects::nonNull) .distinct() .collect(ImmutableList.toImmutableList());
if (values.isEmpty()) { return Optional.empty(); } else if (values.size() == 1) { return Optional.of(values.get(0)); } else { //throw new AdempiereException("More than one value were extracted (" + values + ") from " + list); return Optional.empty(); } } public Stream<PackageableList> groupBy(Function<Packageable, ?> classifier) { return list.stream() .collect(Collectors.groupingBy(classifier, LinkedHashMap::new, PackageableList.collect())) .values() .stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\PackageableList.java
1
请完成以下Java代码
public void removeOrder(final UUID id) { validateState(); final OrderItem orderItem = getOrderItem(id); orderItems.remove(orderItem); price = price.subtract(orderItem.getPrice()); } private OrderItem getOrderItem(final UUID id) { return orderItems.stream() .filter(orderItem -> orderItem.getProductId() .equals(id)) .findFirst() .orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist.")); } private void validateState() { if (OrderStatus.COMPLETED.equals(status)) { throw new DomainException("The order is in completed state."); } } private void validateProduct(final Product product) { if (product == null) { throw new DomainException("The product cannot be null."); } } public UUID getId() { return id; } public OrderStatus getStatus() { return status; } public BigDecimal getPrice() { return price;
} public List<OrderItem> getOrderItems() { return Collections.unmodifiableList(orderItems); } @Override public int hashCode() { return Objects.hash(id, orderItems, price, status); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Order)) return false; Order other = (Order) obj; return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; } private Order() { } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\Order.java
1
请完成以下Java代码
private void assertJUnitMode() { if (!Adempiere.isUnitTestMode()) { throw new AdempiereException("JUnit mode is not active!"); } } public synchronized void clear() { map.clear(); } public synchronized <T> void registerJUnitBean(@NonNull final T beanImpl) { assertJUnitMode(); @SuppressWarnings("unchecked") final Class<T> beanType = (Class<T>)beanImpl.getClass(); registerJUnitBean(beanType, beanImpl); } public synchronized <BT, T extends BT> void registerJUnitBean( @NonNull final Class<BT> beanType, @NonNull final T beanImpl) { assertJUnitMode(); final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>()); if (!beans.contains(beanImpl)) { beans.add(beanImpl); logger.info("JUnit testing: Registered bean {}={}", beanType, beanImpl); } else { logger.info("JUnit testing: Skip registering bean because already registered {}={}", beanType, beanImpl); } } public synchronized <BT, T extends BT> void registerJUnitBeans( @NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd) { assertJUnitMode(); final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>()); beans.addAll(beansToAdd); logger.info("JUnit testing: Registered beans {}={}", beanType, beansToAdd); } public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); final ArrayList<Object> beans = map.get(ClassReference.of(beanType)); if (beans == null || beans.isEmpty()) { return null; } if (beans.size() > 1) { logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans); } final T beanImpl = castBean(beans.get(0), beanType); logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl); return beanImpl;
} private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType) { @SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl; return beanImplCasted; } public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); List<Object> beanObjs = map.get(ClassReference.of(beanType)); if (beanObjs == null) { final List<Object> assignableBeans = map.values() .stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(impl -> beanType.isAssignableFrom(impl.getClass())) .collect(Collectors.toList()); if (assignableBeans.isEmpty()) { return null; } beanObjs = assignableBeans; } return beanObjs .stream() .map(beanObj -> castBean(beanObj, beanType)) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java
1
请完成以下Java代码
public class StoredHtmlSrc extends MultiPartElement implements Printable { private static final long serialVersionUID = 50303119083373138L; /** Logger */ protected static Logger log = LogManager.getLogger(StoredHtmlSrc.class.getName()); /** * Load html-src (text) stored in JAR, e.g. to load a style-sheet * @param elementType e.g. elementType=STYLE * @param srcLocation package/filename in SRC e.g. org/compiere/util/standard.css * todo if needed: also write for SinglePartElement and StringElement */ public StoredHtmlSrc(String elementType, String srcLocation) { this.setElementType(elementType); URL url = getClass().getClassLoader().getResource(srcLocation); if (url==null) {
log.warn("failed to load html-src: " + srcLocation); return; } InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader( ins ); String cssLine; String result=""; while ((cssLine = bufferedReader.readLine()) != null) result+=cssLine; this.setTagText(result); } catch (IOException e1) { log.warn("failed to load html-src: " + srcLocation); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\StoredHtmlSrc.java
1
请完成以下Spring Boot application配置
server.port=8088 #### kafka\u914D\u7F6E\u751F\u4EA7\u8005 begin #### #============== kafka =================== # \u6307\u5B9Akafka server\u7684\u5730\u5740\uFF0C\u96C6\u7FA4\u914D\u591A\u4E2A\uFF0C\u4E2D\u95F4\uFF0C\u9017\u53F7\u9694\u5F00 spring.kafka.bootstrap-servers=127.0.0.1:9092 #=============== provider ======================= # \u5199\u5165\u5931\u8D25\u65F6\uFF0C\u91CD\u8BD5\u6B21\u6570\u3002\u5F53leader\u8282\u70B9\u5931\u6548\uFF0C\u4E00\u4E2Arepli\u8282\u70B9\u4F1A\u66FF\u4EE3\u6210\u4E3Aleader\u8282\u70B9\uFF0C\u6B64\u65F6\u53EF\u80FD\u51FA\u73B0\u5199\u5165\u5931\u8D25\uFF0C # \u5F53retris\u4E3A0\u65F6\uFF0Cproduce\u4E0D\u4F1A\u91CD\u590D\u3002retirs\u91CD\u53D1\uFF0C\u6B64\u65F6repli\u8282\u70B9\u5B8C\u5168\u6210\u4E3Aleader\u8282\u70B9\uFF0C\u4E0D\u4F1A\u4EA7\u751F\u6D88\u606F\u4E22\u5931\u3002 spring.kafka.producer.retries=0 # \u6BCF\u6B21\u6279\u91CF\u53D1\u9001\u6D88\u606F\u7684\u6570\u91CF,produce\u79EF\u7D2F\u5230\u4E00\u5B9A\u6570\u636E\uFF0C\u4E00\u6B21\u53D1\u9001 spring.kafka.producer.batch-size=16384 # produce\u79EF\u7D2F\u6570\u636E\u4E00\u6B21\u53D1\u9001\uFF0C\u7F13\u5B58\u5927\u5C0F\u8FBE\u5230buffer.memory\u5C31\u53D1\u9001\u6570\u636E spring.kafka.producer.buffer-memory=33554432 #procedure\u8981\u6C42leader\u5728\u8003\u8651\u5B8C\u6210\u8BF7\u6C42\u4E4B\u524D\u6536\u5230\u7684\u786E\u8BA4\u6570\uFF0C\u7528\u4E8E\u63A7\u5236\u53D1\u9001\u8BB0\u5F55\u5728\u670D\u52A1\u7AEF\u7684\u6301\u4E45\u5316\uFF0C\u5176\u503C\u53EF\u4EE5\u4E3A\u5982\u4E0B\uFF1A #acks = 0 \u5982\u679C\u8BBE\u7F6E\u4E3A\u96F6\uFF0C\u5219\u751F\u4EA7\u8005\u5C06\u4E0D\u4F1A\u7B49\u5F85\u6765\u81EA\u670D\u52A1\u5668\u7684\u4EFB\u4F55\u786E\u8BA4\uFF0C\u8BE5\u8BB0\u5F55\u5C06\u7ACB\u5373\u6DFB\u52A0\u5230\u5957\u63A5\u5B57\u7F13\u51B2\u533A\u5E76\u89C6\u4E3A\u5DF2\u53D1\u9001\u3002\u5728\u8FD9\u79CD\u60C5\u51B5\u4E0B\uFF0C\u65E0\u6CD5\u4FDD\u8BC1\u670D\u52A1\u5668\u5DF2\u6536\u5230\u8BB0\u5F55\uFF0C\u5E76\u4E14\u91CD\u8BD5\u914D\u7F6E\u5C06\u4E0D\u4F1A\u751F\u6548\uFF08\u56E0\u4E3A\u5BA2\u6237\u7AEF\u901A\u5E38\u4E0D\u4F1A\u77E5\u9053\u4EFB\u4F55\u6545\u969C\uFF09\uFF0C\u4E3A\u6BCF\u6761\u8BB0\u5F55\u8FD4\u56DE\u7684\u504F\u79FB\u91CF\u59CB\u7EC8\u8BBE\u7F6E\u4E3A-1\u3002 #acks = 1 \u8FD9\u610F\u5473\u7740leader\u4F1A\u5C06\u8BB0\u5F55\u5199\u5165\u5176\u672C\u5730\u65E5\u5FD7\uFF0C\u4F46\u65E0\u9700\u7B49\u5F85\u6240\u6709\u526F\u672C\u670D\u52A1\u5668\u7684\u5B8C\u5168\u786E\u8BA4\u5373\u53EF\u505A\u51FA\u56DE\u5E94\uFF0C\u5728\u8FD9\u79CD\u60C5\u51B5\u4E0B\uFF0C\u5982\u679Cleader\u5728\u786E\u8BA4\u8BB0\u5F55\u540E\u7ACB\u5373\u5931\u8D25\uFF0C\u4F46\u5728\u5C06\u6570\u636E\u590D\u5236\u5230\u6240\u6709\u7684\u526F\u672C\u670D\u52A1\u5668\u4E4B\u524D\uFF0C\u5219\u8BB0\u5F55\u5C06\u4F1A\u4E22\u5931\u3002 #acks = all \u8FD9\u610F\u5473\u7740leader\u5C06\u7B49\u5F85\u5B8C\u6574\u7684\u540C\u6B65\u526F\u672C\u96C6\u4EE5\u786E\u8BA4\u8BB0\u5F55\uFF0C\u8FD9\u4FDD\u8BC1\u4E86\u53EA\u8981\u81F3\u5C11\u4E00\u4E2A\u540C\u6B65\u526F\u672C\u670D\u52A1\u5668\u4ECD\u7136\u5B58\u6D3B\uFF0C\u8BB0\u5F55\u5C31\u4E0D\u4F1A\u4E22\u5931\uFF0C\u8FD9\u662F\u6700\u5F3A\u6709\u529B\u7684\u4FDD\u8BC1\uFF0C\u8FD9\u76F8\u5F53\u4E8Eacks = -1\u7684\u8BBE\u7F6E\u3002 #\u53EF\u4EE5\u8BBE\u7F6E\u7684\u503C\u4E3A\uFF1Aall, -1, 0, 1 spring.kafka.producer.acks=1 # \u6307\u5B9A\u6D88\u606Fkey\u548C\u6D88\u606F\u4F53\u7684\u7F16\u89E3\u7801\u65B9\u5F0F spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer spring.kafka.
producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer #### kafka\u914D\u7F6E\u751F\u4EA7\u8005 end #### #### kafka\u914D\u7F6E\u6D88\u8D39\u8005 start #### # \u6307\u5B9A\u9ED8\u8BA4\u6D88\u8D39\u8005group id --> \u7531\u4E8E\u5728kafka\u4E2D\uFF0C\u540C\u4E00\u7EC4\u4E2D\u7684consumer\u4E0D\u4F1A\u8BFB\u53D6\u5230\u540C\u4E00\u4E2A\u6D88\u606F\uFF0C\u4F9D\u9760groud.id\u8BBE\u7F6E\u7EC4\u540D spring.kafka.consumer.group-id=test # smallest\u548Clargest\u624D\u6709\u6548\uFF0C\u5982\u679Csmallest\u91CD\u65B00\u5F00\u59CB\u8BFB\u53D6\uFF0C\u5982\u679C\u662Flargest\u4ECElogfile\u7684offset\u8BFB\u53D6\u3002\u4E00\u822C\u60C5\u51B5\u4E0B\u6211\u4EEC\u90FD\u662F\u8BBE\u7F6Esmallest spring.kafka.consumer.auto-offset-reset=earliest # enable.auto.commit:true --> \u8BBE\u7F6E\u81EA\u52A8\u63D0\u4EA4offset spring.kafka.consumer.enable-auto-commit=true #\u5982\u679C'enable.auto.commit'\u4E3Atrue\uFF0C\u5219\u6D88\u8D39\u8005\u504F\u79FB\u81EA\u52A8\u63D0\u4EA4\u7ED9Kafka\u7684\u9891\u7387\uFF08\u4EE5\u6BEB\u79D2\u4E3A\u5355\u4F4D\uFF09\uFF0C\u9ED8\u8BA4\u503C\u4E3A5000\u3002 spring.kafka.consumer.auto-commit-interval=1000 # \u6307\u5B9A\u6D88\u606Fkey\u548C\u6D88\u606F\u4F53\u7684\u7F16\u89E3\u7801\u65B9\u5F0F spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer #### kafka\u914D\u7F6E\u6D88\u8D39\u8005 end ####
repos\springboot-demo-master\kafka\src\main\resources\application.properties
2
请完成以下Java代码
public final class JoseHeaderNames { /** * {@code alg} - the algorithm header identifies the cryptographic algorithm used to * secure a JWS or JWE */ public static final String ALG = "alg"; /** * {@code jku} - the JWK Set URL header is a URI that refers to a resource for a set * of JSON-encoded public keys, one of which corresponds to the key used to digitally * sign a JWS or encrypt a JWE */ public static final String JKU = "jku"; /** * {@code jwk} - the JSON Web Key header is the public key that corresponds to the key * used to digitally sign a JWS or encrypt a JWE */ public static final String JWK = "jwk"; /** * {@code kid} - the key ID header is a hint indicating which key was used to secure a * JWS or JWE */ public static final String KID = "kid"; /** * {@code x5u} - the X.509 URL header is a URI that refers to a resource for the X.509 * public key certificate or certificate chain corresponding to the key used to * digitally sign a JWS or encrypt a JWE */ public static final String X5U = "x5u"; /** * {@code x5c} - the X.509 certificate chain header contains the X.509 public key * certificate or certificate chain corresponding to the key used to digitally sign a * JWS or encrypt a JWE */ public static final String X5C = "x5c"; /** * {@code x5t} - the X.509 certificate SHA-1 thumbprint header is a base64url-encoded * SHA-1 thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate * corresponding to the key used to digitally sign a JWS or encrypt a JWE * @deprecated The SHA-1 algorithm has been proven to be vulnerable to collision * attacks and should not be used. See the <a target="_blank" href= * "https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html">Google * Security Blog</a> for more info. * @see <a target="_blank" href= * "https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html">Announcing * the first SHA1 collision</a> */ @Deprecated public static final String X5T = "x5t"; /** * {@code x5t#S256} - the X.509 certificate SHA-256 thumbprint header is a
* base64url-encoded SHA-256 thumbprint (a.k.a. digest) of the DER encoding of the * X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt * a JWE */ public static final String X5T_S256 = "x5t#S256"; /** * {@code typ} - the type header is used by JWS/JWE applications to declare the media * type of a JWS/JWE */ public static final String TYP = "typ"; /** * {@code cty} - the content type header is used by JWS/JWE applications to declare * the media type of the secured content (the payload) */ public static final String CTY = "cty"; /** * {@code crit} - the critical header indicates that extensions to the JWS/JWE/JWA * specifications are being used that MUST be understood and processed */ public static final String CRIT = "crit"; private JoseHeaderNames() { } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JoseHeaderNames.java
1
请在Spring Boot框架中完成以下Java代码
public ListenableFuture<EdqsResponse> processRequest(TenantId tenantId, CustomerId customerId, EdqsRequest request) { var requestMsg = ToEdqsMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setTs(System.currentTimeMillis()) .setRequestMsg(TransportProtos.EdqsRequestMsg.newBuilder() .setValue(JacksonUtil.toString(request)) .build()); if (customerId != null && !customerId.isNullUid()) { requestMsg.setCustomerIdMSB(customerId.getId().getMostSignificantBits()); requestMsg.setCustomerIdLSB(customerId.getId().getLeastSignificantBits()); } UUID key = UUID.randomUUID(); Integer partition = edqsPartitionService.resolvePartition(tenantId, key); ListenableFuture<TbProtoQueueMsg<FromEdqsMsg>> resultFuture = requestTemplate.send(new TbProtoQueueMsg<>(key, requestMsg.build()), partition);
return Futures.transform(resultFuture, msg -> { TransportProtos.EdqsResponseMsg responseMsg = msg.getValue().getResponseMsg(); return JacksonUtil.fromString(responseMsg.getValue(), EdqsResponse.class); }, MoreExecutors.directExecutor()); } @Override public boolean isSupported() { return true; } @PreDestroy private void stop() { requestTemplate.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edqs\DefaultEdqsApiService.java
2
请完成以下Java代码
public static HuPackingInstructionsId ofRepoId(final int repoId) { if (repoId == TEMPLATE.repoId) { return TEMPLATE; } else if (repoId == VIRTUAL.repoId) { return VIRTUAL; } else { return new HuPackingInstructionsId(repoId); } } @Nullable public static HuPackingInstructionsId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final HuPackingInstructionsId HuPackingInstructionsId) { return HuPackingInstructionsId != null ? HuPackingInstructionsId.getRepoId() : -1; } public static final HuPackingInstructionsId TEMPLATE = new HuPackingInstructionsId(100); public static final HuPackingInstructionsId VIRTUAL = new HuPackingInstructionsId(101); int repoId; private HuPackingInstructionsId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final HuPackingInstructionsId o1, final HuPackingInstructionsId o2) { return Objects.equals(o1, o2); } public boolean isTemplate() { return isTemplateRepoId(repoId); }
public static boolean isTemplateRepoId(final int repoId) { return repoId == TEMPLATE.repoId; } public boolean isVirtual() { return isVirtualRepoId(repoId); } public static boolean isVirtualRepoId(final int repoId) { return repoId == VIRTUAL.repoId; } public boolean isRealPackingInstructions() { return isRealPackingInstructionsRepoId(repoId); } public static boolean isRealPackingInstructionsRepoId(final int repoId) { return repoId > 0 && !isTemplateRepoId(repoId) && !isVirtualRepoId(repoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuPackingInstructionsId.java
1
请完成以下Java代码
public void setC_Queue_Processor_ID (int C_Queue_Processor_ID) { if (C_Queue_Processor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_ID, Integer.valueOf(C_Queue_Processor_ID)); } /** Get Queue Processor Definition. @return Queue Processor Definition */ @Override public int getC_Queue_Processor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Keep Alive Time (millis). @param KeepAliveTimeMillis When the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. */ @Override public void setKeepAliveTimeMillis (int KeepAliveTimeMillis) { set_Value (COLUMNNAME_KeepAliveTimeMillis, Integer.valueOf(KeepAliveTimeMillis)); } /** Get Keep Alive Time (millis). @return When the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. */ @Override public int getKeepAliveTimeMillis () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepAliveTimeMillis); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Pool Size. @param PoolSize The number of threads to keep in the pool, even if they are idle */ @Override public void setPoolSize (int PoolSize) { set_Value (COLUMNNAME_PoolSize, Integer.valueOf(PoolSize)); } /** Get Pool Size. @return The number of threads to keep in the pool, even if they are idle */ @Override public int getPoolSize ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_PoolSize); if (ii == null) return 0; return ii.intValue(); } /** * Priority AD_Reference_ID=154 * Reference name: _PriorityRule */ public static final int PRIORITY_AD_Reference_ID=154; /** High = 3 */ public static final String PRIORITY_High = "3"; /** Medium = 5 */ public static final String PRIORITY_Medium = "5"; /** Low = 7 */ public static final String PRIORITY_Low = "7"; /** Urgent = 1 */ public static final String PRIORITY_Urgent = "1"; /** Minor = 9 */ public static final String PRIORITY_Minor = "9"; /** Set Priority. @param Priority Indicates if this request is of a high, medium or low priority. */ @Override public void setPriority (java.lang.String Priority) { set_Value (COLUMNNAME_Priority, Priority); } /** Get Priority. @return Indicates if this request is of a high, medium or low priority. */ @Override public java.lang.String getPriority () { return (java.lang.String)get_Value(COLUMNNAME_Priority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor.java
1
请完成以下Java代码
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) { int onesComplement = Integer.valueOf(getOnesComplement(secondNum)); StringBuilder output = new StringBuilder(); int carry = 0; int temp; while (firstNum != 0 || onesComplement != 0) { temp = (firstNum % 10 + onesComplement % 10 + carry) % 2; output.append(temp); carry = (firstNum % 10 + onesComplement % 10 + carry) / 2; firstNum = firstNum / 10; onesComplement = onesComplement / 10; } String additionOfFirstNumAndOnesComplement = output.reverse() .toString(); if (carry == 1) { return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry); } else { return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement)); } } public Integer getOnesComplement(Integer num) {
StringBuilder onesComplement = new StringBuilder(); while (num > 0) { int lastDigit = num % 10; if (lastDigit == 0) { onesComplement.append(1); } else { onesComplement.append(0); } num = num / 10; } return Integer.valueOf(onesComplement.reverse() .toString()); } }
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\binarynumbers\BinaryNumbers.java
1
请完成以下Java代码
private static OrgId getOrgId(final Login loginService, final UserId userId, final RoleId roleId, final ClientId clientId) { final Set<OrgId> orgIds = loginService.getAvailableOrgs(roleId, userId, clientId); final OrgId orgId; if (orgIds == null || orgIds.isEmpty()) { throw new AdempiereException("User is not assigned to an AD_Org"); } else if (orgIds.size() != 1) { // if there are more Orgs, we are going with organization "*" orgId = OrgId.ANY; } else { orgId = orgIds.iterator().next(); } return orgId; } private Role getRoleToLogin(LoginAuthenticateResponse response) { final ImmutableList<Role> roles = response.getAvailableRoles(); if (roles.isEmpty()) { throw new AdempiereException("User has no role assigned"); } else if (roles.size() == 1) { return roles.get(0); } else { final ArrayList<Role> nonSysAdminRoles = new ArrayList<>(); for (final Role role : roles)
{ if (role.isSystem()) { continue; } nonSysAdminRoles.add(role); } if (nonSysAdminRoles.size() == 1) { return nonSysAdminRoles.get(0); } else { throw new AdempiereException("Multiple roles are not supported. Make sure user has only one role assigned"); } } } @NonNull private static Login getLoginService() { final LoginContext loginCtx = new LoginContext(Env.newTemporaryCtx()); loginCtx.setWebui(true); return new Login(loginCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\authentication\AuthenticationRestController.java
1
请完成以下Java代码
private WFProcessHeaderProperties getAdditionalHeaderProperties( @NonNull final PickingJobLine line, @NonNull final PickingJobOptions options, @NonNull final HUCache huCache, @NonNull final JsonOpts opts) { final WFProcessHeaderProperties.WFProcessHeaderPropertiesBuilder builder = WFProcessHeaderProperties.builder(); getLastPickedBestBeforeDate(line, options, huCache, opts).ifPresent(builder::entry); return builder.build(); } private Optional<WFProcessHeaderProperty> getLastPickedBestBeforeDate( @NonNull final PickingJobLine line, @NonNull final PickingJobOptions pickingJobOptions, @NonNull final HUCache huCache, @NonNull final JsonOpts opts) { if (!pickingJobOptions.isShowLastPickedBestBeforeDateForLines()) { return Optional.empty(); } final String lastPickedHUBestBeforeDate = line.getLastPickedHUId() .map(huId -> huService.getAttributeValue(huCache.getOrLoad(huId), ATTR_BestBeforeDate)) .map(IAttributeValue::getValueAsDate) .map(date -> JsonHUAttributeConverters.toDisplayValue(date, opts.getAdLanguage())) .map(String::valueOf) .orElse(""); return Optional.of(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adMessage(LAST_PICKED_HU_BEST_BEFORE_DATE)) .value(lastPickedHUBestBeforeDate) .build()); } private void cacheLastPickedHUsForEachLineIfNeeded( @NonNull final HUCache cache, @NonNull final PickingJobOptions pickingJobOptions, @NonNull final PickingJob job) { if (!pickingJobOptions.isShowLastPickedBestBeforeDateForLines()) { return; } final Set<HuId> huIds = job.streamLines() .map(PickingJobLine::getLastPickedHUId)
.filter(Optional::isPresent) .map(Optional::get) .collect(ImmutableSet.toImmutableSet()); cache.cacheHUs(huService.getByIds(huIds)); } @Value @Builder private static class HUCache { public static HUCache init(@NonNull Function<HuId, I_M_HU> loadHU) { return HUCache.builder() .loadHU(loadHU) .build(); } @NonNull Function<HuId, I_M_HU> loadHU; Map<HuId, I_M_HU> huById = new ConcurrentHashMap<>(); public void cacheHUs(@NonNull final List<I_M_HU> hus) { hus.forEach(hu -> huById.put(HuId.ofRepoId(hu.getM_HU_ID()), hu)); } @NonNull public I_M_HU getOrLoad(@NonNull final HuId huId) { return huById.computeIfAbsent(huId, loadHU); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\ActualPickingWFActivityHandler.java
1
请完成以下Java代码
public void setText (String mnemonicLabel) { String text = createMnemonic (mnemonicLabel); super.setText (text); if (text != null && getName() == null) setName(text); //workaround for focus accelerator issue if (getLabelFor() != null && getLabelFor() instanceof JTextComponent) { if ( m_savedMnemonic > 0) ((JTextComponent)getLabelFor()).setFocusAccelerator(m_savedMnemonic); else ((JTextComponent)getLabelFor()).setFocusAccelerator('\0'); } } // setText /** * Create Mnemonics of text containing "&". * Based on MS notation of &Help => H is Mnemonics * @param text test with Mnemonics * @return text w/o & * @see JLabel#setLabelFor(java.awt.Component) */ private String createMnemonic(String text) { m_savedMnemonic = 0; if (text == null) return text; int pos = text.indexOf('&'); if (pos != -1) // We have a nemonic { char ch = text.charAt(pos+1); if (ch != ' ') // &_ - is the & character { setDisplayedMnemonic(ch); setSavedMnemonic(ch); return text.substring(0, pos) + text.substring(pos+1); } } return text; } // createMnemonic /** * Set ReadWrite * @param rw enabled */ public void setReadWrite (boolean rw) { this.setEnabled(rw); } // setReadWrite /** * Set Label For * @param c component */ @Override public void setLabelFor (Component c) { //reset old if any if (getLabelFor() != null && getLabelFor() instanceof JTextComponent) {
((JTextComponent)getLabelFor()).setFocusAccelerator('\0'); } super.setLabelFor(c); if (c.getName() == null) c.setName(getName()); //workaround for focus accelerator issue if (c instanceof JTextComponent) { if (m_savedMnemonic > 0) { ((JTextComponent)c).setFocusAccelerator(m_savedMnemonic); } } } // setLabelFor /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic } // CLabel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CLabel.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired UserService userService; // 用户服务层 /** * 获取用户列表 * 处理 "/users" 的 GET 请求,用来获取用户列表 * 通过 @RequestParam 传递参数,进一步实现条件查询或者分页查询 */ @RequestMapping(method = RequestMethod.GET) public String getUserList(ModelMap map) { map.addAttribute("userList", userService.findAll()); return "userList"; } /** * 显示创建用户表单 * * @param map * @return */ @RequestMapping(value = "/create", method = RequestMethod.GET) public String createUserForm(ModelMap map) { map.addAttribute("user", new User()); map.addAttribute("action", "create"); return "userForm"; } /** * 创建用户 * 处理 "/users" 的 POST 请求,用来获取用户列表 * 通过 @ModelAttribute 绑定参数,也通过 @RequestParam 从页面中传递参数 */ @RequestMapping(value = "/create", method = RequestMethod.POST) public String postUser(ModelMap map, @ModelAttribute @Valid User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { map.addAttribute("action", "create"); return "userForm"; } userService.insertByUser(user); return "redirect:/users/"; } /** * 显示需要更新用户表单 * 处理 "/users/{id}" 的 GET 请求,通过 URL 中的 id 值获取 User 信息 * URL 中的 id ,通过 @PathVariable 绑定参数 */ @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
public String getUser(@PathVariable Long id, ModelMap map) { map.addAttribute("user", userService.findById(id)); map.addAttribute("action", "update"); return "userForm"; } /** * 处理 "/users/{id}" 的 PUT 请求,用来更新 User 信息 * */ @RequestMapping(value = "/update", method = RequestMethod.POST) public String putUser(ModelMap map, @ModelAttribute @Valid User user, BindingResult bindingResult) { if (bindingResult.hasErrors()) { map.addAttribute("action", "update"); return "userForm"; } userService.update(user); return "redirect:/users/"; } /** * 处理 "/users/{id}" 的 GET 请求,用来删除 User 信息 */ @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { userService.delete(id); return "redirect:/users/"; } }
repos\springboot-learning-example-master\chapter-4-spring-boot-validating-form-input\src\main\java\spring\boot\core\web\UserController.java
2
请完成以下Java代码
public class KafkaBackoffException extends KafkaException { private static final long serialVersionUID = 1L; private final String listenerId; private final TopicPartition topicPartition; private final long dueTimestamp; /** * Constructor with data from the BackOff event. * * @param message the error message. * @param topicPartition the partition that was backed off. * @param listenerId the listenerId for the consumer that was backed off. * @param dueTimestamp the time at which the message should be consumed. */
public KafkaBackoffException(String message, TopicPartition topicPartition, String listenerId, long dueTimestamp) { super(message); this.listenerId = listenerId; this.topicPartition = topicPartition; this.dueTimestamp = dueTimestamp; } public String getListenerId() { return this.listenerId; } public TopicPartition getTopicPartition() { return this.topicPartition; } public long getDueTimestamp() { return this.dueTimestamp; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\KafkaBackoffException.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderUpdateReq extends AbsReq { /** 订单id(必填项) */ private String id; /** 订单状态 {@link com.gaoxi.enumeration.order.OrderStateEnum} */ private Integer orderStateCode; /** 物流单号 */ private String expressNo; /** 支付方式 {@link com.gaoxi.enumeration.order.PayModeEnum} */ private Integer payModeCode; /** 订单总金额 */ private String totalPrice; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getOrderStateCode() { return orderStateCode; } public void setOrderStateCode(Integer orderStateCode) { this.orderStateCode = orderStateCode; } public String getExpressNo() { return expressNo; } public void setExpressNo(String expressNo) { this.expressNo = expressNo; } public Integer getPayModeCode() { return payModeCode; } public void setPayModeCode(Integer payModeCode) {
this.payModeCode = payModeCode; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } @Override public String toString() { return "OrderUpdateReq{" + "id='" + id + '\'' + ", orderStateCode=" + orderStateCode + ", expressNo='" + expressNo + '\'' + ", payModeCode=" + payModeCode + ", totalPrice='" + totalPrice + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\order\OrderUpdateReq.java
2
请完成以下Java代码
private void publishRefreshEvent(List<Signal<Route>> signals) { cache.put(CACHE_KEY, signals); Objects.requireNonNull(applicationEventPublisher, "ApplicationEventPublisher is required"); applicationEventPublisher.publishEvent(new RefreshRoutesResultEvent(this)); } private Flux<Route> getNonScopedRoutes(RefreshRoutesEvent scopedEvent) { return this.getRoutes() .filter(route -> !RouteLocator.matchMetadata(route.getMetadata(), scopedEvent.getMetadata())); } private void handleRefreshError(Throwable throwable) { if (log.isErrorEnabled()) { log.error("Refresh routes error !!!", throwable); }
Objects.requireNonNull(applicationEventPublisher, "ApplicationEventPublisher is required"); applicationEventPublisher.publishEvent(new RefreshRoutesResultEvent(this, throwable)); } @Override public int getOrder() { return 0; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\CachingRouteLocator.java
1
请完成以下Java代码
public void setAD_User_Attribute_ID (final int AD_User_Attribute_ID) { if (AD_User_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Attribute_ID, AD_User_Attribute_ID); } @Override public int getAD_User_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Attribute_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Attribute AD_Reference_ID=541332 * Reference name: AD_User_Attribute */ public static final int ATTRIBUTE_AD_Reference_ID=541332; /** Delegate = D */
public static final String ATTRIBUTE_Delegate = "D"; /** Politician = P */ public static final String ATTRIBUTE_Politician = "P"; /** Rechtsberater = R */ public static final String ATTRIBUTE_Rechtsberater = "R"; /** Schätzer = S */ public static final String ATTRIBUTE_Schaetzer = "S"; /** Vorstand = V */ public static final String ATTRIBUTE_Vorstand = "V"; @Override public void setAttribute (final java.lang.String Attribute) { set_Value (COLUMNNAME_Attribute, Attribute); } @Override public java.lang.String getAttribute() { return get_ValueAsString(COLUMNNAME_Attribute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Attribute.java
1
请完成以下Java代码
public class ADFormADValidator extends AbstractADValidator<I_AD_Form> { @Override public void validate(@NonNull final I_AD_Form form) { // In case of forms, this field may be empty if (Check.isBlank(form.getClassname())) { return; } Util.validateJavaClassname(form.getClassname(), null); } @Override public String getLogMessage(@NonNull final IADValidatorViolation violation) { final StringBuilder message = new StringBuilder(); try { final I_AD_Form form = InterfaceWrapperHelper.create(violation.getItem(), I_AD_Form.class);
message.append("Error on ").append(form).append(" (IsActive=").append(form.isActive()).append("): "); } catch (final Exception e) { message.append("Error (InterfaceWrapperHelper exception: ").append(e.getLocalizedMessage()).append(") on ").append(violation.getItem()).append(": "); } message.append(violation.getError().getLocalizedMessage()); return message.toString(); } @Override public Class<I_AD_Form> getType() { return I_AD_Form.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\spi\impl\ADFormADValidator.java
1
请完成以下Java代码
public OrgId getOrgIdByLocatorRepoId(final int locatorId) { return warehouseDAO.retrieveOrgIdByLocatorId(locatorId); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsOfTheSamePickingGroup(@NonNull final WarehouseId warehouseId) { final Set<WarehouseId> pickFromWarehouseIds = warehouseDAO.getWarehouseIdsOfSamePickingGroup(warehouseId); return warehouseDAO.getLocatorIdsByWarehouseIds(pickFromWarehouseIds); } @Override @NonNull public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds) { return warehouseDAO.getLocatorIdsByRepoId(locatorIds); } @Override public LocatorQRCode getLocatorQRCode(@NonNull final LocatorId locatorId) { final I_M_Locator locator = warehouseDAO.getLocatorById(locatorId); return LocatorQRCode.ofLocator(locator); } @Override @NonNull public ExplainedOptional<LocatorQRCode> getLocatorQRCodeByValue(@NonNull String locatorValue) { final List<I_M_Locator> locators = getActiveLocatorsByValue(locatorValue); if (locators.isEmpty()) { return ExplainedOptional.emptyBecause(AdempiereException.MSG_NotFound); } else if (locators.size() > 1)
{ return ExplainedOptional.emptyBecause(DBMoreThanOneRecordsFoundException.MSG_QueryMoreThanOneRecordsFound); } else { final I_M_Locator locator = locators.get(0); return ExplainedOptional.of(LocatorQRCode.ofLocator(locator)); } } @Override public List<I_M_Locator> getActiveLocatorsByValue(final @NotNull String locatorValue) { return warehouseDAO.retrieveActiveLocatorsByValue(locatorValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseBL.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiKeyDataValidator extends DataValidator<ApiKey> { private final ApiKeyDao apiKeyDao; private final TenantService tenantService; private final UserService userService; @Override protected void validateDataImpl(TenantId tenantId, ApiKey apiKey) { if (apiKey.getId() != null) { if (apiKey.getUuidId() == null) { throw new DataValidationException("API Key UUID should be specified!"); } if (apiKey.getId().isNullUid()) { throw new DataValidationException("API key UUID must not be the reserved null value!"); } } if (apiKey.getTenantId() == null || apiKey.getTenantId().getId() == null) { throw new DataValidationException("API key should be assigned to tenant!"); } if (!TenantId.SYS_TENANT_ID.equals(apiKey.getTenantId()) && !tenantService.tenantExists(apiKey.getTenantId())) { throw new DataValidationException("API key reference a non-existent tenant!"); } if (apiKey.getUserId() == null || apiKey.getUserId().getId() == null) {
throw new DataValidationException("API key should be assigned to user!"); } if (userService.findUserById(apiKey.getTenantId(), apiKey.getUserId()) == null) { throw new DataValidationException("API key reference a non-existent user!"); } } @Override protected ApiKey validateUpdate(TenantId tenantId, ApiKey apiKey) { ApiKey old = apiKeyDao.findById(tenantId, apiKey.getUuidId()); if (old == null) { throw new DataValidationException("Cannot update non-existent API key!"); } if (!old.getUserId().equals(apiKey.getUserId())) { throw new DataValidationException("Cannot update API key user id!"); } if (old.getExpirationTime() != apiKey.getExpirationTime()) { throw new DataValidationException("Cannot update API key expiration time!"); } return old; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\ApiKeyDataValidator.java
2
请完成以下Java代码
public Optional<Money> getProfitMinBasePrice(@NonNull final Collection<OrderAndLineId> orderAndLineIds) { if (orderAndLineIds.isEmpty()) { return Optional.empty(); } final ImmutableSet<Money> profitBasePrices = ordersRepo.getOrderLinesByIds(orderAndLineIds, I_C_OrderLine.class) .stream() .map(this::getProfitBasePrice) .collect(ImmutableSet.toImmutableSet()); if (profitBasePrices.isEmpty()) { return Optional.empty(); } else if (profitBasePrices.size() == 1) { return Optional.of(profitBasePrices.iterator().next()); } else if (!Money.isSameCurrency(profitBasePrices))
{ return Optional.empty(); } else { return profitBasePrices.stream().reduce(Money::min); } } private Money getProfitBasePrice(@NonNull final I_C_OrderLine orderLineRecord) { final CurrencyId currencyId = CurrencyId.ofRepoId(orderLineRecord.getC_Currency_ID()); return Money.of(orderLineRecord.getProfitPriceActual(), currencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\grossprofit\OrderLineWithGrossProfitPriceRepository.java
1
请完成以下Java代码
public String getId() { return id; } @Override public I_M_HU getM_HU() { if (huItem == null) { return null; } return huItem.getM_HU(); } @Override public I_M_HU getVHU() { if (vhuItem == null) { return null; } return vhuItem.getM_HU(); } private I_M_HU getEffectiveHU() { final I_M_HU hu = getM_HU(); if (hu != null) { return hu; } return getVHU(); } @Override public I_M_HU_Item getM_HU_Item() { return huItem; } @Override public I_M_HU_Item getVHU_Item() { return vhuItem; } @Override public IHUTransactionCandidate getCounterpart() { return counterpartTrx; } private void setCounterpart(@NonNull final IHUTransactionCandidate counterpartTrx) { Check.assume(this != counterpartTrx, "counterpartTrx != this"); if (this.counterpartTrx == null) { this.counterpartTrx = counterpartTrx; } else if (this.counterpartTrx == counterpartTrx) { // do nothing; it was already set } else { throw new HUException("Posible development error: changing the counterpart transaction is not allowed" + "\n Transaction: " + this + "\n Counterpart trx (old): " + this.counterpartTrx + "\n Counterpart trx (new): " + counterpartTrx);
} } @Override public void pair(final IHUTransactionCandidate counterpartTrx) { Check.errorUnless(counterpartTrx instanceof HUTransactionCandidate, "Param counterPartTrx needs to be a HUTransaction counterPartTrx={}", counterpartTrx); this.setCounterpart(counterpartTrx); // by casting to HUTransaction (which currently is the only implementation of IHUTransaction), we don't have to make setCounterpart() public. ((HUTransactionCandidate)counterpartTrx).setCounterpart(this); } @Override public LocatorId getLocatorId() { return locatorId; } @Override public void setSkipProcessing() { skipProcessing = true; } @Override public String getHUStatus() { return huStatus; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTransactionCandidate.java
1
请完成以下Java代码
public String toString() { // NOTE: we are making it translatable friendly because it's displayed in Preferences->Info->Role final int queryRecordsPerRole = getMaxQueryRecordsPerRole(); final int confirmQueryRecords = getConfirmQueryRecords(); return "WindowMaxQueryRecords[" + "@MaxQueryRecords@: " + queryRecordsPerRole + ", @ConfirmQueryRecords@: " + confirmQueryRecords + "]"; } /** @return false, i.e. never inherit this constraint because it shall be defined by current role itself */ @Override public boolean isInheritable() { return false; } /** * @return maximum allowed rows to be presented to user in a window or ZERO if no restriction. */ public int getMaxQueryRecordsPerRole()
{ return maxQueryRecordsPerRole; } /** * Gets the maximum allowed records to be presented to user, without asking him to confirm/refine the initial query. * * @return maximum allowed records to be presented to user, without asking him to confirm/refine the initial query; always returns greater than zero. */ public int getConfirmQueryRecords() { return confirmQueryRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\WindowMaxQueryRecordsConstraint.java
1
请在Spring Boot框架中完成以下Java代码
public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 写入缓存 * * @param key * @param value * @return
*/ @Override public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Redis\src\main\java\com\gaoxi\redis\service\RedisServiceImpl.java
2
请完成以下Java代码
public DmnDeploymentQuery createDeploymentQuery() { return new DmnDeploymentQueryImpl(commandExecutor); } @Override public NativeDmnDeploymentQuery createNativeDeploymentQuery() { return new NativeDmnDeploymentQueryImpl(commandExecutor); } @Override public DmnDecision getDecision(String decisionId) { return commandExecutor.execute(new GetDeploymentDecisionCmd(decisionId)); } @Override public DmnDefinition getDmnDefinition(String decisionId) { return commandExecutor.execute(new GetDmnDefinitionCmd(decisionId)); } @Override
public InputStream getDmnResource(String decisionId) { return commandExecutor.execute(new GetDeploymentDmnResourceCmd(decisionId)); } @Override public void setDecisionCategory(String decisionId, String category) { commandExecutor.execute(new SetDecisionTableCategoryCmd(decisionId, category)); } @Override public InputStream getDecisionRequirementsDiagram(String decisionId) { return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionId)); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnRepositoryServiceImpl.java
1
请完成以下Java代码
public BatchEntity findBatchById(String id) { return getDbEntityManager().selectById(BatchEntity.class, id); } public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) { configureQuery(batchQuery); return (Long) getDbEntityManager().selectOne("selectBatchCountByQueryCriteria", batchQuery); } @SuppressWarnings("unchecked") public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery, Page page) { configureQuery(batchQuery); return getDbEntityManager().selectList("selectBatchesByQueryCriteria", batchQuery, page); } public void updateBatchSuspensionStateById(String batchId, SuspensionState suspensionState) {
Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("batchId", batchId); parameters.put("suspensionState", suspensionState.getStateCode()); ListQueryParameterObject queryParameter = new ListQueryParameterObject(); queryParameter.setParameter(parameters); getDbEntityManager().update(BatchEntity.class, "updateBatchSuspensionStateByParameters", queryParameter); } protected void configureQuery(BatchQueryImpl batchQuery) { getAuthorizationManager().configureBatchQuery(batchQuery); getTenantManager().configureQuery(batchQuery); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\BatchManager.java
1
请完成以下Java代码
private Optional<BigDecimal> extractWeightInKg(@NonNull final I_M_Package mpackage) { if (InterfaceWrapperHelper.isNull(mpackage, I_M_Package.COLUMNNAME_PackageWeight)) { return Optional.empty(); } final BigDecimal weightInKg = kgPrecision.round(mpackage.getPackageWeight()); // we assume it's in Kg return weightInKg.signum() > 0 ? Optional.of(weightInKg) : Optional.empty(); } private void createAndSendDeliveryOrder( @NonNull final DeliveryOrderKey deliveryOrderKey, @NonNull final Collection<I_M_Package> mpackages) { final ShipperId shipperId = deliveryOrderKey.getShipperId(); final ShipperGatewayId shipperGatewayId = getShipperGatewayId(shipperId); final DeliveryOrderService deliveryOrderRepository = shipperRegistry.getDeliveryOrderService(shipperGatewayId); final ImmutableSet<PackageInfo> packageInfos = mpackages.stream() .map(mpackage -> PackageInfo.builder() .packageId(PackageId.ofRepoId(mpackage.getM_Package_ID())) .poReference(mpackage.getPOReference()) .description(StringUtils.trimBlankToNull(mpackage.getDescription())) .weightInKg(extractWeightInKg(mpackage).orElse(null)) .packageDimension(extractPackageDimensions(mpackage)) .build()) .collect(ImmutableSet.toImmutableSet()); final CreateDraftDeliveryOrderRequest request = CreateDraftDeliveryOrderRequest.builder() .deliveryOrderKey(deliveryOrderKey) .packageInfos(packageInfos) .build(); final DraftDeliveryOrderCreator shipperGatewayService = shipperRegistry.getShipperGatewayService(shipperGatewayId); DeliveryOrder deliveryOrder = shipperGatewayService.createDraftDeliveryOrder(request); deliveryOrder = deliveryOrderRepository.save(deliveryOrder); DeliveryOrderWorkpackageProcessor.enqueueOnTrxCommit(deliveryOrder.getId(), shipperGatewayId, deliveryOrderKey.getAsyncBatchId()); } private static PackageDimensions extractPackageDimensions(@NonNull final I_M_Package mpackage)
{ return PackageDimensions.builder() .lengthInCM(mpackage.getLengthInCm()) .widthInCM(mpackage.getWidthInCm()) .heightInCM(mpackage.getHeightInCm()) .build(); } private ShipperGatewayId getShipperGatewayId(final ShipperId shipperId) { return shipperDAO.getShipperGatewayId(shipperId).orElseThrow(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean hasServiceSupport(@NonNull final ShipperGatewayId shipperGatewayId) { return shipperRegistry.hasServiceSupport(shipperGatewayId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\ShipperGatewayFacade.java
1
请完成以下Java代码
public void setBackground (Color bg) { if (bg.equals(getBackground())) return; super.setBackground(bg); } // setBackground /** * Set Font to Bold * @param bold true bold false normal */ public void setFontBold (boolean bold) { Font font = getFont(); if (bold != font.isBold()) { font = new Font (font.getName(), bold ? Font.BOLD : Font.PLAIN, font.getSize()); setFont (font); } } // setFontBold /************************************************************************** * Set label text - if it includes &, the next character is the Mnemonic * @param mnemonicLabel Label containing Mnemonic */ @Override public void setText (String mnemonicLabel) { String text = createMnemonic (mnemonicLabel); super.setText (text); if (text != null && getName() == null) setName(text); //workaround for focus accelerator issue if (getLabelFor() != null && getLabelFor() instanceof JTextComponent) { if ( m_savedMnemonic > 0) ((JTextComponent)getLabelFor()).setFocusAccelerator(m_savedMnemonic); else ((JTextComponent)getLabelFor()).setFocusAccelerator('\0'); } } // setText /** * Create Mnemonics of text containing "&". * Based on MS notation of &Help => H is Mnemonics * @param text test with Mnemonics * @return text w/o & * @see JLabel#setLabelFor(java.awt.Component) */ private String createMnemonic(String text) { m_savedMnemonic = 0; if (text == null) return text; int pos = text.indexOf('&'); if (pos != -1) // We have a nemonic { char ch = text.charAt(pos+1); if (ch != ' ') // &_ - is the & character { setDisplayedMnemonic(ch); setSavedMnemonic(ch); return text.substring(0, pos) + text.substring(pos+1); } } return text; } // createMnemonic /** * Set ReadWrite * @param rw enabled */ public void setReadWrite (boolean rw) { this.setEnabled(rw); } // setReadWrite /** * Set Label For * @param c component */
@Override public void setLabelFor (Component c) { //reset old if any if (getLabelFor() != null && getLabelFor() instanceof JTextComponent) { ((JTextComponent)getLabelFor()).setFocusAccelerator('\0'); } super.setLabelFor(c); if (c.getName() == null) c.setName(getName()); //workaround for focus accelerator issue if (c instanceof JTextComponent) { if (m_savedMnemonic > 0) { ((JTextComponent)c).setFocusAccelerator(m_savedMnemonic); } } } // setLabelFor /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic } // CLabel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CLabel.java
1
请完成以下Java代码
public Builder<T> include(final T itemToInclude) { Check.assumeNotNull(itemToInclude, "itemToInclude not null"); final boolean added = includes.add(itemToInclude); // Reset last built, in case of change if (added) { lastBuilt = null; } return this; } public Builder<T> exclude(final T itemToExclude) { // guard against null: tollerate it but do nothing if (itemToExclude == null)
{ return this; } final boolean added = excludes.add(itemToExclude); // Reset last built, in case of change if (added) { lastBuilt = null; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IncludeExcludeListPredicate.java
1
请完成以下Java代码
private static CertificateFactory x509CertificateFactory() { try { return CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { throw new IllegalArgumentException(ex); } } private static List<String> readAllLines(InputStream source) { BufferedReader reader = new BufferedReader(new InputStreamReader(source)); return reader.lines().collect(Collectors.toList()); } private static KeyFactory rsaFactory() { try { return KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException(ex); } } private static boolean isNotPkcs8Wrapper(String line) { return !PKCS8_PEM_HEADER.equals(line) && !PKCS8_PEM_FOOTER.equals(line); } private static class X509PemDecoder implements Converter<List<String>, RSAPublicKey> { private final KeyFactory keyFactory; X509PemDecoder(KeyFactory keyFactory) { this.keyFactory = keyFactory; } @Override public @NonNull RSAPublicKey convert(List<String> lines) { StringBuilder base64Encoded = new StringBuilder(); for (String line : lines) { if (isNotX509PemWrapper(line)) { base64Encoded.append(line); } } byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString()); try { return (RSAPublicKey) this.keyFactory.generatePublic(new X509EncodedKeySpec(x509)); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private boolean isNotX509PemWrapper(String line) { return !X509_PEM_HEADER.equals(line) && !X509_PEM_FOOTER.equals(line); } } private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> {
private final CertificateFactory certificateFactory; X509CertificateDecoder(CertificateFactory certificateFactory) { this.certificateFactory = certificateFactory; } @Override public @NonNull RSAPublicKey convert(List<String> lines) { StringBuilder base64Encoded = new StringBuilder(); for (String line : lines) { if (isNotX509CertificateWrapper(line)) { base64Encoded.append(line); } } byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString()); try (InputStream x509CertStream = new ByteArrayInputStream(x509)) { X509Certificate certificate = (X509Certificate) this.certificateFactory .generateCertificate(x509CertStream); return (RSAPublicKey) certificate.getPublicKey(); } catch (CertificateException | IOException ex) { throw new IllegalArgumentException(ex); } } private boolean isNotX509CertificateWrapper(String line) { return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\converter\RsaKeyConverters.java
1
请完成以下Spring Boot application配置
spring: security: user: name: "user" password: "password" boot: admin: client: username: "user" #These two are needed so that the client password: "password" #can register at the protected server api instance: metadata: user.name:
"user" #These two are needed so that the server user.password: "password" #can access the protected client endpoints
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\resources\application-secure.yml
2
请在Spring Boot框架中完成以下Java代码
public class CasSecuredApplication { private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class); public static void main(String... args) { SpringApplication.run(CasSecuredApplication.class, args); } @Bean public CasAuthenticationFilter casAuthenticationFilter( AuthenticationManager authenticationManager, ServiceProperties serviceProperties) throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setAuthenticationManager(authenticationManager); filter.setServiceProperties(serviceProperties); return filter; } @Bean public ServiceProperties serviceProperties() { logger.info("service properties"); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService("http://localhost:8900/login/cas"); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public TicketValidator ticketValidator() { return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); } @Bean public CasUserDetailsService getUser(){ return new CasUserDetailsService(); } @Bean public CasAuthenticationProvider casAuthenticationProvider( TicketValidator ticketValidator, ServiceProperties serviceProperties) { CasAuthenticationProvider provider = new CasAuthenticationProvider(); provider.setServiceProperties(serviceProperties); provider.setTicketValidator(ticketValidator); provider.setUserDetailsService(
s -> new User("casuser", "Mellon", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); //For Authentication with a Database-backed UserDetailsService //provider.setUserDetailsService(getUser()); provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); return provider; } @Bean public SecurityContextLogoutHandler securityContextLogoutHandler() { return new SecurityContextLogoutHandler(); } @Bean public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/cas/logout", securityContextLogoutHandler()); logoutFilter.setFilterProcessesUrl("/logout/cas"); return logoutFilter; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } }
repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\java\com\baeldung\cassecuredapp\CasSecuredApplication.java
2
请完成以下Java代码
public MFColor setGradientStartPoint(final int startPoint) { if (!isGradient()) { return this; } return toBuilder().gradientStartPoint(startPoint).build(); } public MFColor setGradientRepeatDistance(final int repeatDistance) { if (!isGradient()) { return this; } return toBuilder().gradientRepeatDistance(repeatDistance).build(); } public MFColor setTextureURL(final URL textureURL) { if (!isTexture() || textureURL == null) { return this; } return toBuilder().textureURL(textureURL).build(); } public MFColor setTextureTaintColor(final Color color) { if (!isTexture() || color == null) { return this; } return toBuilder().textureTaintColor(color).build(); } public MFColor setTextureCompositeAlpha(final float alpha) { if (!isTexture()) { return this; } return toBuilder().textureCompositeAlpha(alpha).build(); } public MFColor setLineColor(final Color color) { if (!isLine() || color == null) { return this; } return toBuilder().lineColor(color).build(); } public MFColor setLineBackColor(final Color color) {
if (!isLine() || color == null) { return this; } return toBuilder().lineBackColor(color).build(); } public MFColor setLineWidth(final float width) { if (!isLine()) { return this; } return toBuilder().lineWidth(width).build(); } public MFColor setLineDistance(final int distance) { if (!isLine()) { return this; } return toBuilder().lineDistance(distance).build(); } public MFColor toFlatColor() { switch (getType()) { case FLAT: return this; case GRADIENT: return ofFlatColor(getGradientUpperColor()); case LINES: return ofFlatColor(getLineBackColor()); case TEXTURE: return ofFlatColor(getTextureTaintColor()); default: throw new IllegalStateException("Type not supported: " + getType()); } } public String toHexString() { final Color awtColor = toFlatColor().getFlatColor(); return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } public static String toHexString(final int red, final int green, final int blue) { Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red); Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green); Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue); return String.format("#%02x%02x%02x", red, green, blue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java
1
请完成以下Java代码
public String toString() { return "PlainContextAware[" // +", ctx="+ctx // don't print it... it's fucking too big + ", trxName=" + trxName + "]"; } @Override public int hashCode() { return new HashcodeBuilder() .append(ctx) .append(trxName) .toHashcode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final PlainContextAware other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .appendByRef(ctx, other.ctx) .append(trxName, other.trxName) .isEqual();
} @Override public Properties getCtx() { return ctx; } @Override public String getTrxName() { return trxName; } @Override public boolean isAllowThreadInherited() { return allowThreadInherited; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\PlainContextAware.java
1
请完成以下Java代码
public void add(String key) { tfDictionary.add(key); } public List<String> extractSuffixExtended(int length, int size) { return extractSuffix(length, size, true); } /** * 提取公共后缀 * @param length 公共后缀长度 * @param size 频率最高的前多少个公共后缀 * @param extend 长度是否拓展为从1到length为止的后缀 * @return 公共后缀列表 */ public List<String> extractSuffix(int length, int size, boolean extend) { TFDictionary suffixTreeSet = new TFDictionary(); for (String key : tfDictionary.keySet()) { if (key.length() > length) { suffixTreeSet.add(key.substring(key.length() - length, key.length())); if (extend) { for (int l = 1; l < length; ++l) { suffixTreeSet.add(key.substring(key.length() - l, key.length())); } } } } if (extend) { size *= length; } return extract(suffixTreeSet, size); } private static List<String> extract(TFDictionary suffixTreeSet, int size) { List<String> suffixList = new ArrayList<String>(size); for (TermFrequency termFrequency : suffixTreeSet.values()) { if (suffixList.size() >= size) break; suffixList.add(termFrequency.getKey()); } return suffixList; } /** * 此方法认为后缀一定是整个的词语,所以length是以词语为单位的 * @param length * @param size * @param extend * @return */ public List<String> extractSuffixByWords(int length, int size, boolean extend) { TFDictionary suffixTreeSet = new TFDictionary(); for (String key : tfDictionary.keySet())
{ List<Term> termList = StandardTokenizer.segment(key); if (termList.size() > length) { suffixTreeSet.add(combine(termList.subList(termList.size() - length, termList.size()))); if (extend) { for (int l = 1; l < length; ++l) { suffixTreeSet.add(combine(termList.subList(termList.size() - l, termList.size()))); } } } } return extract(suffixTreeSet, size); } private static String combine(List<Term> termList) { StringBuilder sbResult = new StringBuilder(); for (Term term : termList) { sbResult.append(term.word); } return sbResult.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonSuffixExtractor.java
1
请完成以下Java代码
public void setRemittanceAmt (final BigDecimal RemittanceAmt) { set_Value (COLUMNNAME_RemittanceAmt, RemittanceAmt); } @Override public BigDecimal getRemittanceAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_RemittanceAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setService_BPartner_ID (final int Service_BPartner_ID) { if (Service_BPartner_ID < 1) set_Value (COLUMNNAME_Service_BPartner_ID, null); else set_Value (COLUMNNAME_Service_BPartner_ID, Service_BPartner_ID); } @Override public int getService_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Service_BPartner_ID); } @Override public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount) { set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount); } @Override public BigDecimal getServiceFeeAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public org.compiere.model.I_C_Invoice getService_Fee_Invoice() { return get_ValueAsPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setService_Fee_Invoice(final org.compiere.model.I_C_Invoice Service_Fee_Invoice) { set_ValueFromPO(COLUMNNAME_Service_Fee_Invoice_ID, org.compiere.model.I_C_Invoice.class, Service_Fee_Invoice); } @Override public void setService_Fee_Invoice_ID (final int Service_Fee_Invoice_ID) { if (Service_Fee_Invoice_ID < 1) set_Value (COLUMNNAME_Service_Fee_Invoice_ID, null); else set_Value (COLUMNNAME_Service_Fee_Invoice_ID, Service_Fee_Invoice_ID); } @Override public int getService_Fee_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_Service_Fee_Invoice_ID);
} @Override public void setServiceFeeVatRate (final @Nullable BigDecimal ServiceFeeVatRate) { set_Value (COLUMNNAME_ServiceFeeVatRate, ServiceFeeVatRate); } @Override public BigDecimal getServiceFeeVatRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeVatRate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setService_Product_ID (final int Service_Product_ID) { if (Service_Product_ID < 1) set_Value (COLUMNNAME_Service_Product_ID, null); else set_Value (COLUMNNAME_Service_Product_ID, Service_Product_ID); } @Override public int getService_Product_ID() { return get_ValueAsInt(COLUMNNAME_Service_Product_ID); } @Override public void setService_Tax_ID (final int Service_Tax_ID) { if (Service_Tax_ID < 1) set_Value (COLUMNNAME_Service_Tax_ID, null); else set_Value (COLUMNNAME_Service_Tax_ID, Service_Tax_ID); } @Override public int getService_Tax_ID() { return get_ValueAsInt(COLUMNNAME_Service_Tax_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice_Line.java
1
请完成以下Java代码
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 Period No. @param PeriodNo Unique Period Number */ public void setPeriodNo (int PeriodNo) { set_Value (COLUMNNAME_PeriodNo, Integer.valueOf(PeriodNo)); } /** Get Period No. @return Unique Period Number */ public int getPeriodNo () { Integer ii = (Integer)get_Value(COLUMNNAME_PeriodNo); if (ii == null) return 0; return ii.intValue(); } /** PeriodType AD_Reference_ID=115 */ public static final int PERIODTYPE_AD_Reference_ID=115; /** Standard Calendar Period = S */ public static final String PERIODTYPE_StandardCalendarPeriod = "S"; /** Adjustment Period = A */ public static final String PERIODTYPE_AdjustmentPeriod = "A"; /** Set Period Type. @param PeriodType Period Type */ public void setPeriodType (String PeriodType) { set_ValueNoCheck (COLUMNNAME_PeriodType, PeriodType); }
/** Get Period Type. @return Period Type */ public String getPeriodType () { return (String)get_Value(COLUMNNAME_PeriodType); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java
1
请完成以下Java代码
public int getCollectedErrorsCount() { return errors.size(); } public void setCurrentWindow(@NonNull final AdWindowId windowId) { setCurrentWindow(windowId, null); } public void setCurrentWindow(@NonNull final DocumentEntityDescriptor entityDescriptor) { setCurrentWindow(entityDescriptor.getWindowId().toAdWindowId(), entityDescriptor.getCaption().translate(adLanguage)); } public void setCurrentWindow(@NonNull final AdWindowId windowId, @Nullable final String windowName) { this.currentWindowId = windowId; this._currentWindowName = windowName; } public void clearCurrentWindow() { this.currentWindowId = null; this._currentWindowName = null; } @Nullable public String getCurrentWindowName() { if (this._currentWindowName == null && this.currentWindowId != null) { this._currentWindowName = adWindowDAO.retrieveWindowName(currentWindowId).translate(adLanguage); } return this._currentWindowName; }
public void collectError(@NonNull final String errorMessage) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .errorMessage(errorMessage) .build()); } public void collectError(@NonNull final Throwable exception) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .error(JsonErrors.ofThrowable(exception, adLanguage)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ErrorsCollector.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() {
return email; } public void setEmail(String email) { this.email = email; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\parametrizedtypereference\User.java
1
请完成以下Java代码
public class JsonObjectRestVariableConverter implements RestVariableConverter { protected ObjectMapper objectMapper; public JsonObjectRestVariableConverter(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public String getRestTypeName() { return "json"; } @Override public Class<?> getVariableType() { return JsonNode.class; } @Override public Object getVariableValue(EngineRestVariable result) { if (result.getValue() != null) { if (result.getValue() instanceof Map || result.getValue() instanceof List) { // When the variable is coming from the REST API it automatically gets converted to an ArrayList or // LinkedHashMap. In all other cases JSON is saved as ArrayNode or ObjectNode. For consistency the // variable is converted to such an object here. return objectMapper.valueToTree(result.getValue()); } else {
return result.getValue(); } } return null; } @Override public void convertVariableValue(Object variableValue, EngineRestVariable result) { if (variableValue != null) { if (!(variableValue instanceof JsonNode)) { throw new FlowableIllegalArgumentException("Converter can only convert tools.jackson.databind.JsonNode."); } result.setValue(variableValue); } else { result.setValue(null); } } }
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\variable\JsonObjectRestVariableConverter.java
1
请完成以下Java代码
public void setSource(DmnElement source) { sourceRef.setReferenceTargetElement(this, source); } public DmnElement getTarget() { return targetRef.getReferenceTargetElement(this); } public void setTarget(DmnElement target) { targetRef.setReferenceTargetElement(this, target); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, DMN_ELEMENT_ASSOCIATION) .namespaceUri(LATEST_DMN_NS) .extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); } }); associationDirectionAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .defaultValue(AssociationDirection.None)
.build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); sourceRef = sequenceBuilder.element(SourceRef.class) .required() .uriElementReference(DmnElement.class) .build(); targetRef = sequenceBuilder.element(TargetRef.class) .required() .uriElementReference(DmnElement.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\AssociationImpl.java
1
请完成以下Java代码
public CostPrice addToOwnCostPrice(@NonNull final CostAmount ownCostPriceToAdd) { if (ownCostPriceToAdd.isZero()) { return this; } return withOwnCostPrice(getOwnCostPrice().add(ownCostPriceToAdd)); } public CostPrice withOwnCostPrice(final CostAmount ownCostPrice) { return toBuilder().ownCostPrice(ownCostPrice).build(); } public CostPrice withZeroOwnCostPrice() { final CostAmount ownCostPrice = getOwnCostPrice(); if (ownCostPrice.isZero()) { return this; } return withOwnCostPrice(ownCostPrice.toZero()); } public CostPrice withZeroComponentsCostPrice() { final CostAmount componentsCostPrice = getComponentsCostPrice(); if (componentsCostPrice.isZero()) { return this; } return withComponentsCostPrice(componentsCostPrice.toZero()); } public CostPrice withComponentsCostPrice(final CostAmount componentsCostPrice) { return toBuilder().componentsCostPrice(componentsCostPrice).build(); } public CostPrice add(final CostPrice costPrice) { if (!UomId.equals(this.getUomId(), costPrice.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + costPrice); } return builder() .ownCostPrice(getOwnCostPrice().add(costPrice.getOwnCostPrice())) .componentsCostPrice(getComponentsCostPrice().add(costPrice.getComponentsCostPrice())) .uomId(getUomId()) .build(); }
public CostAmount multiply(@NonNull final Quantity quantity) { if (!UomId.equals(uomId, quantity.getUomId())) { throw new AdempiereException("UOM does not match: " + this + ", " + quantity); } return toCostAmount().multiply(quantity); } public CostAmount multiply( @NonNull final Duration duration, @NonNull final TemporalUnit durationUnit) { final BigDecimal durationBD = DurationUtils.toBigDecimal(duration, durationUnit); return toCostAmount().multiply(durationBD); } public CostPrice convertAmounts( @NonNull final UomId toUomId, @NonNull final UnaryOperator<CostAmount> converter) { if (UomId.equals(this.uomId, toUomId)) { return this; } return toBuilder() .uomId(toUomId) .ownCostPrice(converter.apply(getOwnCostPrice())) .componentsCostPrice(converter.apply(getComponentsCostPrice())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostPrice.java
1
请完成以下Java代码
public String getState() { return state; } public void setState(String state) { this.state = state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override
public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", processDefinitionKey=" + processDefinitionKey + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", executionId=" + executionId + ", tenantId=" + tenantId + ", activityInstanceId=" + activityInstanceId + ", caseDefinitionKey=" + caseDefinitionKey + ", caseDefinitionId=" + caseDefinitionId + ", caseInstanceId=" + caseInstanceId + ", caseExecutionId=" + caseExecutionId + ", name=" + name + ", createTime=" + createTime + ", revision=" + revision + ", serializerName=" + getSerializerName() + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", state=" + state + ", byteArrayId=" + getByteArrayId() + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java
1
请完成以下Java代码
public class FailedDeserializationInfo { private final String topic; private final @Nullable Headers headers; private final byte[] data; private final boolean isForKey; private final Exception exception; /** * Construct an instance with the contextual information. * @param topic topic associated with the data. * @param headers headers associated with the record; may be empty. * @param data serialized bytes; may be null. * @param isForKey true for a key deserializer, false otherwise. * @param exception exception causing the deserialization error. */ public FailedDeserializationInfo(String topic, @Nullable Headers headers, byte[] data, boolean isForKey, Exception exception) { this.topic = topic; this.headers = headers; this.data = Arrays.copyOf(data, data.length); this.isForKey = isForKey; this.exception = exception; } public String getTopic() {
return this.topic; } public @Nullable Headers getHeaders() { return this.headers; } public byte[] getData() { return Arrays.copyOf(this.data, this.data.length); } public boolean isForKey() { return this.isForKey; } public Exception getException() { return this.exception; } @Override public String toString() { return "FailedDeserializationInfo{" + "topic='" + this.topic + '\'' + ", headers=" + this.headers + ", data=" + Arrays.toString(this.data) + ", isForKey=" + this.isForKey + ", exception=" + this.exception + '}'; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\FailedDeserializationInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class JobConfiguration { private final static Logger LOGGER = Logger.getLogger(JobConfiguration.class.getName()); @Autowired private PlatformTransactionManager transactionManager; @Autowired private JobRepository jobRepository; @Bean public Job job1(Step step1, Step step2) { return new JobBuilder("job1", jobRepository).incrementer(new RunIdIncrementer()) .start(step1) .next(step2) .build(); } @Bean public Step step1() { return new StepBuilder("job1step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("Tasklet has run"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } @Bean public Step step2() { return new StepBuilder("job1step2", jobRepository).<String, String> chunk(3, transactionManager) .reader(new ListItemReader<>(Arrays.asList("7", "2", "3", "10", "5", "6"))) .processor(new ItemProcessor<String, String>() { @Override public String process(String item) throws Exception { LOGGER.info("Processing of chunks"); return String.valueOf(Integer.parseInt(item) * -1); } }) .writer(new ItemWriter<String>() { @Override public void write(Chunk<? extends String> items) throws Exception { for (String item : items) { LOGGER.info(">> " + item); } }
}) .build(); } @Bean public Job job2(Step job2step1) { return new JobBuilder("job2", jobRepository).incrementer(new RunIdIncrementer()) .start(job2step1) .build(); } @Bean public Step job2step1() { return new StepBuilder("job2step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("This job is from Baeldung"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-task\springcloudtaskbatch\src\main\java\com\baeldung\task\JobConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class AppDictionaryBL implements IAppDictionaryBL { // private final Logger log = CLogMgt.getLogger(getClass()); @Override public MTable getReferencedTable(Properties ctx, String tableName, String columnName) { final MTable table = MTable.get(ctx, tableName); return getReferencedTable(table, columnName); } @Override public MTable getReferencedTable(MTable parentTable, String columnName) { final Properties ctx = parentTable.getCtx(); final MColumn parentColumn = parentTable.getColumn(columnName); if (parentColumn == null) return null; final int dt = parentColumn.getAD_Reference_ID(); final int referenceId = parentColumn.getAD_Reference_Value_ID(); // Check first if is a custom lookup (e.g. Location, PAttribute etc)
String tableName = DisplayType.getTableName(dt); if (tableName != null) { return MTable.get(ctx, tableName); } // TableDir if (dt == DisplayType.TableDir || (dt == DisplayType.Search && referenceId <= 0)) { tableName = MQuery.getZoomTableName(columnName); return MTable.get(ctx, tableName); } // Table if (dt == DisplayType.Table || (dt == DisplayType.Search && referenceId > 0)) { // TODO improve, cache int tableId = DB.getSQLValueEx(null, "SELECT AD_Table_ID FROM AD_Ref_Table WHERE AD_Reference_ID=?", referenceId); return MTable.get(ctx, tableId); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\AppDictionaryBL.java
2
请完成以下Java代码
public void setDescription (final @Nullable String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setExternalSystem_Outbound_Endpoint_ID (final int ExternalSystem_Outbound_Endpoint_ID) { if (ExternalSystem_Outbound_Endpoint_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID, ExternalSystem_Outbound_Endpoint_ID); } @Override public int getExternalSystem_Outbound_Endpoint_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Outbound_Endpoint_ID); } @Override public void setLoginUsername (final @Nullable String LoginUsername) { set_Value (COLUMNNAME_LoginUsername, LoginUsername); } @Override public String getLoginUsername() { return get_ValueAsString(COLUMNNAME_LoginUsername); } @Override public void setOutboundHttpEP (final String OutboundHttpEP) { set_Value (COLUMNNAME_OutboundHttpEP, OutboundHttpEP); } @Override public String getOutboundHttpEP() { return get_ValueAsString(COLUMNNAME_OutboundHttpEP); } @Override public void setOutboundHttpMethod (final String OutboundHttpMethod) { set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod); } @Override public String getOutboundHttpMethod() { return get_ValueAsString(COLUMNNAME_OutboundHttpMethod); } @Override public void setPassword (final @Nullable String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSasSignature (final @Nullable String SasSignature) { set_Value (COLUMNNAME_SasSignature, SasSignature); } @Override public String getSasSignature() { return get_ValueAsString(COLUMNNAME_SasSignature);
} /** * Type AD_Reference_ID=542016 * Reference name: ExternalSystem_Outbound_Endpoint_EndpointType */ public static final int TYPE_AD_Reference_ID=542016; /** HTTP = HTTP */ public static final String TYPE_HTTP = "HTTP"; /** SFTP = SFTP */ public static final String TYPE_SFTP = "SFTP"; /** FILE = FILE */ public static final String TYPE_FILE = "FILE"; /** EMAIL = EMAIL */ public static final String TYPE_EMAIL = "EMAIL"; /** TCP = TCP */ public static final String TYPE_TCP = "TCP"; @Override public void setType (final String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java
1
请完成以下Java代码
public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } /** * Status AD_Reference_ID=542015 * Reference name: OutboundLogLineStatus */ public static final int STATUS_AD_Reference_ID=542015; /** Print_Success = Print_Success */ public static final String STATUS_Print_Success = "Print_Success"; /** Print_Failure = Print_Failure */ public static final String STATUS_Print_Failure = "Print_Failure"; /** Email_Success = Email_Success */ public static final String STATUS_Email_Success = "Email_Success"; /** Email_Failure = Email_Failure */
public static final String STATUS_Email_Failure = "Email_Failure"; @Override public void setStatus (final @Nullable java.lang.String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @Override public void setStoreURI (final @Nullable java.lang.String StoreURI) { set_Value (COLUMNNAME_StoreURI, StoreURI); } @Override public java.lang.String getStoreURI() { return get_ValueAsString(COLUMNNAME_StoreURI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java-gen\de\metas\document\archive\model\X_C_Doc_Outbound_Log_Line.java
1
请在Spring Boot框架中完成以下Java代码
public class MilestoneRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); public void save(@NonNull final Milestone milestone) { final I_S_Milestone record = InterfaceWrapperHelper.loadOrNew(milestone.getMilestoneId(), I_S_Milestone.class); if (milestone.getDueDate() != null) { record.setMilestone_DueDate(Timestamp.from(milestone.getDueDate())); } record.setAD_Org_ID(milestone.getOrgId().getRepoId()); record.setName(milestone.getName()); record.setValue(milestone.getValue()); record.setDescription(milestone.getDescription()); record.setProcessed(milestone.isProcessed()); record.setExternalUrl(milestone.getExternalURL());
InterfaceWrapperHelper.saveRecord(record); milestone.setMilestoneId(MilestoneId.ofRepoId(record.getS_Milestone_ID())); } public boolean exists(@NonNull final MilestoneId milestoneId) { return queryBL .createQueryBuilder(I_S_Milestone.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Milestone.COLUMNNAME_S_Milestone_ID, milestoneId.getRepoId()) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\milestone\MilestoneRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityFilterProperties { /** * Order applied to the {@code SecurityFilterChain} that is used to configure basic * authentication for application endpoints. Create your own * {@code SecurityFilterChain} if you want to add your own authentication for all or * some of those endpoints. */ public static final int BASIC_AUTH_ORDER = Ordered.LOWEST_PRECEDENCE - 5; /** * Default order of Spring Security's Filter in the servlet container (i.e. amongst * other filters registered with the container). There is no connection between this * and the {@code @Order} on a {@code SecurityFilterChain}. */ public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100; /** * Security filter chain order for Servlet-based web applications. */ private int order = DEFAULT_FILTER_ORDER; /** * Security filter chain dispatcher types for Servlet-based web applications. */ private Set<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class); public int getOrder() { return this.order;
} public void setOrder(int order) { this.order = order; } public Set<DispatcherType> getDispatcherTypes() { return this.dispatcherTypes; } public void setDispatcherTypes(Set<DispatcherType> dispatcherTypes) { this.dispatcherTypes = dispatcherTypes; } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\SecurityFilterProperties.java
2
请在Spring Boot框架中完成以下Java代码
public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public CategoryEntity getTopCateEntity() { return topCateEntity; } public void setTopCateEntity(CategoryEntity topCateEntity) { this.topCateEntity = topCateEntity; } public CategoryEntity getSubCategEntity() { return subCategEntity; } public void setSubCategEntity(CategoryEntity subCategEntity) { this.subCategEntity = subCategEntity; } public BrandEntity getBrandEntity() { return brandEntity; } public void setBrandEntity(BrandEntity brandEntity) { this.brandEntity = brandEntity; } public ProdStateEnum getProdStateEnum() { return prodStateEnum; } public void setProdStateEnum(ProdStateEnum prodStateEnum) { this.prodStateEnum = prodStateEnum; } public List<ProdImageEntity> getProdImageEntityList() { return prodImageEntityList; } public void setProdImageEntityList(List<ProdImageEntity> prodImageEntityList) { this.prodImageEntityList = prodImageEntityList; } public String getContent() { return content; } public void setContent(String content) { this.content = content;
} public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } @Override public String toString() { return "ProductEntity{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请完成以下Java代码
private LookupDataSource getLookupDataSource(@NonNull final String fieldName) { if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName)) { return paymentTermLookup; } else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName)) { return priceTypeLookup; } else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName)) { return pricingSystemLookup; } else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName)) { return currencyIdLookup; } else { throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field"); } } public String getTemporaryPriceConditionsColor()
{ return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor); } private String retrieveTemporaryPriceConditionsColor() { final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId(); return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId)); } private static String toHexString(@Nullable final MFColor color) { if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java
1
请完成以下Java代码
public void dump(String projectId) { this.stringAtomicReference.set(projectId); } public AtomicReference<String> getStringAtomicReference() { return stringAtomicReference; } } @Bean IntegrationFlow inboundProcess(FlowableInboundGateway inboundGateway) { return IntegrationFlow .from(inboundGateway) .handle(new GenericHandler<DelegateExecution>() { @Override public Object handle(DelegateExecution execution, MessageHeaders headers) { return MessageBuilder.withPayload(execution) .setHeader("projectId", "2143243") .setHeader("orderId", "246") .copyHeaders(headers).build(); } }) .get(); } @Bean
CommandLineRunner init( final AnalysingService analysingService, final RuntimeService runtimeService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { String integrationGatewayProcess = "integrationGatewayProcess"; runtimeService.startProcessInstanceByKey( integrationGatewayProcess, Collections.singletonMap("customerId", (Object) 232L)); System.out.println("projectId=" + analysingService.getStringAtomicReference().get()); } }; } // ... }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-integration\src\main\java\flowable\Application.java
1
请完成以下Java代码
public EntityView findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(entityViewRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public PageData<EntityView> findByTenantId(UUID tenantId, PageLink pageLink) { return findEntityViewsByTenantId(tenantId, pageLink); } @Override public EntityViewId getExternalIdByInternal(EntityViewId internalId) { return Optional.ofNullable(entityViewRepository.getExternalIdById(internalId.getId())) .map(EntityViewId::new).orElse(null); } @Override public EntityView findByTenantIdAndName(UUID tenantId, String name) { return findEntityViewByTenantIdAndName(tenantId, name).orElse(null); } @Override
public PageData<EntityView> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<EntityViewFields> findNextBatch(UUID id, int batchSize) { return entityViewRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) { return entityViewRepository.findEntityInfosByNamePrefix(tenantId.getId(), name); } @Override public EntityType getEntityType() { return EntityType.ENTITY_VIEW; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\entityview\JpaEntityViewDao.java
1
请完成以下Java代码
public class DDOrderDropToCommand { @NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class); @NonNull private final DDOrderLowLevelDAO ddOrderLowLevelDAO; @NonNull private final DDOrderMoveScheduleRepository ddOrderMoveScheduleRepository; @NonNull private final PPOrderSourceHUService ppOrderSourceHUService; // Params @NonNull private final Instant movementDate = SystemTime.asInstant(); @NonNull private final Set<DDOrderMoveScheduleId> scheduleIds; @Nullable private final LocatorId dropToLocatorId; @Builder private DDOrderDropToCommand( final @NonNull DDOrderLowLevelDAO ddOrderLowLevelDAO, final @NonNull DDOrderMoveScheduleRepository ddOrderMoveScheduleRepository, final @NonNull PPOrderSourceHUService ppOrderSourceHUService, // final @NonNull DDOrderDropToRequest request) { this.ddOrderLowLevelDAO = ddOrderLowLevelDAO; this.ddOrderMoveScheduleRepository = ddOrderMoveScheduleRepository; this.ppOrderSourceHUService = ppOrderSourceHUService; this.scheduleIds = request.getScheduleIds(); this.dropToLocatorId = request.getDropToLocatorId(); } public ImmutableList<DDOrderMoveSchedule> execute() { return trxManager.callInThreadInheritedTrx(this::executeInTrx); } private ImmutableList<DDOrderMoveSchedule> executeInTrx() { return ddOrderMoveScheduleRepository.updateByIds(scheduleIds, this::processSchedule); } private void processSchedule(final DDOrderMoveSchedule schedule) { schedule.assertInTransit(); //
// generate movement InTransit -> DropTo Locator final LocatorId dropToLocatorId = this.dropToLocatorId != null ? this.dropToLocatorId : schedule.getDropToLocatorId(); final MovementId dropToMovementId = createDropToMovement(schedule, dropToLocatorId); // // update the schedule schedule.markAsDroppedTo(dropToLocatorId, dropToMovementId); } private MovementId createDropToMovement(@NonNull final DDOrderMoveSchedule schedule, @NonNull final LocatorId dropToLocatorId) { final I_DD_Order ddOrder = ddOrderLowLevelDAO.getById(schedule.getDdOrderId()); final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getInTransitLocatorId().orElseThrow()) .toLocatorId(dropToLocatorId) .huIdsToMove(schedule.getPickedHUIds()) .build(); final HUMovementGeneratorResult result = new HUMovementGenerator(request).createMovement(); final PPOrderId forwardPPOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID()); if (forwardPPOrderId != null) { reserveHUsForManufacturing(forwardPPOrderId, result); } return result.getSingleMovementLineId().getMovementId(); } private void reserveHUsForManufacturing(@NonNull final PPOrderId ppOrderId, @NonNull final HUMovementGeneratorResult result) { ppOrderSourceHUService.addSourceHUs(ppOrderId, result.getMovedHUIds()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\drop_to\DDOrderDropToCommand.java
1
请在Spring Boot框架中完成以下Java代码
ConfigDataResourceNotFoundException withLocation(ConfigDataLocation location) { return new ConfigDataResourceNotFoundException(this.resource, location, getCause()); } private static String getMessage(ConfigDataResource resource, @Nullable ConfigDataLocation location) { return String.format("Config data %s cannot be found", getReferenceDescription(resource, location)); } private static String getReferenceDescription(ConfigDataResource resource, @Nullable ConfigDataLocation location) { String description = String.format("resource '%s'", resource); if (location != null) { description += String.format(" via location '%s'", location); } return description; } /** * Throw a {@link ConfigDataNotFoundException} if the specified {@link Path} does not * exist. * @param resource the config data resource * @param pathToCheck the path to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, Path pathToCheck) { throwIfNot(resource, Files.exists(pathToCheck)); } /** * Throw a {@link ConfigDataNotFoundException} if the specified {@link File} does not * exist. * @param resource the config data resource * @param fileToCheck the file to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, File fileToCheck) { throwIfNot(resource, fileToCheck.exists());
} /** * Throw a {@link ConfigDataNotFoundException} if the specified {@link Resource} does * not exist. * @param resource the config data resource * @param resourceToCheck the resource to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, Resource resourceToCheck) { throwIfNot(resource, resourceToCheck.exists()); } private static void throwIfNot(ConfigDataResource resource, boolean check) { if (!check) { throw new ConfigDataResourceNotFoundException(resource); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataResourceNotFoundException.java
2
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } public int getAD_Reference_ID() { return adReferenceId; } public String getName() { return name; } public List<ListItemInfo> getItems() { return items; } public static class Builder { private Integer adReferenceId; private String name; private ImmutableList.Builder<ListItemInfo> items = ImmutableList.builder(); private Builder() { super(); } public ListInfo build() {
return new ListInfo(this); } public Builder setAD_Reference_ID(final int adReferenceId) { this.adReferenceId = adReferenceId; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder addItem(final String value, final String name, final String valueName) { final ListItemInfo item = new ListItemInfo(value, name, valueName); items.add(item); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\ListInfo.java
1
请完成以下Java代码
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 static PaymentRule ofCode(@NonNull final String code) { final PaymentRule type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + PaymentRule.class + " found for code: " + code); } return type; } @Nullable public static String toCodeOrNull(@Nullable final PaymentRule type) { return type != null ? type.getCode() : null; } private static final ImmutableMap<String, PaymentRule> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), PaymentRule::getCode); public boolean isCashOrCheck() { return isCash() || isCheck(); } public boolean isCash() {
return this == Cash; } public boolean isCheck() { return this == Check; } public boolean isOnCredit() {return OnCredit.equals(this);} public boolean isPayPal() {return PayPal.equals(this);} public boolean isSettlement() {return Settlement.equals(this);} public boolean isDirectDebit() { return this == DirectDebit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\PaymentRule.java
1
请完成以下Java代码
public static PhoneNumber fromString(@NonNull final String phoneNoAsStr) { final List<String> parts = Splitter.on("-").splitToList(phoneNoAsStr.trim()); if (parts.size() != 3) { throw new IllegalArgumentException("Invalid PhoneNo string: " + phoneNoAsStr); } String countryCode = parts.get(0); if (countryCode.startsWith("+")) { countryCode = countryCode.substring(1); } String areaCode = parts.get(1); String phoneNumber = parts.get(2); return builder() .countryCode(countryCode) .areaCode(areaCode) .phoneNumber(phoneNumber) .build(); } @NonNull String countryCode; @NonNull String areaCode; @NonNull String phoneNumber; @Builder private PhoneNumber( final String countryCode, final String areaCode, final String phoneNumber)
{ Check.assumeNotEmpty(countryCode, "countryCode is not empty"); Check.assumeNotEmpty(areaCode, "areaCode is not empty"); Check.assumeNotEmpty(phoneNumber, "phoneNumber is not empty"); this.countryCode = countryCode.trim(); this.areaCode = areaCode.trim(); this.phoneNumber = phoneNumber.trim(); } @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() { return "+" + countryCode + "-" + areaCode + "-" + phoneNumber; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\model\PhoneNumber.java
1
请完成以下Java代码
public class ProcessCandidateStarterGroupImpl extends ProcessCandidateStarterImpl implements ProcessCandidateStarterGroup { private String groupId; public ProcessCandidateStarterGroupImpl() {} public ProcessCandidateStarterGroupImpl(String processDefinitionId, String groupId) { super(processDefinitionId); this.groupId = groupId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProcessCandidateStarterGroupImpl that = (ProcessCandidateStarterGroupImpl) o;
return ( Objects.equals(groupId, that.groupId) && Objects.equals(getProcessDefinitionId(), that.getProcessDefinitionId()) ); } @Override public int hashCode() { return Objects.hash(getProcessDefinitionId(), groupId); } @Override public String getGroupId() { return this.groupId; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessCandidateStarterGroupImpl.java
1
请完成以下Java代码
public class PmsCommentReplay implements Serializable { private Long id; private Long commentId; private String memberNickName; private String memberIcon; private String content; private Date createTime; @ApiModelProperty(value = "评论人员类型;0->会员;1->管理员") private Integer type; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCommentId() { return commentId; } public void setCommentId(Long commentId) { this.commentId = commentId; } public String getMemberNickName() { return memberNickName; } public void setMemberNickName(String memberNickName) { this.memberNickName = memberNickName; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public String getContent() {
return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", commentId=").append(commentId); sb.append(", memberNickName=").append(memberNickName); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsCommentReplay.java
1
请完成以下Java代码
public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_ProductBOM() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_ProductBOM_ID(), get_TrxName()); } /** Set BOM Product. @param M_ProductBOM_ID Bill of Material Component Product */ public void setM_ProductBOM_ID (int M_ProductBOM_ID) { if (M_ProductBOM_ID < 1) set_Value (COLUMNNAME_M_ProductBOM_ID, null); else set_Value (COLUMNNAME_M_ProductBOM_ID, Integer.valueOf(M_ProductBOM_ID)); } /** Get BOM Product. @return Bill of Material Component Product */ public int getM_ProductBOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_ProductOperation getM_ProductOperation() throws RuntimeException { return (I_M_ProductOperation)MTable.get(getCtx(), I_M_ProductOperation.Table_Name) .getPO(getM_ProductOperation_ID(), get_TrxName()); } /** Set Product Operation. @param M_ProductOperation_ID Product Manufacturing Operation */ public void setM_ProductOperation_ID (int M_ProductOperation_ID) { if (M_ProductOperation_ID < 1) set_Value (COLUMNNAME_M_ProductOperation_ID, null); else
set_Value (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID)); } /** Get Product Operation. @return Product Manufacturing Operation */ public int getM_ProductOperation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMProduct.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getTerminatePlanItemDefinitionIds() { return terminatePlanItemDefinitionIds; } @ApiModelProperty(value = "plan item definition ids to be terminated") public void setTerminatePlanItemDefinitionIds(List<String> terminatePlanItemDefinitionIds) { this.terminatePlanItemDefinitionIds = terminatePlanItemDefinitionIds; } public List<String> getAddWaitingForRepetitionPlanItemDefinitionIds() { return addWaitingForRepetitionPlanItemDefinitionIds; } @ApiModelProperty(value = "add waiting for repetition to provided plan item definition ids") public void setAddWaitingForRepetitionPlanItemDefinitionIds(List<String> addWaitingForRepetitionPlanItemDefinitionIds) { this.addWaitingForRepetitionPlanItemDefinitionIds = addWaitingForRepetitionPlanItemDefinitionIds; } public List<String> getRemoveWaitingForRepetitionPlanItemDefinitionIds() { return removeWaitingForRepetitionPlanItemDefinitionIds; } @ApiModelProperty(value = "remove waiting for repetition to provided plan item definition ids") public void setRemoveWaitingForRepetitionPlanItemDefinitionIds(List<String> removeWaitingForRepetitionPlanItemDefinitionIds) { this.removeWaitingForRepetitionPlanItemDefinitionIds = removeWaitingForRepetitionPlanItemDefinitionIds; } public Map<String, String> getChangePlanItemIds() { return changePlanItemIds; } @ApiModelProperty(value = "map an existing plan item id to new plan item id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemIds(Map<String, String> changePlanItemIds) { this.changePlanItemIds = changePlanItemIds; }
public Map<String, String> getChangePlanItemIdsWithDefinitionId() { return changePlanItemIdsWithDefinitionId; } @ApiModelProperty(value = "map an existing plan item id to new plan item id with the plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemIdsWithDefinitionId(Map<String, String> changePlanItemIdsWithDefinitionId) { this.changePlanItemIdsWithDefinitionId = changePlanItemIdsWithDefinitionId; } public List<PlanItemDefinitionWithTargetIdsRequest> getChangePlanItemDefinitionsWithNewTargetIds() { return changePlanItemDefinitionsWithNewTargetIds; } @ApiModelProperty(value = "map an existing plan item id to a new plan item id and plan item definition id, this should not be necessary in general, but could be needed when plan item ids change between case definition versions.") public void setChangePlanItemDefinitionsWithNewTargetIds(List<PlanItemDefinitionWithTargetIdsRequest> changePlanItemDefinitionsWithNewTargetIds) { this.changePlanItemDefinitionsWithNewTargetIds = changePlanItemDefinitionsWithNewTargetIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\ChangePlanItemStateRequest.java
2
请完成以下Java代码
public class CompensateEventDefinitionParseHandler extends AbstractBpmnParseHandler<CompensateEventDefinition> { private static final Logger LOGGER = LoggerFactory.getLogger(CompensateEventDefinitionParseHandler.class); @Override public Class<? extends BaseElement> getHandledType() { return CompensateEventDefinition.class; } @Override protected void executeParse(BpmnParse bpmnParse, CompensateEventDefinition eventDefinition) { ScopeImpl scope = bpmnParse.getCurrentScope(); if (StringUtils.isNotEmpty(eventDefinition.getActivityRef())) { if (scope.findActivity(eventDefinition.getActivityRef()) == null) { LOGGER.warn("Invalid attribute value for 'activityRef': no activity with id '{}' in current scope {}", eventDefinition.getActivityRef(), scope.getId()); } } org.activiti.engine.impl.bpmn.parser.CompensateEventDefinition compensateEventDefinition = new org.activiti.engine.impl.bpmn.parser.CompensateEventDefinition(); compensateEventDefinition.setActivityRef(eventDefinition.getActivityRef()); compensateEventDefinition.setWaitForCompletion(eventDefinition.isWaitForCompletion()); ActivityImpl activity = bpmnParse.getCurrentActivity(); if (bpmnParse.getCurrentFlowElement() instanceof ThrowEvent) { activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateThrowCompensationEventActivityBehavior((ThrowEvent) bpmnParse.getCurrentFlowElement(), compensateEventDefinition)); } else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement(); boolean interrupting = boundaryEvent.isCancelActivity(); activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createBoundaryEventActivityBehavior(boundaryEvent, interrupting, activity)); activity.setProperty("type", "compensationBoundaryCatch"); } else { // What to do? } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\CompensateEventDefinitionParseHandler.java
1
请完成以下Java代码
public GenericEventListenerInstanceQuery elementId(String elementId) { innerQuery.planItemInstanceElementId(elementId); return this; } @Override public GenericEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) { innerQuery.planItemDefinitionId(planItemDefinitionId); return this; } @Override public GenericEventListenerInstanceQuery name(String name) { innerQuery.planItemInstanceName(name); return this; } @Override public GenericEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public GenericEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public GenericEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public GenericEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public GenericEventListenerInstanceQuery asc() { innerQuery.asc(); return this; }
@Override public GenericEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return innerQuery.count(); } @Override public GenericEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return GenericEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<GenericEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<GenericEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<GenericEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(GenericEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public ConfigureAction getConfigureAction() { return this.configureAction; } public void setConfigureAction(ConfigureAction configureAction) { this.configureAction = configureAction; } public RepositoryType getRepositoryType() { return this.repositoryType; } public void setRepositoryType(RepositoryType repositoryType) { this.repositoryType = repositoryType; } /** * Strategies for configuring and validating Redis. */ public enum ConfigureAction { /** * Ensure that Redis Keyspace events for Generic commands and Expired events are * enabled. */ NOTIFY_KEYSPACE_EVENTS, /** * No not attempt to apply any custom Redis configuration. */ NONE
} /** * Type of Redis session repository to auto-configure. */ public enum RepositoryType { /** * Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository. */ DEFAULT, /** * Auto-configure a RedisIndexedSessionRepository or * ReactiveRedisIndexedSessionRepository. */ INDEXED } }
repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java
2