instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class OrderProcessContext <T> implements Serializable { /** 是否终止下面的流程 */ private boolean isStop = false; /** 订单受理请求 */ private OrderProcessReq orderProcessReq; /** 订单受理结果 */ private T orderProcessRsp; public boolean isStop() { return isStop; } public void setStop(boolean stop) { isStop = stop; } public OrderProcessReq getOrderProcessReq() { return orderProcessReq; } public void setOrderProcessReq(OrderProcessReq orderProcessReq) { this.orderProcessReq = orderProcessReq; } public T getOrderProcessRsp() { return orderProcessRsp;
} public void setOrderProcessRsp(T orderProcessRsp) { this.orderProcessRsp = orderProcessRsp; } @Override public String toString() { return "OrderProcessContext{" + "isStop=" + isStop + ", orderProcessReq=" + orderProcessReq + ", orderProcessRsp=" + orderProcessRsp + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\context\OrderProcessContext.java
2
请在Spring Boot框架中完成以下Java代码
public class User { private Long id; private String userName; private String firstName; private String lastName; private String email; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) {
this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\repositoryvsdaopattern\User.java
2
请完成以下Java代码
public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; }
@Override public String getDerivedFrom() { return null; } @Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @ApiModelProperty(example = "2023-06-04T22:05:05.474+0000") public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner;
} @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobResponse.java
2
请完成以下Java代码
public void setM_QualityInsp_LagerKonf_ProcessingFee_ID (int M_QualityInsp_LagerKonf_ProcessingFee_ID) { if (M_QualityInsp_LagerKonf_ProcessingFee_ID < 1) set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ProcessingFee_ID, null); else set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_ProcessingFee_ID, Integer.valueOf(M_QualityInsp_LagerKonf_ProcessingFee_ID)); } /** Get Verarbeitungskosten (Sortierkosten). @return Verarbeitungskosten (Sortierkosten) */ @Override public int getM_QualityInsp_LagerKonf_ProcessingFee_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_ProcessingFee_ID); if (ii == null) return 0; return ii.intValue(); } @Override public I_M_QualityInsp_LagerKonf_Version getM_QualityInsp_LagerKonf_Version() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class); } @Override public void setM_QualityInsp_LagerKonf_Version(I_M_QualityInsp_LagerKonf_Version M_QualityInsp_LagerKonf_Version) { set_ValueFromPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class, M_QualityInsp_LagerKonf_Version); } /** Set Lagerkonferenz-Version. @param M_QualityInsp_LagerKonf_Version_ID Lagerkonferenz-Version */ @Override public void setM_QualityInsp_LagerKonf_Version_ID (int M_QualityInsp_LagerKonf_Version_ID) { if (M_QualityInsp_LagerKonf_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, Integer.valueOf(M_QualityInsp_LagerKonf_Version_ID)); } /** Get Lagerkonferenz-Version. @return Lagerkonferenz-Version */ @Override public int getM_QualityInsp_LagerKonf_Version_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID); if (ii == null) return 0; return ii.intValue(); } /** Set % ab. @param PercentFrom % ab */ @Override public void setPercentFrom (java.math.BigDecimal PercentFrom)
{ set_Value (COLUMNNAME_PercentFrom, PercentFrom); } /** Get % ab. @return % ab */ @Override public java.math.BigDecimal getPercentFrom () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PercentFrom); if (bd == null) return Env.ZERO; return bd; } /** Set Betrag pro Einheit. @param Processing_Fee_Amt_Per_UOM Betrag pro Einheit */ @Override public void setProcessing_Fee_Amt_Per_UOM (java.math.BigDecimal Processing_Fee_Amt_Per_UOM) { set_Value (COLUMNNAME_Processing_Fee_Amt_Per_UOM, Processing_Fee_Amt_Per_UOM); } /** Get Betrag pro Einheit. @return Betrag pro Einheit */ @Override public java.math.BigDecimal getProcessing_Fee_Amt_Per_UOM () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Processing_Fee_Amt_Per_UOM); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_ProcessingFee.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemShopware6ConfigMapping { @NonNull Integer seqNo; @Nullable DocTypeId docTypeOrderId; @Nullable String paymentRule; @NonNull String bpartnerIfExists; @NonNull String bpartnerIfNotExists; @NonNull String bpartnerLocationIfExists; @NonNull String bpartnerLocationIfNotExists; @Nullable Boolean isInvoiceEmailEnabled; @Nullable PaymentTermId paymentTermId; @Nullable String sw6CustomerGroup; @Nullable String sw6PaymentMethod; @Nullable String description; @Builder public ExternalSystemShopware6ConfigMapping( @NonNull final Integer seqNo,
final int docTypeOrderId, @Nullable final String paymentRule, final int paymentTermId, @NonNull final String bpartnerIfExists, @NonNull final String bpartnerIfNotExists, @NonNull final String bpartnerLocationIfExists, @NonNull final String bpartnerLocationIfNotExists, @Nullable final Boolean isInvoiceEmailEnabled, @Nullable final String sw6CustomerGroup, @Nullable final String sw6PaymentMethod, @Nullable final String description) { this.seqNo = seqNo; this.docTypeOrderId = DocTypeId.ofRepoIdOrNull(docTypeOrderId); this.paymentRule = paymentRule; this.paymentTermId = PaymentTermId.ofRepoIdOrNull(paymentTermId); this.sw6CustomerGroup = sw6CustomerGroup; this.sw6PaymentMethod = sw6PaymentMethod; this.description = description; this.bpartnerIfExists = bpartnerIfExists; this.bpartnerIfNotExists = bpartnerIfNotExists; this.bpartnerLocationIfExists = bpartnerLocationIfExists; this.bpartnerLocationIfNotExists = bpartnerLocationIfNotExists; this.isInvoiceEmailEnabled = isInvoiceEmailEnabled; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\shopware6\ExternalSystemShopware6ConfigMapping.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringBootAdminEurekaApplication { private final AdminServerProperties adminServer; public SpringBootAdminEurekaApplication(AdminServerProperties adminServer) { this.adminServer = adminServer; } public static void main(String[] args) { SpringApplication.run(SpringBootAdminEurekaApplication.class, args); } @Bean @Profile("insecure") public SecurityWebFilterChain securityWebFilterChainPermitAll(ServerHttpSecurity http) { return http.authorizeExchange((authorizeExchange) -> authorizeExchange.anyExchange().permitAll()) .csrf(ServerHttpSecurity.CsrfSpec::disable) .build(); } @Bean @Profile("secure") public SecurityWebFilterChain securityWebFilterChainSecure(ServerHttpSecurity http) { return http .authorizeExchange( (authorizeExchange) -> authorizeExchange.pathMatchers(this.adminServer.path("/assets/**")) .permitAll() .pathMatchers("/actuator/health/**") .permitAll() .pathMatchers(this.adminServer.path("/login")) .permitAll() .anyExchange() .authenticated()) .formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login")) .authenticationSuccessHandler(loginSuccessHandler(this.adminServer.path("/")))) .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout")) .logoutSuccessHandler(logoutSuccessHandler(this.adminServer.path("/login?logout"))))
.httpBasic(Customizer.withDefaults()) .csrf(ServerHttpSecurity.CsrfSpec::disable) .build(); } // The following two methods are only required when setting a custom base-path (see // 'basepath' profile in application.yml) private ServerLogoutSuccessHandler logoutSuccessHandler(String uri) { RedirectServerLogoutSuccessHandler successHandler = new RedirectServerLogoutSuccessHandler(); successHandler.setLogoutSuccessUrl(URI.create(uri)); return successHandler; } private ServerAuthenticationSuccessHandler loginSuccessHandler(String uri) { RedirectServerAuthenticationSuccessHandler successHandler = new RedirectServerAuthenticationSuccessHandler(); successHandler.setLocation(URI.create(uri)); return successHandler; } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\java\de\codecentric\boot\admin\SpringBootAdminEurekaApplication.java
2
请完成以下Java代码
private Chain createExecuteChain(SyncGraphQlTransport transport) { Encoder<?> encoder = HttpMessageConverterDelegate.asEncoder(getJsonConverter()); Decoder<?> decoder = HttpMessageConverterDelegate.asDecoder(getJsonConverter()); Chain chain = (request) -> { GraphQlResponse response = transport.execute(request); return new DefaultClientGraphQlResponse(request, response, encoder, decoder); }; return this.interceptors.stream() .reduce(SyncGraphQlClientInterceptor::andThen) .map((i) -> (Chain) (request) -> i.intercept(request, chain)) .orElse(chain); } private HttpMessageConverter<Object> getJsonConverter() { Assert.notNull(this.jsonConverter, "jsonConverter has not been set"); return this.jsonConverter; }
private static final class DefaultJacksonConverter { static HttpMessageConverter<Object> initialize() { JsonMapper jsonMapper = JsonMapper.builder().addModule(new GraphQlJacksonModule()).build(); return new JacksonJsonHttpMessageConverter(jsonMapper); } } @SuppressWarnings("removal") private static final class DefaultJackson2Converter { static HttpMessageConverter<Object> initialize() { com.fasterxml.jackson.databind.ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json() .modulesToInstall(new GraphQlJackson2Module()).build(); return new MappingJackson2HttpMessageConverter(objectMapper); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientSyncBuilder.java
1
请完成以下Java代码
private static JsonLine buildNShiftLine(@NonNull final JsonDeliveryAdvisorRequestItem item) { // nShift expects weight in grams and dimensions in millimeters. final int weightGrams = item.getGrossWeightKg().multiply(BigDecimal.valueOf(1000)).intValue(); final JsonLine.JsonLineBuilder lineBuilder = JsonLine.builder() .lineWeight(weightGrams); if (item.getPackageDimensions() != null) { final int lengthMM = item.getPackageDimensions().getLengthInCM() * 10; final int widthMM = item.getPackageDimensions().getWidthInCM() * 10; final int heightMM = item.getPackageDimensions().getHeightInCM() * 10; lineBuilder.number(1); // on advice, it's always 1, as we combine the dimensions via @link de.metas.product.PackageDimensions.ofProductDimensionsAndQty() lineBuilder.length(lengthMM); lineBuilder.width(widthMM); lineBuilder.height(heightMM); } return lineBuilder.build(); } private static JsonDeliveryAdvisorResponse buildJsonDeliveryAdvisorResponse(@NonNull final JsonShipAdvisorResponse response, @NonNull final String requestId) { Check.assumeEquals(response.getProducts().size(), 1, "response should only contain 1 shipperProduct, pls check defined shipment rules"); final JsonShipAdvisorResponseProduct product = response.getProducts().get(0); final JsonDeliveryAdvisorResponse.JsonDeliveryAdvisorResponseBuilder responseBuilder = JsonDeliveryAdvisorResponse.builder() .requestId(requestId) .shipperProduct(JsonShipperProduct.builder() .name(product.getProdName())
.code(String.valueOf(product.getProdConceptID())) .build()); final JsonShipAdvisorResponseGoodsType productGoodsType = Check.assumeNotNull(product.getProductGoodsType(), "response should contain a GoodsType, pls check defined shipment rules"); responseBuilder.goodsType(JsonGoodsType.builder() .id(String.valueOf(productGoodsType.getGoodsTypeId())) .name(productGoodsType.getGoodsTypeName()) .build()); responseBuilder.shipperProductServices(product.getServices() .stream() .map(NShiftShipAdvisorService::toJsonCarrierService) .collect(ImmutableList.toImmutableList()) ); return responseBuilder.build(); } private static JsonCarrierService toJsonCarrierService(@NonNull final JsonShipAdvisorResponseService jsonShipAdvisorResponseService) { return JsonCarrierService.builder() .name(jsonShipAdvisorResponseService.getName()) .id(String.valueOf(jsonShipAdvisorResponseService.getServiceId())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftShipAdvisorService.java
1
请完成以下Java代码
protected final void recalculateWeightGross(final IAttributeSet attributeSet) { // final IAttributeStorage attributeStorage = (IAttributeStorage)attributeSet; final IWeightable weightable = getWeightableOrNull(attributeSet); // NOTE: we calculate WeightGross, no matter if our HU is allowed to be weighted by user // final boolean weightUOMFriendly = weightable.isWeightable(); final BigDecimal weightTareTotal = weightable.getWeightTareTotal(); final BigDecimal weightNet = weightable.getWeightNet(); final BigDecimal weightGross = weightNet.add(weightTareTotal); weightable.setWeightGross(weightGross); } protected final void recalculateWeightNet(final IAttributeSet attributeSet) { final IWeightable weightable = getWeightableOrNull(attributeSet); Weightables.updateWeightNet(weightable); } protected boolean isLUorTUorTopLevelVHU(IAttributeSet attributeSet) { if (!isVirtualHU(attributeSet)) { return true;
} final I_M_HU hu = huAttributesBL.getM_HU_OrNull(attributeSet); final boolean virtualTopLevelHU = handlingUnitsBL.isTopLevel(hu); return virtualTopLevelHU; } @Override public final String generateStringValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { throw new UnsupportedOperationException("Not supported"); } @Override public final Date generateDateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute) { throw new UnsupportedOperationException("Not supported"); } @Override public final AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName) { throw new UnsupportedOperationException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\AbstractWeightAttributeValueCallout.java
1
请完成以下Java代码
public class ReverseStringExamples { public static String reverse(String input) { if (input == null) { return null; } String output = ""; for (int i = input.length() - 1; i >= 0; i--) { output = output + input.charAt(i); } return output; } public static String reverseUsingStringBuilder(String input) { if (input == null) { return null; } StringBuilder output = new StringBuilder(input).reverse(); return output.toString(); } public static String reverseUsingApacheCommons(String input) { return StringUtils.reverse(input); } public static String reverseTheOrderOfWords(String sentence) { if (sentence == null) { return null; } StringBuilder output = new StringBuilder(); String[] words = sentence.split(" "); for (int i = words.length - 1; i >= 0; i--) { output.append(words[i]); output.append(" "); } return output.toString() .trim(); } public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) { return StringUtils.reverseDelimited(sentence, ' '); } public static String reverseUsingIntStreamRangeMethod(String str) { if (str == null) { return null; } char[] charArray = str.toCharArray();
return IntStream.range(0, str.length()) .mapToObj(i -> charArray[str.length() - i - 1]) .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append) .toString(); } public static String reverseUsingStreamOfMethod(String str) { if (str == null) { return null; } return Stream.of(str) .map(string -> new StringBuilder(string).reverse()) .collect(Collectors.joining()); } public static String reverseUsingCharsMethod(String str) { if (str == null) { return null; } return str.chars() .mapToObj(c -> (char) c) .reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms\src\main\java\com\baeldung\reverse\ReverseStringExamples.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final MutableAllocationResult other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(qtyToAllocate, other.qtyToAllocate) .append(transactions, other.transactions) .append(attributeTransactions, other.attributeTransactions) .isEqual(); } @Override public boolean isCompleted() { return qtyToAllocate.signum() == 0; } @Override public void subtractAllocatedQty(@NonNull final BigDecimal qtyAllocated) { final BigDecimal qtyToAllocateNew = qtyToAllocate.subtract(qtyAllocated); Check.assume(qtyToAllocateNew.signum() >= 0, "Cannot allocate {} when qtyToAllocate is {}", qtyAllocated, qtyToAllocate); qtyToAllocate = qtyToAllocateNew; } @Override public BigDecimal getQtyToAllocate() { return qtyToAllocate; } @Override public BigDecimal getQtyAllocated() { return qtyToAllocateInitial.subtract(qtyToAllocate); } @Override public void addTransaction(final IHUTransactionCandidate trx) { transactions.add(trx); } @Override public void addTransactions(final List<IHUTransactionCandidate> trxs) { trxs.forEach(trx -> addTransaction(trx)); } @Override public List<IHUTransactionCandidate> getTransactions() { return transactionsRO; }
@Override public void addAttributeTransaction(final IHUTransactionAttribute attributeTrx) { attributeTransactions.add(attributeTrx); } @Override public void addAttributeTransactions(final List<IHUTransactionAttribute> attributeTrxs) { attributeTransactions.addAll(attributeTrxs); } @Override public List<IHUTransactionAttribute> getAttributeTransactions() { return attributeTransactionsRO; } @Override public void aggregateTransactions() { final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); final List<IHUTransactionCandidate> aggregateTransactions = huTrxBL.aggregateTransactions(transactions); transactions.clear(); transactions.addAll(aggregateTransactions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\MutableAllocationResult.java
1
请完成以下Java代码
public class SubscriptionLoggerUtil extends LoggerUtil { public void handlerBeansFound(Class<ExternalTaskHandler> externalTaskHandlerClass, String[] beanNamesForType) { logDebug("001", "Handler beans found for {}: {}", externalTaskHandlerClass, beanNamesForType); } public void beanRegistered(String subscriptionBeanName, String handlerBeanName) { logDebug("002", "Subscription bean '{}' registered for handler bean '{}'", subscriptionBeanName, handlerBeanName); } public void notFound(BeanDefinition beanDefinition) { logInfo("003", "Subscription not found for handler bean {}", beanDefinition); } public void found(ExternalTaskSubscription annotation, BeanDefinition beanDefinition) { logDebug("004", "Subscription found {} for handler bean {}", annotation, beanDefinition); } public void initialized(String topicName) {
logDebug("005", "Subscription for topic name {} initialized", topicName); } public void opened(String topicName) { logDebug("006", "Subscription for topic name {} opened", topicName); } public void closed(String topicName) { logDebug("007", "Subscription for topic name {} closed", topicName); } public NotInitializedException notInitializedException(String topicName) { return new NotInitializedException(exceptionMessage( "008", "Subscription with topic name '{}' has yet not been initialized", topicName)); } public NotOpenedException notOpenedException(String topicName) { return new NotOpenedException(exceptionMessage( "009", "Subscription with topic name '{}' has yet not been opened", topicName)); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\util\SubscriptionLoggerUtil.java
1
请完成以下Java代码
public int getCopies() { return copies; } public void setCopies(final int copies) { this.copies = copies; } @Override public String toString() { return String.format("PrintPackage [transactionId=%s, printPackageId=%s, pageCount=%s, copies=%s, format=%s, printPackageInfos=%s, printJobInstructionsID=%s]", transactionId, printPackageId, pageCount, copies, format, printPackageInfos, printJobInstructionsID); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + copies; result = prime * result + ((format == null) ? 0 : format.hashCode()); result = prime * result + pageCount; result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode()); result = prime * result + ((printPackageId == null) ? 0 : printPackageId.hashCode()); result = prime * result + ((printPackageInfos == null) ? 0 : printPackageInfos.hashCode()); result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackage other = (PrintPackage)obj; if (copies != other.copies) return false; if (format == null) { if (other.format != null) return false; } else if (!format.equals(other.format)) return false; if (pageCount != other.pageCount) return false; if (printJobInstructionsID == null) { if (other.printJobInstructionsID != null) return false;
} else if (!printJobInstructionsID.equals(other.printJobInstructionsID)) return false; if (printPackageId == null) { if (other.printPackageId != null) return false; } else if (!printPackageId.equals(other.printPackageId)) return false; if (printPackageInfos == null) { if (other.printPackageInfos != null) return false; } else if (!printPackageInfos.equals(other.printPackageInfos)) return false; if (transactionId == null) { if (other.transactionId != null) return false; } else if (!transactionId.equals(other.transactionId)) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java
1
请完成以下Java代码
public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID); } @Override public int getReversalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public void setUPC (final @Nullable java.lang.String UPC) { throw new IllegalArgumentException ("UPC is virtual column"); }
@Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValue (final @Nullable java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLine.java
1
请完成以下Java代码
public @Nullable PostInvocationAttribute createPostInvocationAttribute(String postFilterAttribute, String postAuthorizeAttribute) { try { ExpressionParser parser = getParser(); Expression postAuthorizeExpression = (postAuthorizeAttribute != null) ? parser.parseExpression(postAuthorizeAttribute) : null; Expression postFilterExpression = (postFilterAttribute != null) ? parser.parseExpression(postFilterAttribute) : null; if (postFilterExpression != null || postAuthorizeExpression != null) { return new PostInvocationExpressionAttribute(postFilterExpression, postAuthorizeExpression); } } catch (ParseException ex) { throw new IllegalArgumentException("Failed to parse expression '" + ex.getExpressionString() + "'", ex); } return null; }
/** * Delay the lookup of the {@link ExpressionParser} to prevent SEC-2136 * @return */ private ExpressionParser getParser() { if (this.parser != null) { return this.parser; } synchronized (this.parserLock) { this.parser = this.handler.getExpressionParser(); this.handler = null; } return this.parser; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\expression\method\ExpressionBasedAnnotationAttributeFactory.java
1
请在Spring Boot框架中完成以下Java代码
private static final class Saml2MetadataResponseResolverAdapter implements Saml2MetadataResponseResolver { private final RelyingPartyRegistrationResolver registrations; private RequestMatcher requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher("/saml2/service-provider-metadata/{registrationId}"); private final Saml2MetadataResolver metadataResolver; private String metadataFilename = DEFAULT_METADATA_FILE_NAME; Saml2MetadataResponseResolverAdapter(RelyingPartyRegistrationResolver registrations, Saml2MetadataResolver metadataResolver) { this.registrations = registrations; this.metadataResolver = metadataResolver; } @Override public Saml2MetadataResponse resolve(HttpServletRequest request) { RequestMatcher.MatchResult matcher = this.requestMatcher.matcher(request); if (!matcher.isMatch()) { return null; } String registrationId = matcher.getVariables().get("registrationId"); RelyingPartyRegistration relyingPartyRegistration = this.registrations.resolve(request, registrationId); if (relyingPartyRegistration == null) {
throw new Saml2Exception("registration not found"); } registrationId = relyingPartyRegistration.getRegistrationId(); String metadata = this.metadataResolver.resolve(relyingPartyRegistration); String fileName = this.metadataFilename.replace("{registrationId}", registrationId); return new Saml2MetadataResponse(metadata, fileName); } void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } void setMetadataFilename(String metadataFilename) { Assert.hasText(metadataFilename, "metadataFilename cannot be empty"); Assert.isTrue(metadataFilename.contains("{registrationId}"), "metadataFilename must contain a {registrationId} match variable"); this.metadataFilename = metadataFilename; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2MetadataFilter.java
2
请完成以下Java代码
public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setMovementDate (final java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPosted (final boolean Posted) { set_Value (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); }
@Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine() { return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class); } @Override public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine) { set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine); } @Override public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID) { if (S_TimeExpenseLine_ID < 1) set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null); else set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID); } @Override public int getS_TimeExpenseLine_ID() { return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
1
请完成以下Spring Boot application配置
events: queues: order-processing-retry-queue: order_processing_retry_queue order-processing-async-queue: order_processing_async_queue order-processing-no-retries-queue: order_processing_no_retries_queue acknowledgment: order-processing-no-retries-queue: ALWAYS product: id: smartphone: 123e4567-
e89b-12d3-a456-426614174000 wireless-headphones: 123e4567-e89b-12d3-a456-426614174001 laptop: 123e4567-e89b-12d3-a456-426614174002
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\resources\application-acknowledgement.yaml
2
请完成以下Java代码
public Object getValue() { return this.value; } @Override public @Nullable Origin getOrigin() { return this.origin; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ConfigurationProperty other = (ConfigurationProperty) obj; boolean result = true; result = result && ObjectUtils.nullSafeEquals(this.name, other.name); result = result && ObjectUtils.nullSafeEquals(this.value, other.value); return result; } @Override public int hashCode() { int result = ObjectUtils.nullSafeHashCode(this.name); result = 31 * result + ObjectUtils.nullSafeHashCode(this.value); return result; } @Override public String toString() { return new ToStringCreator(this).append("name", this.name) .append("value", this.value)
.append("origin", this.origin) .toString(); } @Override public int compareTo(ConfigurationProperty other) { return this.name.compareTo(other.name); } @Contract("_, !null -> !null") static @Nullable ConfigurationProperty of(ConfigurationPropertyName name, @Nullable OriginTrackedValue value) { if (value == null) { return null; } return new ConfigurationProperty(name, value.getValue(), value.getOrigin()); } @Contract("_, _, !null, _ -> !null") static @Nullable ConfigurationProperty of(@Nullable ConfigurationPropertySource source, ConfigurationPropertyName name, @Nullable Object value, @Nullable Origin origin) { if (value == null) { return null; } return new ConfigurationProperty(source, name, value, origin); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationProperty.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_M_FreightCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Freight Category. @param M_FreightCategory_ID Category of the Freight */ public void setM_FreightCategory_ID (int M_FreightCategory_ID) { if (M_FreightCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, Integer.valueOf(M_FreightCategory_ID)); } /** Get Freight Category. @return Category of the Freight */ public int getM_FreightCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCategory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_FreightCategory.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) { int count = orderService.updateReceiverInfo(receiverInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改订单费用信息") @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) { int count = orderService.updateMoneyInfo(moneyInfoParam); if (count > 0) { return CommonResult.success(count); }
return CommonResult.failed(); } @ApiOperation("备注订单") @RequestMapping(value = "/update/note", method = RequestMethod.POST) @ResponseBody public CommonResult updateNote(@RequestParam("id") Long id, @RequestParam("note") String note, @RequestParam("status") Integer status) { int count = orderService.updateNote(id, note, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderController.java
2
请完成以下Java代码
protected ExpressionFactory createExpressionFactory() { Properties properties = new Properties(); properties.put(ExpressionFactoryImpl.PROP_CACHE_SIZE, String.valueOf(expressionCacheSize)); try { return new ExpressionFactoryImpl(properties, createTypeConverter()); } catch (ELException e) { throw LOG.unableToInitializeFeelEngine(e); } } protected FeelTypeConverter createTypeConverter() { return new FeelTypeConverter(); }
protected ElContextFactory createElContextFactory() { FeelElContextFactory factory = new FeelElContextFactory(); for (FeelToJuelFunctionTransformer functionTransformer : customFunctionTransformers) { factory.addCustomFunction(functionTransformer.getName(), functionTransformer.getMethod()); } return factory; } protected Cache<TransformExpressionCacheKey, String> createTransformExpressionCache() { return new ConcurrentLruCache<TransformExpressionCacheKey, String>(expressionCacheSize); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\FeelEngineFactoryImpl.java
1
请完成以下Java代码
public static JsonKPIDataResult of( @NonNull final UserDashboardItemDataResponse itemData, @NonNull final KPIJsonOptions jsonOpts) { if (itemData.getKpiData() != null) { final KPIDataResult kpiData = itemData.getKpiData(); return of(kpiData, jsonOpts) .withItemId(itemData.getItemId().getRepoId()); } else { final WebuiError error = itemData.getError(); assert error != null; return builder() .itemId(itemData.getItemId().getRepoId()) .error(JsonWebuiError.of(error, jsonOpts)) .build(); } } public static JsonKPIDataResult of(
@NonNull final KPIDataResult kpiData, @NonNull final KPIJsonOptions jsonOpts) { return builder() .range(kpiData.getRange()) .datasets(kpiData.getDatasets() .stream() .map(dataSet -> JsonKPIDataSet.of(dataSet, jsonOpts)) .collect(ImmutableList.toImmutableList())) .took(kpiData.getDatasetsComputedTime().toString()) .computedTimestamp(DateTimeConverters.toJson(kpiData.getDatasetsComputedTime(), jsonOpts.getZoneId())) .error(kpiData.getError() != null ? JsonWebuiError.of(kpiData.getError(), jsonOpts) : null) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonKPIDataResult.java
1
请完成以下Java代码
public ProcessDefinition findProcessDefinitionByKeyAndVersionAndTenantId( String processDefinitionKey, Integer processDefinitionVersion, String tenantId ) { if (tenantId == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return processDefinitionDataManager.findProcessDefinitionByKeyAndVersion( processDefinitionKey, processDefinitionVersion ); } else { return processDefinitionDataManager.findProcessDefinitionByKeyAndVersionAndTenantId( processDefinitionKey, processDefinitionVersion, tenantId ); } } @Override public List<ProcessDefinition> findProcessDefinitionsByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return processDefinitionDataManager.findProcessDefinitionsByNativeQuery(parameterMap, firstResult, maxResults); } @Override public long findProcessDefinitionCountByNativeQuery(Map<String, Object> parameterMap) {
return processDefinitionDataManager.findProcessDefinitionCountByNativeQuery(parameterMap); } @Override public void updateProcessDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { processDefinitionDataManager.updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId); } public ProcessDefinitionDataManager getProcessDefinitionDataManager() { return processDefinitionDataManager; } public void setProcessDefinitionDataManager(ProcessDefinitionDataManager processDefinitionDataManager) { this.processDefinitionDataManager = processDefinitionDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityManagerImpl.java
1
请完成以下Java代码
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Root Entry. @param Root_ID Root Entry */ @Override public void setRoot_ID (int Root_ID) { if (Root_ID < 1) set_Value (COLUMNNAME_Root_ID, null); else set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID)); } /** Get Root Entry. @return Root Entry */ @Override public int getRoot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */
@Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java
1
请完成以下Java代码
public User password(String password) { this.password = password; return this; } /** * Get password * @return password **/ @ApiModelProperty(value = "") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User phone(String phone) { this.phone = phone; return this; } /** * Get phone * @return phone **/ @ApiModelProperty(value = "") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } /** * User Status * @return userStatus **/ @ApiModelProperty(value = "User Status") public Integer getUserStatus() { return userStatus; } public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {
return false; } User user = (User) o; return Objects.equals(this.id, user.id) && Objects.equals(this.username, user.username) && Objects.equals(this.firstName, user.firstName) && Objects.equals(this.lastName, user.lastName) && Objects.equals(this.email, user.email) && Objects.equals(this.password, user.password) && Objects.equals(this.phone, user.phone) && Objects.equals(this.userStatus, user.userStatus); } @Override public int hashCode() { return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\User.java
1
请完成以下Java代码
public int size() { return storage.size(); } /** * 模型中的词向量维度 * * @return */ public int dimension() { if (storage == null || storage.isEmpty()) { return 0;
} return storage.values().iterator().next().size(); } /** * 删除元素 * * @param key * @return */ public Vector remove(K key) { return storage.remove(key); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractVectorModel.java
1
请完成以下Java代码
public void initHUStorages(final I_M_HU hu) { // nothing } @Override public void initHUItemStorages(final I_M_HU_Item item) { // nothing } @Override public I_M_HU_Storage retrieveStorage(final I_M_HU hu, @NonNull final ProductId productId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Storage.class, hu) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_HU_ID, hu.getM_HU_ID()) .addEqualsFilter(I_M_HU_Storage.COLUMNNAME_M_Product_ID, productId) .create() .firstOnly(I_M_HU_Storage.class); } @Override public void save(final I_M_HU_Storage storage) { InterfaceWrapperHelper.save(storage); } @Override public List<I_M_HU_Storage> retrieveStorages(final I_M_HU hu) { final List<I_M_HU_Storage> huStorages = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Storage.class, hu) .filter(new EqualsQueryFilter<I_M_HU_Storage>(I_M_HU_Storage.COLUMNNAME_M_HU_ID, hu.getM_HU_ID())) .create() .setOnlyActiveRecords(true) .list(I_M_HU_Storage.class); // Optimization: set parent link for (final I_M_HU_Storage huStorage : huStorages) { huStorage.setM_HU(hu); } return huStorages; } @Override public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item huItem, @NonNull final ProductId productId) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Item_Storage.class, huItem) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID())) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_Product_ID, productId)) .create() .setOnlyActiveRecords(true) .firstOnly(I_M_HU_Item_Storage.class); } @Override public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item huItem) {
final IQueryBuilder<I_M_HU_Item_Storage> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item_Storage.class, huItem) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID())); queryBuilder.orderBy() .addColumn(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_Storage_ID); // predictive order final List<I_M_HU_Item_Storage> huItemStorages = queryBuilder .create() .setOnlyActiveRecords(true) .list(I_M_HU_Item_Storage.class); // Optimization: set parent link for (final I_M_HU_Item_Storage huItemStorage : huItemStorages) { huItemStorage.setM_HU_Item(huItem); } return huItemStorages; } @Override public void save(final I_M_HU_Item_Storage storageLine) { InterfaceWrapperHelper.save(storageLine); } @Override public void save(final I_M_HU_Item item) { InterfaceWrapperHelper.save(item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorageDAO.java
1
请完成以下Java代码
public VersionRestService getVersionRestService(@PathParam("name") String engineName) { return super.getVersionRestService(engineName); } @Path("/{name}" + SchemaLogRestService.PATH) public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) { return super.getSchemaLogRestService(engineName); } @Override @Path("/{name}" + EventSubscriptionRestService.PATH) public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) { return super.getEventSubscriptionRestService(engineName); } @Override @Path("/{name}" + TelemetryRestService.PATH) public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) { return super.getTelemetryRestService(engineName); } @GET @Produces(MediaType.APPLICATION_JSON) public List<ProcessEngineDto> getProcessEngineNames() { ProcessEngineProvider provider = getProcessEngineProvider(); Set<String> engineNames = provider.getProcessEngineNames();
List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>(); for (String engineName : engineNames) { ProcessEngineDto dto = new ProcessEngineDto(); dto.setName(engineName); results.add(dto); } return results; } @Override protected URI getRelativeEngineUri(String engineName) { return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java
1
请完成以下Java代码
public final UserSpecificationsBuilder with(final String key, final String operation, final Object value, final String prefix, final String suffix) { return with(null, key, operation, value, prefix, suffix); } public final UserSpecificationsBuilder with(final String orPredicate, final String key, final String operation, final Object value, final String prefix, final String suffix) { SearchOperation op = SearchOperation.getSimpleOperation(operation.charAt(0)); if (op != null) { if (op == SearchOperation.EQUALITY) { // the operation may be complex operation final boolean startWithAsterisk = prefix != null && prefix.contains(SearchOperation.ZERO_OR_MORE_REGEX); final boolean endWithAsterisk = suffix != null && suffix.contains(SearchOperation.ZERO_OR_MORE_REGEX); if (startWithAsterisk && endWithAsterisk) { op = SearchOperation.CONTAINS; } else if (startWithAsterisk) { op = SearchOperation.ENDS_WITH; } else if (endWithAsterisk) { op = SearchOperation.STARTS_WITH; } } params.add(new SpecSearchCriteria(orPredicate, key, op, value)); } return this; } public Specification<User> build() { if (params.size() == 0) return null; Specification<User> result = new UserSpecification(params.get(0));
for (int i = 1; i < params.size(); i++) { result = params.get(i).isOrPredicate() ? Specification.where(result).or(new UserSpecification(params.get(i))) : Specification.where(result).and(new UserSpecification(params.get(i))); } return result; } public final UserSpecificationsBuilder with(UserSpecification spec) { params.add(spec.getCriteria()); return this; } public final UserSpecificationsBuilder with(SpecSearchCriteria criteria) { params.add(criteria); return this; } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\UserSpecificationsBuilder.java
1
请完成以下Java代码
public class VariablesPropagator { private ExecutionEntityManager executionEntityManager; private final VariablesCalculator variablesCalculator; public VariablesPropagator(VariablesCalculator variablesCalculator) { this.variablesCalculator = variablesCalculator; } public void propagate(DelegateExecution execution, Map<String, Object> availableVariables) { if (availableVariables != null && !availableVariables.isEmpty()) { // in the case of a multi instance we need to set the available variables in the local execution scope so that // MultiInstanceBehaviour will manage to aggregate the results inside the result collection. Otherwise, the mapping logic is applied. if (execution.getParent().isMultiInstanceRoot()) { execution.setVariablesLocal(availableVariables); } else if (execution.getProcessInstanceId() != null) { final ExecutionEntity processInstanceEntity = getExecutionEntityManager().findById( execution.getProcessInstanceId() ); processInstanceEntity.setVariables(
variablesCalculator.calculateOutPutVariables( MappingExecutionContext.buildMappingExecutionContext(execution), availableVariables ) ); } } } protected ExecutionEntityManager getExecutionEntityManager() { if (executionEntityManager == null) { executionEntityManager = Context.getCommandContext().getExecutionEntityManager(); } return executionEntityManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\VariablesPropagator.java
1
请在Spring Boot框架中完成以下Java代码
protected DataResponse<ActivityInstanceResponse> getQueryResponse(ActivityInstanceQueryRequest queryRequest, Map<String, String> allRequestParams) { ActivityInstanceQuery query = runtimeService.createActivityInstanceQuery(); // Populate query based on request if (queryRequest.getActivityId() != null) { query.activityId(queryRequest.getActivityId()); } if (queryRequest.getActivityInstanceId() != null) { query.activityInstanceId(queryRequest.getActivityInstanceId()); } if (queryRequest.getActivityName() != null) { query.activityName(queryRequest.getActivityName()); } if (queryRequest.getActivityType() != null) { query.activityType(queryRequest.getActivityType()); } if (queryRequest.getExecutionId() != null) { query.executionId(queryRequest.getExecutionId()); } if (queryRequest.getFinished() != null) { Boolean finished = queryRequest.getFinished(); if (finished) { query.finished(); } else { query.unfinished(); } } if (queryRequest.getTaskAssignee() != null) { query.taskAssignee(queryRequest.getTaskAssignee()); } if (queryRequest.getTaskCompletedBy() != null) { query.taskCompletedBy(queryRequest.getTaskCompletedBy()); } if (queryRequest.getProcessInstanceId() != null) { query.processInstanceId(queryRequest.getProcessInstanceId()); }
if (queryRequest.getProcessInstanceIds() != null && !queryRequest.getProcessInstanceIds().isEmpty()) { query.processInstanceIds(queryRequest.getProcessInstanceIds()); } if (queryRequest.getProcessDefinitionId() != null) { query.processDefinitionId(queryRequest.getProcessDefinitionId()); } if (queryRequest.getTenantId() != null) { query.activityTenantId(queryRequest.getTenantId()); } if (queryRequest.getTenantIdLike() != null) { query.activityTenantIdLike(queryRequest.getTenantIdLike()); } if (Boolean.TRUE.equals(queryRequest.getWithoutTenantId())) { query.activityWithoutTenantId(); } if (restApiInterceptor != null) { restApiInterceptor.accessActivityInfoWithQuery(query, queryRequest); } return paginateList(allRequestParams, queryRequest, query, "startTime", allowedSortProperties, restResponseFactory::createActivityInstanceResponseList); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ActivityInstanceBaseResource.java
2
请完成以下Java代码
public class RepeatingFailedJobListener implements TransactionListener { protected CommandExecutor commandExecutor; protected String jobId; public RepeatingFailedJobListener(CommandExecutor commandExecutor, String jobId) { this.commandExecutor = commandExecutor; this.jobId = jobId; } public void execute(CommandContext commandContext) { CreateNewTimerJobCommand cmd = new CreateNewTimerJobCommand(jobId); commandExecutor.execute(cmd); } protected class CreateNewTimerJobCommand implements Command<Void> { protected String jobId; public CreateNewTimerJobCommand(String jobId) { this.jobId = jobId; } public Void execute(CommandContext commandContext) {
TimerEntity failedJob = (TimerEntity) commandContext .getJobManager() .findJobById(jobId); Date newDueDate = failedJob.calculateNewDueDate(); if (newDueDate != null) { failedJob.createNewTimerJob(newDueDate); // update configuration of failed job TimerJobConfiguration config = (TimerJobConfiguration) failedJob.getJobHandlerConfiguration(); config.setFollowUpJobCreated(true); failedJob.setJobHandlerConfiguration(config); } return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\RepeatingFailedJobListener.java
1
请完成以下Java代码
public int getModifiers() { return this.modifiers; } /** * Return the name. * @return the name */ public String getName() { return this.name; } /** * Return the return type. * @return the return type */ public String getReturnType() { return this.returnType; } /** * Return the value. * @return the value */ public Object getValue() { return this.value; } /** * Return whether this field is initialized. * @return whether the field is initialized. */ public boolean isInitialized() { return this.initialized; } /** * Builder for creating a {@link JavaFieldDeclaration}. */ public static final class Builder { private final String name; private String returnType; private int modifiers; private Object value; private boolean initialized; private Builder(String name) { this.name = name; }
/** * Sets the modifiers. * @param modifiers the modifiers * @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /** * Sets the value. * @param value the value * @return this for method chaining */ public Builder value(Object value) { this.value = value; this.initialized = true; return this; } /** * Sets the return type. * @param returnType the return type * @return this for method chaining */ public JavaFieldDeclaration returning(String returnType) { this.returnType = returnType; return new JavaFieldDeclaration(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaFieldDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public class OLCandId implements RepoIdAware { @JsonCreator public static OLCandId ofRepoId(final int repoId) { return new OLCandId(repoId); } public static OLCandId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new OLCandId(repoId) : null; } public static int toRepoId(@Nullable final OLCandId olCandId) { return olCandId != null ? olCandId.getRepoId() : -1; }
int repoId; private OLCandId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_OLCand_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandId.java
2
请完成以下Java代码
public void setC_Queue_PackageProcessor_ID (int C_Queue_PackageProcessor_ID) { if (C_Queue_PackageProcessor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, Integer.valueOf(C_Queue_PackageProcessor_ID)); } /** Get WorkPackage Processor. @return WorkPackage Processor */ @Override public int getC_Queue_PackageProcessor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_PackageProcessor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Assigned Workpackage Processors. @param C_Queue_Processor_Assign_ID Assigned Workpackage Processors */ @Override public void setC_Queue_Processor_Assign_ID (int C_Queue_Processor_Assign_ID) { if (C_Queue_Processor_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_Processor_Assign_ID, Integer.valueOf(C_Queue_Processor_Assign_ID)); } /** Get Assigned Workpackage Processors. @return Assigned Workpackage Processors */ @Override public int getC_Queue_Processor_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_Processor_Assign_ID); if (ii == null)
return 0; return ii.intValue(); } @Override public de.metas.async.model.I_C_Queue_Processor getC_Queue_Processor() { return get_ValueAsPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class); } @Override public void setC_Queue_Processor(de.metas.async.model.I_C_Queue_Processor C_Queue_Processor) { set_ValueFromPO(COLUMNNAME_C_Queue_Processor_ID, de.metas.async.model.I_C_Queue_Processor.class, C_Queue_Processor); } /** Set Queue Processor Definition. @param C_Queue_Processor_ID Queue Processor Definition */ @Override 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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Processor_Assign.java
1
请完成以下Java代码
public void createMembership(String userId, String groupId) { MembershipEntity membershipEntity = create(); membershipEntity.setUserId(userId); membershipEntity.setGroupId(groupId); insert(membershipEntity, false); if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent( FlowableIdmEventType.MEMBERSHIP_CREATED, groupId, userId), engineConfiguration.getEngineCfgKey()); } } @Override public void deleteMembership(String userId, String groupId) { dataManager.deleteMembership(userId, groupId); if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent(
FlowableIdmEventType.MEMBERSHIP_DELETED, groupId, userId), engineConfiguration.getEngineCfgKey()); } } @Override public void deleteMembershipByGroupId(String groupId) { dataManager.deleteMembershipByGroupId(groupId); } @Override public void deleteMembershipByUserId(String userId) { dataManager.deleteMembershipByUserId(userId); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\MembershipEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserService customUserService; @Autowired protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/users/**") .authenticated()
.antMatchers(HttpMethod.POST) .authenticated() .antMatchers(HttpMethod.PUT) .authenticated() .antMatchers(HttpMethod.DELETE) .authenticated() .antMatchers("/**") .permitAll() .and() .sessionManagement() .and() .httpBasic(); } }
repos\springBoot-master\springboot-springSecurity2\src\main\java\com\us\example\config\WebSecurityConfig.java
2
请完成以下Java代码
private final I_M_HU_Trx_Line createTrxLineReversal(final IReference<I_M_HU_Trx_Hdr> reversalTrxHdrRef, final I_M_HU_Trx_Line trxLine) { Check.assumeNotNull(reversalTrxHdrRef, "reversalTrxHdrRef not null"); Check.assumeNotNull(trxLine, "trxLine not null"); if (trxLine.getReversalLine_ID() > 0) { throw new AdempiereException("Cannot reverse " + trxLine + " because it was already reversed by " + trxLine.getReversalLine()); } final I_M_HU_Trx_Hdr reversalTrxHdr = reversalTrxHdrRef.getValue(); Check.assumeNotNull(reversalTrxHdr, "reversalTrxHdr not null"); final I_M_HU_Trx_Line reversalTrxLine = InterfaceWrapperHelper.newInstance(I_M_HU_Trx_Line.class, reversalTrxHdr); InterfaceWrapperHelper.copyValues(trxLine, reversalTrxLine, true); // honorIsCalculated=true reversalTrxLine.setM_HU_Trx_Hdr(reversalTrxHdr); reversalTrxLine.setAD_Org_ID(reversalTrxHdr.getAD_Org_ID()); reversalTrxLine.setIsActive(true); reversalTrxLine.setParent_HU_Trx_Line(null); // to be set reversalTrxLine.setProcessed(false); reversalTrxLine.setQty(trxLine.getQty().negate()); reversalTrxLine.setReversalLine(trxLine); saveTrxLine(reversalTrxLine); // // Link back to original transaction final String trxName = InterfaceWrapperHelper.getTrxName(reversalTrxHdr); trxLine.setReversalLine(reversalTrxLine); InterfaceWrapperHelper.save(trxLine, trxName); // // Reverse attribute transactions final IHUTransactionAttributeProcessor attributeTrxProcessor = createHUTransactionAttributeProcessor(reversalTrxHdrRef); attributeTrxProcessor.reverseTrxAttributes(reversalTrxLine, trxLine); return reversalTrxLine; } /** * Link counterpart transactions (i.e. sets Parent_HU_Trx_Line_ID to point each other). *
* NOTE: after linking trx lines will be saved in this method. * * @param trxLine * @param counterpartTrxLine */ private final void linkTrxLines( @NonNull final I_M_HU_Trx_Line trxLine, @NonNull final I_M_HU_Trx_Line counterpartTrxLine) { if (trxLine.getM_HU_Trx_Hdr_ID() != counterpartTrxLine.getM_HU_Trx_Hdr_ID()) { throw new AdempiereException("Transactions lines shall have same header: " + trxLine + ", " + counterpartTrxLine); } // Link counterpartTrxLine -> trxLine if (trxLine.getM_HU_Trx_Line_ID() <= 0) { // make sure trxLine is saved so we have an ID to link with saveTrxLine(trxLine); } counterpartTrxLine.setParent_HU_Trx_Line(trxLine); saveTrxLine(counterpartTrxLine); // Link trxLine -> counterpartTrxLine trxLine.setParent_HU_Trx_Line(counterpartTrxLine); saveTrxLine(trxLine); } private IHUTransactionAttributeProcessor createHUTransactionAttributeProcessor(final IReference<I_M_HU_Trx_Hdr> trxHdrRef) { final IHUTransactionAttributeProcessor trxAttributeProcessor = new HUTransactionAttributeProcessor(getHUContext()); trxAttributeProcessor.setM_HU_Trx_Hdr(trxHdrRef); return trxAttributeProcessor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTransactionProcessor.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrayNumber() { return trayNumber; } public void setTrayNumber(String trayNumber) { this.trayNumber = trayNumber;
} public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java
1
请完成以下Java代码
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getResourceName() { return resourceName; } @Override
public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String toString() { return "ChannelDefinitionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void startAlwaysRunningRoutes() { getRoutes() .stream() .filter(CustomRouteController::isAlwaysRunning) .forEach(this::start); } private void start(final Route route) { try { getRouteController().startRoute(route.getRouteId()); } catch (final Exception e) { throw new RuntimeException("Exception caught when trying to start route=" + route.getRouteId(), e); } } private void stop(final Route route) { try { getRouteController().stopRoute(route.getRouteId(), 100, TimeUnit.MILLISECONDS); } catch (final Exception e) { throw new RuntimeException("Exception caught when trying to suspend route=" + route.getRouteId(), e); } } @NonNull private List<Route> getRoutes() {
return camelContext.getRoutes(); } @NonNull private RouteController getRouteController() { return camelContext.getRouteController(); } private static boolean isReadyToStart(@NonNull final Route route) { final boolean isStartOnDemand = CamelRoutesGroup.ofCodeOptional(route.getGroup()) .map(CamelRoutesGroup::isStartOnDemand) .orElse(false); return !isStartOnDemand; } private static boolean canBeStopped(@NonNull final Route route) { return !isAlwaysRunning(route); } private static boolean isAlwaysRunning(@NonNull final Route route) { return CamelRoutesGroup.ofCodeOptional(route.getGroup()) .map(CamelRoutesGroup::isAlwaysOn) .orElse(false); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\CustomRouteController.java
2
请完成以下Java代码
private ArrayList<I_AD_User> getOrLoadContacts() { if (contacts == null) { if (record.getC_BPartner_ID() > 0) { contacts = new ArrayList<>(bpartnersRepo.retrieveContacts(record)); } else { contacts = new ArrayList<>(); } } return contacts; }
public BPartnerContactId addAndSaveContact(final I_AD_User contact) { bpartnersRepo.save(contact); final BPartnerContactId contactId = BPartnerContactId.ofRepoId(contact.getC_BPartner_ID(), contact.getAD_User_ID()); if (!getContactById(contactId).isPresent()) { getOrLoadContacts().add(contact); } return contactId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnersCache.java
1
请在Spring Boot框架中完成以下Java代码
public class TraceableVariablesCommandContextCloseListener implements CommandContextCloseListener { protected TraceableObject<?, ?> traceableObject; public TraceableVariablesCommandContextCloseListener(TraceableObject<?, ?> traceableObject) { this.traceableObject = traceableObject; } @Override public void closing(CommandContext commandContext) { traceableObject.updateIfValueChanged(); } @Override public void closed(CommandContext commandContext) { } @Override public void afterSessionsFlush(CommandContext commandContext) {
} @Override public void closeFailure(CommandContext commandContext) { } @Override public Integer order() { return 1; } @Override public boolean multipleAllowed() { return true; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\TraceableVariablesCommandContextCloseListener.java
2
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "username") private String userName; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "address_id", referencedColumnName = "id") private Address address; public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\foreignkeybased\User.java
2
请完成以下Java代码
private BPartnerImportContext createNewContext(final boolean insertOnly) { final BPartnersCache bpartnersCache = BPartnersCache.builder() .bpartnersRepo(bpartnersRepo) .build(); return BPartnerImportContext.builder() .bpartnersCache(bpartnersCache) .insertOnly(insertOnly) .build(); } private ImportRecordResult importOrUpdateBPartner(final BPartnerImportContext context) { final ImportRecordResult bpartnerImportResult; // We don't have a previous C_BPartner_ID // => create or update existing BPartner from this line final boolean bpartnerExists = context.isCurrentBPartnerIdSet(); if (context.isInsertOnly() && bpartnerExists) { // #4994 do not update existing entries return ImportRecordResult.Nothing; } bpartnerImportResult = bpartnerExists ? ImportRecordResult.Updated : ImportRecordResult.Inserted; bpartnerImporter.importRecord(context); return bpartnerImportResult; } private void createUpdateInterestArea(final I_I_BPartner importRecord) { final int interestAreaId = importRecord.getR_InterestArea_ID(); if (interestAreaId <= 0) { return; } final int adUserId = importRecord.getAD_User_ID(); if (adUserId <= 0) { return; } final MContactInterest ci = MContactInterest.get(getCtx(), interestAreaId, adUserId, true, // active
ITrx.TRXNAME_ThreadInherited); ci.save(); // don't subscribe or re-activate } @Override public Class<I_I_BPartner> getImportModelClass() { return I_I_BPartner.class; } @Override public String getImportTableName() { return I_I_BPartner.Table_Name; } @Override protected String getImportOrderBySql() { // gody: 20070113 - Order so the same values are consecutive. return I_I_BPartner.COLUMNNAME_BPValue + ", " + I_I_BPartner.COLUMNNAME_GlobalId + ", " + I_I_BPartner.COLUMNNAME_I_BPartner_ID; } @Override protected String getTargetTableName() { return I_C_BPartner.Table_Name; } @Override public I_I_BPartner retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_BPartner(ctx, rs, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public LicenseFeeSettings getById(@NonNull final LicenseFeeSettingsId licenseFeeSettingsId) { final I_C_LicenseFeeSettings licenseFeeSettings = InterfaceWrapperHelper.load(licenseFeeSettingsId, I_C_LicenseFeeSettings.class); return toLicenseFeeSettings(licenseFeeSettings); } @NonNull private LicenseFeeSettings toLicenseFeeSettings(@NonNull final I_C_LicenseFeeSettings record) { final LicenseFeeSettingsId licenseFeeSettingsId = LicenseFeeSettingsId.ofRepoId(record.getC_LicenseFeeSettings_ID()); final ImmutableList<LicenseFeeSettingsLine> licenseFeeSettingsLines = queryBL.createQueryBuilder(I_C_LicenseFeeSettingsLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_LicenseFeeSettingsLine.COLUMNNAME_C_LicenseFeeSettings_ID, licenseFeeSettingsId) .create() .stream() .map(this::toLicenseFeeSettingsLine) .collect(ImmutableList.toImmutableList()); return LicenseFeeSettings.builder() .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .licenseFeeSettingsId(licenseFeeSettingsId) .commissionProductId(ProductId.ofRepoId(record.getCommission_Product_ID())) .pointsPrecision(record.getPointsPrecision()) .lines(licenseFeeSettingsLines) .build(); }
@NonNull private LicenseFeeSettingsLine toLicenseFeeSettingsLine(@NonNull final I_C_LicenseFeeSettingsLine record) { final LicenseFeeSettingsId licenseFeeSettingsId = LicenseFeeSettingsId.ofRepoId(record.getC_LicenseFeeSettings_ID()); return LicenseFeeSettingsLine.builder() .licenseFeeSettingsLineId(LicenseFeeSettingsLineId.ofRepoId(licenseFeeSettingsId, record.getC_LicenseFeeSettingsLine_ID())) .licenseFeeSettingsId(licenseFeeSettingsId) .seqNo(record.getSeqNo()) .percentOfBasedPoints(Percent.of(record.getPercentOfBasePoints())) .bpGroupIdMatch(BPGroupId.ofRepoIdOrNull(record.getC_BP_Group_Match_ID())) .active(record.isActive()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\repository\LicenseFeeSettingsRepository.java
2
请完成以下Java代码
public String getTaskDescription() { return taskDescription; } public String getTaskDescriptionLike() { return taskDescriptionLike; } public String getTaskDeleteReason() { return taskDeleteReason; } public String getTaskDeleteReasonLike() { return taskDeleteReasonLike; } public List<String> getTaskAssigneeIds() { return taskAssigneeIds; } public String getTaskAssignee() { return taskAssignee; } public String getTaskAssigneeLike() { return taskAssigneeLike; } public String getTaskId() { return taskId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public String getTaskOwnerLike() { return taskOwnerLike; } public String getTaskOwner() { return taskOwner; } public String getTaskParentTaskId() { return taskParentTaskId; } public Date getCreationDate() { return creationDate; } public String getCandidateUser() { return candidateUser; } public String getCandidateGroup() {
return candidateGroup; } public String getInvolvedUser() { return involvedUser; } public List<String> getInvolvedGroups() { return involvedGroups; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getTaskNameLikeIgnoreCase() { return taskNameLikeIgnoreCase; } public String getTaskDescriptionLikeIgnoreCase() { return taskDescriptionLikeIgnoreCase; } public String getTaskOwnerLikeIgnoreCase() { return taskOwnerLikeIgnoreCase; } public String getTaskAssigneeLikeIgnoreCase() { return taskAssigneeLikeIgnoreCase; } public String getLocale() { return locale; } public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void launchJob() throws Exception { Date date = new Date(); logger.debug("scheduler starts at " + date); if (enabled.get()) { JobExecution jobExecution = jobLauncher.run(job(jobRepository, transactionManager), new JobParametersBuilder().addDate("launchDate", date) .toJobParameters()); batchRunCounter.incrementAndGet(); logger.debug("Batch job ends with status as " + jobExecution.getStatus()); } logger.debug("scheduler ends "); } public void stop() { enabled.set(false); } public void start() { enabled.set(true); } @Bean public TaskScheduler poolScheduler() { return new CustomTaskScheduler(); } private class CustomTaskScheduler extends ThreadPoolTaskScheduler { private static final long serialVersionUID = -7142624085505040603L; @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) { ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; scheduledTasks.put(runnable.getTarget(), future); return future; } } public void cancelFutureSchedulerTasks() { scheduledTasks.forEach((k, v) -> { if (k instanceof SpringBatchScheduler) { v.cancel(false); } }); } @Bean public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new JobBuilder("job", jobRepository) .start(readBooks(jobRepository, transactionManager)) .build(); } @Bean protected Step readBooks(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readBooks", jobRepository) .<Book, Book> chunk(2, transactionManager) .reader(reader()) .writer(writer())
.build(); } @Bean public FlatFileItemReader<Book> reader() { return new FlatFileItemReaderBuilder<Book>().name("bookItemReader") .resource(new ClassPathResource("books.csv")) .delimited() .names(new String[] { "id", "name" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<>() { { setTargetType(Book.class); } }) .build(); } @Bean public ItemWriter<Book> writer() { return items -> { logger.debug("writer..." + items.size()); for (Book item : items) { logger.debug(item.toString()); } }; } public AtomicInteger getBatchRunCounter() { return batchRunCounter; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchscheduler\SpringBatchScheduler.java
2
请完成以下Java代码
public void receiveMessage(Message message) throws BusinessException { log.info("Received message: {}", message.toString()); throw new BusinessException(); } @Bean @ConditionalOnProperty( value = "amqp.configuration.current", havingValue = "simple-dlq") public SimpleDLQAmqpContainer simpleAmqpContainer() { return new SimpleDLQAmqpContainer(rabbitTemplate); } @Bean @ConditionalOnProperty( value = "amqp.configuration.current", havingValue = "routing-dlq") public RoutingDLQAmqpContainer routingDLQAmqpContainer() { return new RoutingDLQAmqpContainer(rabbitTemplate);
} @Bean @ConditionalOnProperty( value = "amqp.configuration.current", havingValue = "dlx-custom") public DLQCustomAmqpContainer dlqAmqpContainer() { return new DLQCustomAmqpContainer(rabbitTemplate); } @Bean @ConditionalOnProperty( value = "amqp.configuration.current", havingValue = "parking-lot-dlx") public ParkingLotDLQAmqpContainer parkingLotDLQAmqpContainer() { return new ParkingLotDLQAmqpContainer(rabbitTemplate); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\consumer\MessagesConsumer.java
1
请完成以下Java代码
public AllocableStorage getStorage(final HuId huId, final ProductId productId) { final ReservableStorageKey key = ReservableStorageKey.of(huId, productId); return storages.computeIfAbsent(key, this::retrieveStorage); } private AllocableStorage retrieveStorage(final ReservableStorageKey key) { final ProductId productId = key.getProductId(); final HuId topLeveHUId = key.getHuId(); final ImmutableSet<HuId> vhuIds = husCache.getVHUIds(topLeveHUId); final ImmutableMap<HuId, HUReservationEntry> reservationsByVHUId = Maps.uniqueIndex(huReservationService.getEntriesByVHUIds(vhuIds), HUReservationEntry::getVhuId); final ArrayList<VHUAllocableStorage> vhuAllocableStorages = new ArrayList<>(); for (final HuId vhuId : husCache.getVHUIds(topLeveHUId)) { final I_M_HU vhu = husCache.getHUById(vhuId); final IHUProductStorage huProductStorage = handlingUnitsBL .getStorageFactory() .getStorage(vhu) .getProductStorageOrNull(productId); if (huProductStorage != null)
{ final int seqNo = vhuId.getRepoId(); final Quantity qtyFreeToAllocate = huProductStorage.getQty(); final HUReservationEntry reservation = reservationsByVHUId.get(vhuId); final HUReservationDocRef reservationDocRef = reservation != null ? reservation.getDocumentRef() : null; final VHUAllocableStorage vhuAllocableStorage = new VHUAllocableStorage(seqNo, productId, qtyFreeToAllocate, reservationDocRef); vhuAllocableStorages.add(vhuAllocableStorage); } } if (vhuAllocableStorages.isEmpty()) { final I_C_UOM stockingUOM = productBL.getStockUOM(productId); final VHUAllocableStorage vhuAllocableStorage = new VHUAllocableStorage(0, productId, Quantity.zero(stockingUOM), null); vhuAllocableStorages.add(vhuAllocableStorage); } return new AllocableStorage(vhuAllocableStorages); } @Value(staticConstructor = "of") private static class ReservableStorageKey { @NonNull HuId huId; @NonNull ProductId productId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\allocableHUStorages\AllocableStoragesSupplier.java
1
请完成以下Java代码
default void setViewsRepository(final IViewsRepository viewsRepository) { } /** * Adds given view to the index. If the view already exists, it will be overridden. */ void put(IView view); /** * @return the {@link IView} identified by <code>viewId</code> or <code>null</code> if not found. */ @Nullable IView getByIdOrNull(ViewId viewId);
/** * Closes and removes the view identified by given <code>viewId</code>. If the view does not exist, the method will do nothing, i.e. not failing. */ void closeById(ViewId viewId, ViewCloseAction closeAction); Stream<IView> streamAllViews(); default ImmutableList<IView> getAllViews() { return streamAllViews().collect(ImmutableList.toImmutableList()); } void invalidateView(ViewId viewId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewsIndexStorage.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getTargetDate() {
return targetDate; } public void setTargetDate(Date targetDate) { this.targetDate = targetDate; } public Todo(){super();} public Todo(String user, String desc, Date targetDate, boolean isDone) { super(); this.userName = user; this.description = desc; this.targetDate = targetDate; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\model\Todo.java
1
请完成以下Java代码
public String filterType() { return "post"; } @Override public int filterOrder() { return 100; } /** * Filter requests to micro-services Swagger docs. */ @Override public boolean shouldFilter() { return RequestContext.getCurrentContext().getRequest().getRequestURI().endsWith(Swagger2Controller.DEFAULT_URL); } @Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); context.getResponse().setCharacterEncoding("UTF-8"); String rewrittenResponse = rewriteBasePath(context); if (context.getResponseGZipped()) { try { context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse))); } catch (IOException e) { log.error("Swagger-docs filter error", e); } } else { context.setResponseBody(rewrittenResponse); } return null; }
@SuppressWarnings("unchecked") private String rewriteBasePath(RequestContext context) { InputStream responseDataStream = context.getResponseDataStream(); String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI(); try { if (context.getResponseGZipped()) { responseDataStream = new GZIPInputStream(context.getResponseDataStream()); } String response = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8); if (response != null) { LinkedHashMap<String, Object> map = this.mapper.readValue(response, LinkedHashMap.class); String basePath = requestUri.replace(Swagger2Controller.DEFAULT_URL, ""); map.put("basePath", basePath); log.debug("Swagger-docs: rewritten Base URL with correct micro-service route: {}", basePath); return mapper.writeValueAsString(map); } } catch (IOException e) { log.error("Swagger-docs filter error", e); } return null; } public static byte[] gzipData(String content) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter gzip = new PrintWriter(new GZIPOutputStream(bos)); gzip.print(content); gzip.flush(); gzip.close(); return bos.toByteArray(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\responserewriting\SwaggerBasePathRewritingFilter.java
1
请完成以下Java代码
public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("key", this.key); creator.append("protocol", this.protocol); creator.append("stores", this.stores); creator.append("options", this.options); return creator.toString(); } private static final class WebServerSslStoreBundle implements SslStoreBundle { private final @Nullable KeyStore keyStore; private final @Nullable KeyStore trustStore; private final @Nullable String keyStorePassword; private WebServerSslStoreBundle(@Nullable KeyStore keyStore, @Nullable KeyStore trustStore, @Nullable String keyStorePassword) { Assert.state(keyStore != null || trustStore != null, "SSL is enabled but no trust material is configured for the default host"); this.keyStore = keyStore; this.trustStore = trustStore; this.keyStorePassword = keyStorePassword; } @Override public @Nullable KeyStore getKeyStore() { return this.keyStore;
} @Override public @Nullable KeyStore getTrustStore() { return this.trustStore; } @Override public @Nullable String getKeyStorePassword() { return this.keyStorePassword; } @Override public String toString() { ToStringCreator creator = new ToStringCreator(this); creator.append("keyStore.type", (this.keyStore != null) ? this.keyStore.getType() : "none"); creator.append("keyStorePassword", (this.keyStorePassword != null) ? "******" : null); creator.append("trustStore.type", (this.trustStore != null) ? this.trustStore.getType() : "none"); return creator.toString(); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\WebServerSslBundle.java
1
请完成以下Java代码
public class ModifiedByValueGeneration implements AnnotationValueGeneration<ModifiedBy> { private final ByValueGenerator generator = new ByValueGenerator(new UserService()); @Override public void initialize(ModifiedBy mby, Class<?> clazz) { } @Override public GenerationTiming getGenerationTiming() { return GenerationTiming.ALWAYS; }
@Override public ValueGenerator<?> getValueGenerator() { return generator; } @Override public boolean referenceColumnInSql() { return false; } @Override public String getDatabaseGeneratedReferencedColumnValue() { return null; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootTimestampGeneration\src\main\java\com\bookstore\by\ModifiedByValueGeneration.java
1
请完成以下Java代码
protected void addCommonFormFieldAttributes(FormField formField, HtmlElementWriter formControl) { String typeName = formField.getTypeName(); if (isEnum(formField) || isDate(formField)) { typeName = StringFormType.TYPE_NAME; } typeName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1); String formFieldId = formField.getId(); formControl .attribute(CLASS_ATTRIBUTE, FORM_CONTROL_CLASS) .attribute(NAME_ATTRIBUTE, formFieldId); if (!formField.isBusinessKey()) { formControl .attribute(CAM_VARIABLE_TYPE_ATTRIBUTE, typeName) .attribute(CAM_VARIABLE_NAME_ATTRIBUTE, formFieldId); } else { formControl.attribute(CAM_BUSINESS_KEY_ATTRIBUTE, null); } // add validation constraints for (FormFieldValidationConstraint constraint : formField.getValidationConstraints()) { String constraintName = constraint.getName(); String configuration = (String) constraint.getConfiguration(); formControl.attribute(CONSTRAINT_READONLY.equals(constraintName) ? CONSTRAINT_DISABLED : constraintName, configuration); } } // helper /////////////////////////////////////////////////////////////////////////////////////
protected boolean isEnum(FormField formField) { return EnumFormType.TYPE_NAME.equals(formField.getTypeName()); } protected boolean isDate(FormField formField) { return DateFormType.TYPE_NAME.equals(formField.getTypeName()); } protected boolean isBoolean(FormField formField) { return BooleanFormType.TYPE_NAME.equals(formField.getTypeName()); } protected boolean isReadOnly(FormField formField) { List<FormFieldValidationConstraint> validationConstraints = formField.getValidationConstraints(); if(validationConstraints != null) { for (FormFieldValidationConstraint validationConstraint : validationConstraints) { if(CONSTRAINT_READONLY.equals(validationConstraint.getName())){ return true; } } } return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlFormEngine.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; }
public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } @Override public String toString() { return "Address [id=" + id + ", name=" + name + ", city=" + city + ", postalCode=" + postalCode + "]"; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\putvspost\Address.java
1
请完成以下Java代码
public class ActivitiMapExceptionParser extends BaseChildElementParser { @Override public String getElementName() { return MAP_EXCEPTION; } @Override public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { if (!(parentElement instanceof Activity)) return; String errorCode = xtr.getAttributeValue(null, MAP_EXCEPTION_ERRORCODE); String andChildren = xtr.getAttributeValue(null, MAP_EXCEPTION_ANDCHILDREN); String exceptionClass = xtr.getElementText(); boolean hasChildrenBool = false; if (StringUtils.isEmpty(andChildren) || andChildren.toLowerCase().equals("false")) { hasChildrenBool = false; } else if (andChildren.toLowerCase().equals("true")) { hasChildrenBool = true; } else { throw new XMLException(
"'" + andChildren + "' is not valid boolean in mapException with errorCode=" + errorCode + " and class=" + exceptionClass ); } if (StringUtils.isEmpty(errorCode) || StringUtils.isEmpty(errorCode.trim())) { throw new XMLException( "No errorCode defined mapException with errorCode=" + errorCode + " and class=" + exceptionClass ); } ((Activity) parentElement).getMapExceptions().add( new MapExceptionEntry(errorCode, exceptionClass, hasChildrenBool) ); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\ActivitiMapExceptionParser.java
1
请完成以下Java代码
public class BoundaryEventParseHandler extends AbstractFlowNodeBpmnParseHandler<BoundaryEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(BoundaryEventParseHandler.class); @Override public Class<? extends BaseElement> getHandledType() { return BoundaryEvent.class; } @Override protected void executeParse(BpmnParse bpmnParse, BoundaryEvent boundaryEvent) { ActivityImpl parentActivity = findActivity(bpmnParse, boundaryEvent.getAttachedToRefId()); if (parentActivity == null) { LOGGER.warn("Invalid reference in boundary event. Make sure that the referenced activity is defined in the same scope as the boundary event {}", boundaryEvent.getId()); return; } ActivityImpl nestedActivity = createActivityOnScope(bpmnParse, boundaryEvent, BpmnXMLConstants.ELEMENT_EVENT_BOUNDARY, parentActivity); bpmnParse.setCurrentActivity(nestedActivity); EventDefinition eventDefinition = null; if (!boundaryEvent.getEventDefinitions().isEmpty()) { eventDefinition = boundaryEvent.getEventDefinitions().get(0); }
if (eventDefinition instanceof TimerEventDefinition || eventDefinition instanceof org.flowable.bpmn.model.ErrorEventDefinition || eventDefinition instanceof SignalEventDefinition || eventDefinition instanceof CancelEventDefinition || eventDefinition instanceof MessageEventDefinition || eventDefinition instanceof org.flowable.bpmn.model.CompensateEventDefinition) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { LOGGER.warn("Unsupported boundary event type for boundary event {}", boundaryEvent.getId()); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\BoundaryEventParseHandler.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!selectedRowIds.isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PickingSlotRow row = getSingleSelectedPickingSlotRow(); if (!row.isTopLevelHU()) { return ProcessPreconditionsResolution.rejectWithInternalReason("select a top level HU"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { // // Get the HU final PickingSlotRow huRow = getSingleSelectedPickingSlotRow(); Check.assume(huRow.isTopLevelHU(), "row {} shall be a top level HU", huRow); final I_M_HU hu = InterfaceWrapperHelper.load(huRow.getHuId(), I_M_HU.class); // // Remove the HU from it's picking slot huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(hu); // // Make sure the HU has the BPartner/Location of the picking slot final PickingSlotRow pickingSlotRow = getRootRowForSelectedPickingSlotRows(); if (pickingSlotRow.getBPartnerId() > 0) { hu.setC_BPartner_ID(pickingSlotRow.getBPartnerId()); hu.setC_BPartner_Location_ID(pickingSlotRow.getBPartnerLocationId()); InterfaceWrapperHelper.save(hu); } // // Move the HU to an after picking locator moveToAfterPickingLocator(hu); // // Inactive all those picking candidates pickingCandidateService.inactivateForHUId(HuId.ofRepoId(hu.getM_HU_ID()));
husExtractedEvents.add(HUExtractedFromPickingSlotEvent.builder() .huId(hu.getM_HU_ID()) .bpartnerId(hu.getC_BPartner_ID()) .bpartnerLocationId(hu.getC_BPartner_Location_ID()) .build()); return MSG_OK; } @Override protected void postProcess(final boolean success) { if (!success) { return; } // // Invalidate the views // Expectation: the HU shall disappear from picking slots view (left side) and shall appear on after picking HUs view (right side). final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView(); invalidateView(pickingSlotsClearingView.getViewId()); // husExtractedEvents.forEach(pickingSlotsClearingView::handleEvent); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutHU.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSingleSelectedBPartnerId().isPresent()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a single selected BPartner"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final BPartnerId bPartnerId = getSingleSelectedBPartnerId().orElse(null); final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID) .setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bPartnerId) .build()) .getViewId(); getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.getViewId()) .target(ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private Optional<BPartnerId> getSingleSelectedBPartnerId() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); return selectedRowIds.isSingleDocumentId() ? Optional.of(selectedRowIds.getSingleDocumentId().toId(BPartnerId::ofRepoId)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_BPartnerView.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringDataJpaConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan(Employee.class.getPackage() .getName()); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); em.setJpaProperties(properties); return em; } @Bean
public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactoryBean.getObject()); return transactionManager; } @Bean public DataSource dataSource() { return DataSourceBuilder.create() .url("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1") .driverClassName("org.h2.Driver") .username("sa") .password("sa") .build(); } @Bean public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) { return new JPAQueryFactory((entityManager)); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\spring\data\persistence\springdatajpadifference\springdata\config\SpringDataJpaConfig.java
2
请完成以下Java代码
static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix() { return stripPrefix(1); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix(int parts) { return ofRequestProcessor(BeforeFilterFunctions.stripPrefix(parts)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(int statusCode) { return setStatus(new HttpStatusHolder(null, statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) { return setStatus(new HttpStatusHolder(statusCode, null)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) { return ofResponseProcessor(AfterFilterFunctions.setStatus(statusCode));
} static HandlerFilterFunction<ServerResponse, ServerResponse> uri(String uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> uri(URI uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(FilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FilterFunctions.java
1
请完成以下Java代码
private boolean recursivePalindrome(String text, int forward, int backward) { if (forward == backward) return true; if ((text.charAt(forward)) != (text.charAt(backward))) return false; if (forward < backward + 1) { return recursivePalindrome(text, forward + 1, backward - 1); } return true; } public boolean isPalindromeUsingIntStream(String text) { String temp = text.replaceAll("\\s+", "") .toLowerCase();
return IntStream.range(0, temp.length() / 2) .noneMatch(i -> temp.charAt(i) != temp.charAt(temp.length() - i - 1)); } boolean hasPalindromePermutation(String text) { long charsWithOddOccurrencesCount = text.chars() .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values() .stream() .filter(count -> count % 2 != 0) .count(); return charsWithOddOccurrencesCount <= 1; } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\palindrom\Palindrome.java
1
请完成以下Java代码
public boolean isRecordCopyingModeIncludingDetails() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.getTableModel().isCopyWithDetails(); } @Override public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError); return; } gridTab.fireDataStatusEEvent(AD_Message, info, isError); } @Override public void fireDataStatusEEvent(final ValueNamePair errorLog) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog); return; } gridTab.fireDataStatusEEvent(errorLog); } @Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { throw new UnsupportedOperationException(); } @Override public ICalloutRecord getCalloutRecord() { final GridTab gridTab = getGridTab(); Check.assumeNotNull(gridTab, "gridTab not null"); return gridTab; } @Override public int getContextAsInt(String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
1
请在Spring Boot框架中完成以下Java代码
public class FTSModelIndexerRegistry { private static final Logger logger = LogManager.getLogger(FTSModelIndexerRegistry.class); private final ImmutableMap<TableName, FTSModelIndexer> indexersBySourceTableName; public FTSModelIndexerRegistry(@NonNull final Optional<List<FTSModelIndexer>> indexers) { this.indexersBySourceTableName = indexers.orElseGet(ImmutableList::of) .stream() .flatMap(indexer -> indexer.getHandledSourceTableNames() .stream() .map(sourceTableName -> GuavaCollectors.entry(sourceTableName, indexer))) .collect(GuavaCollectors.toImmutableMap()); logger.info("Indexers: {}", this.indexersBySourceTableName); } public Optional<FTSModelIndexer> getBySourceTableName(@NonNull final TableName sourceTableName)
{ return Optional.ofNullable(indexersBySourceTableName.get(sourceTableName)); } public List<FTSModelIndexer> getBySourceTableNames(@NonNull final Collection<TableName> sourceTableNames) { return sourceTableNames.stream() .distinct() .map(indexersBySourceTableName::get) .filter(Objects::nonNull) .distinct() .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\handler\FTSModelIndexerRegistry.java
2
请完成以下Java代码
protected CommandContext getCommandContext() { return CommandContextUtil.getCommandContext(); } protected <T> T getSession(Class<T> sessionClass) { return getCommandContext().getSession(sessionClass); } // Engine scoped protected IdmEngineConfiguration getIdmEngineConfiguration() { return idmEngineConfiguration; } protected CommandExecutor getCommandExecutor() { return getIdmEngineConfiguration().getCommandExecutor(); }
protected FlowableEventDispatcher getEventDispatcher() { return getIdmEngineConfiguration().getEventDispatcher(); } protected GroupEntityManager getGroupEntityManager() { return getIdmEngineConfiguration().getGroupEntityManager(); } protected MembershipEntityManager getMembershipEntityManager() { return getIdmEngineConfiguration().getMembershipEntityManager(); } protected IdentityInfoEntityManager getIdentityInfoEntityManager() { return getIdmEngineConfiguration().getIdentityInfoEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\AbstractManager.java
1
请完成以下Java代码
protected void provideRemovalTime(HistoryEvent historicInstance) { if (historicInstance != null) { String rootProcessInstanceId = historicInstance.getRootProcessInstanceId(); authorization.setRootProcessInstanceId(rootProcessInstanceId); Date removalTime = historicInstance.getRemovalTime(); authorization.setRemovalTime(removalTime); } else { // reset authorization.setRootProcessInstanceId(null); authorization.setRemovalTime(null); } } protected HistoryEvent getHistoricProcessInstance(CommandContext commandContext) { String historicProcessInstanceId = authorization.getResourceId(); if (isNullOrAny(historicProcessInstanceId)) { return null; } return commandContext.getHistoricProcessInstanceManager() .findHistoricProcessInstance(historicProcessInstanceId); } protected HistoryEvent getHistoricTaskInstance(CommandContext commandContext) { String historicTaskInstanceId = authorization.getResourceId();
if (isNullOrAny(historicTaskInstanceId)) { return null; } return commandContext.getHistoricTaskInstanceManager() .findHistoricTaskInstanceById(historicTaskInstanceId); } protected boolean isNullOrAny(String resourceId) { return resourceId == null || isAny(resourceId); } protected boolean isAny(String resourceId) { return Objects.equals(Authorization.ANY, resourceId); } protected boolean isResourceEqualTo(Resources resource) { return Objects.equals(resource.resourceType(), authorization.getResource()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SaveAuthorizationCmd.java
1
请完成以下Java代码
public String getTableName() { return m_info.getTableName().getAsString(); } @Override public boolean isAutoComplete() { return m_info != null && m_info.isAutoComplete(); } public MLookupInfo getLookupInfo() { return m_info; } @Override public Set<String> getParameters() { return m_info.getValidationRule().getAllParameters(); } @Override public IValidationContext getValidationContext() {
return m_evalCtx; } public boolean isNumericKey() { return getColumnName().endsWith("_ID"); } @Override public NamePair suggestValidValue(final NamePair value) { return null; } } // MLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookup.java
1
请完成以下Java代码
public final class X509ClientCertificateAuthenticationConverter implements AuthenticationConverter { @Nullable @Override public Authentication convert(HttpServletRequest request) { X509Certificate[] clientCertificateChain = (X509Certificate[]) request .getAttribute("jakarta.servlet.request.X509Certificate"); if (clientCertificateChain == null || clientCertificateChain.length == 0) { return null; } MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request); // client_id (REQUIRED) String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID); if (!StringUtils.hasText(clientId)) { return null; }
if (parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } Map<String, Object> additionalParameters = OAuth2EndpointUtils .getParametersIfMatchesAuthorizationCodeGrantRequest(request, OAuth2ParameterNames.CLIENT_ID); ClientAuthenticationMethod clientAuthenticationMethod = (clientCertificateChain.length == 1) ? ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH : ClientAuthenticationMethod.TLS_CLIENT_AUTH; return new OAuth2ClientAuthenticationToken(clientId, clientAuthenticationMethod, clientCertificateChain, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\X509ClientCertificateAuthenticationConverter.java
1
请完成以下Java代码
public boolean isParent () { Object oo = get_Value(COLUMNNAME_IsParent); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Job Cant. @param JobCant Job Cant */ public void setJobCant (int JobCant) { set_Value (COLUMNNAME_JobCant, Integer.valueOf(JobCant)); } /** Get Job Cant. @return Job Cant */ public int getJobCant () { Integer ii = (Integer)get_Value(COLUMNNAME_JobCant); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public org.eevolution.model.I_HR_Job getNext_Job() throws RuntimeException { return (org.eevolution.model.I_HR_Job)MTable.get(getCtx(), org.eevolution.model.I_HR_Job.Table_Name) .getPO(getNext_Job_ID(), get_TrxName()); } /** Set Next Job. @param Next_Job_ID Next Job */ public void setNext_Job_ID (int Next_Job_ID) { if (Next_Job_ID < 1) set_Value (COLUMNNAME_Next_Job_ID, null); else set_Value (COLUMNNAME_Next_Job_ID, Integer.valueOf(Next_Job_ID)); } /** Get Next Job. @return Next Job */ public int getNext_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Next_Job_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); }
/** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Job.java
1
请完成以下Java代码
public Flux<String> noContent() { return Flux.empty(); } @GetMapping(value = "/accepted", produces = MediaType.APPLICATION_JSON_VALUE) public Flux<String> accepted(ServerHttpResponse response) { response.setStatusCode(HttpStatus.ACCEPTED); return Flux.just("accepted"); } @GetMapping(value = "/bad-request") public Mono<String> badRequest() { return Mono.error(new IllegalArgumentException()); } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments") @ExceptionHandler(IllegalArgumentException.class) public void illegalArgument() { }
@GetMapping(value = "/unauthorized") public ResponseEntity<Mono<String>> unathorized() { return ResponseEntity .status(HttpStatus.UNAUTHORIZED) .header("X-Reason", "user-invalid") .body(Mono.just("unauthorized")); } @Bean public RouterFunction<ServerResponse> notFound() { return RouterFunctions.route(GET("/statuses/not-found"), request -> ServerResponse .notFound() .build()); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\responsestatus\ResponseStatusController.java
1
请在Spring Boot框架中完成以下Java代码
public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } @Override public void setProductNo (final java.lang.String ProductNo) { set_Value (COLUMNNAME_ProductNo, ProductNo); } @Override public java.lang.String getProductNo() { return get_ValueAsString(COLUMNNAME_ProductNo); } @Override public void setReference (final @Nullable java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } @Override public java.lang.String getReference() { return get_ValueAsString(COLUMNNAME_Reference); } @Override public void setSerialNo (final @Nullable java.lang.String SerialNo) { set_Value (COLUMNNAME_SerialNo, SerialNo); } @Override public java.lang.String getSerialNo()
{ return get_ValueAsString(COLUMNNAME_SerialNo); } @Override public void setServiceRepair_Old_Shipped_HU_ID (final int ServiceRepair_Old_Shipped_HU_ID) { if (ServiceRepair_Old_Shipped_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, ServiceRepair_Old_Shipped_HU_ID); } @Override public int getServiceRepair_Old_Shipped_HU_ID() { return get_ValueAsInt(COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID); } @Override public void setWarrantyStartDate (final @Nullable java.sql.Timestamp WarrantyStartDate) { set_Value (COLUMNNAME_WarrantyStartDate, WarrantyStartDate); } @Override public java.sql.Timestamp getWarrantyStartDate() { return get_ValueAsTimestamp(COLUMNNAME_WarrantyStartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_ServiceRepair_Old_Shipped_HU.java
2
请完成以下Java代码
default boolean isCompleted(@NonNull final I_C_Order order) { return DocStatus.ofCode(order.getDocStatus()).isCompleted(); } DocStatus getDocStatus(OrderId orderId); void save(I_C_OrderLine orderLine); de.metas.interfaces.I_C_OrderLine createOrderLine(I_C_Order order); void setProductId( @NonNull I_C_OrderLine orderLine, @NonNull ProductId productId, boolean setUOM); CurrencyConversionContext getCurrencyConversionContext(I_C_Order order); void deleteLineById(final OrderAndLineId orderAndLineId); String getDescriptionBottomById(@NonNull OrderId orderId); String getDescriptionById(@NonNull OrderId orderId); void setShipperId(@NonNull I_C_Order order); default boolean isLUQtySet(final @NonNull de.metas.interfaces.I_C_OrderLine orderLine)
{ final BigDecimal luQty = orderLine.getQtyLU(); return luQty != null && luQty.signum() > 0; } PaymentTermId getPaymentTermId(@NonNull I_C_Order orderRecord); Money getGrandTotal(@NonNull I_C_Order order); void save(I_C_Order order); void syncDatesFromTransportOrder(@NonNull OrderId orderId, @NonNull I_M_ShipperTransportation transportOrder); void syncDateInvoicedFromInvoice(@NonNull OrderId orderId, @NonNull I_C_Invoice invoice); List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\IOrderBL.java
1
请完成以下Java代码
public int getStateCode() { return stateCode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + stateCode; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false;
if (getClass() != obj.getClass()) return false; IncidentStateImpl other = (IncidentStateImpl) obj; if (stateCode != other.stateCode) return false; return true; } @Override public String toString() { return name; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\history\IncidentState.java
1
请完成以下Java代码
public boolean isMetaParameter() { return metaParameter; } public void setMetaParameter(boolean metaParameter) { this.metaParameter = metaParameter; } @JsonIgnore public boolean isNotForBody() { return header || isFullPayload || metaParameter; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventPayload that = (EventPayload) o; return Objects.equals(name, that.name) && Objects.equals(type, that.type) && correlationParameter == that.correlationParameter && header == that.header && isFullPayload == that.isFullPayload && metaParameter == that.metaParameter; } @Override public int hashCode() { return Objects.hash(name, type); } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventPayload.java
1
请完成以下Java代码
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set SQLStatement. @param SQLStatement SQLStatement */ @Override public void setSQLStatement (java.lang.String SQLStatement) { set_Value (COLUMNNAME_SQLStatement, SQLStatement); } /** Get SQLStatement. @return SQLStatement */ @Override public java.lang.String getSQLStatement () { return (java.lang.String)get_Value(COLUMNNAME_SQLStatement); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_ValueNoCheck (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } /** * StepType AD_Reference_ID=53313 * Reference name: Migration step type */ public static final int STEPTYPE_AD_Reference_ID=53313; /** Application Dictionary = AD */ public static final String STEPTYPE_ApplicationDictionary = "AD";
/** SQL Statement = SQL */ public static final String STEPTYPE_SQLStatement = "SQL"; /** Set Step type. @param StepType Migration step type */ @Override public void setStepType (java.lang.String StepType) { set_ValueNoCheck (COLUMNNAME_StepType, StepType); } /** Get Step type. @return Migration step type */ @Override public java.lang.String getStepType () { return (java.lang.String)get_Value(COLUMNNAME_StepType); } /** Set Name der DB-Tabelle. @param TableName Name der DB-Tabelle */ @Override public void setTableName (java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } /** Get Name der DB-Tabelle. @return Name der DB-Tabelle */ @Override public java.lang.String getTableName () { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationStep.java
1
请在Spring Boot框架中完成以下Java代码
public class AccountBizException extends BizException { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(AccountBizException.class); public static final AccountBizException ACCOUNT_NOT_EXIT = new AccountBizException(10010001, "账户不存在"); public static final AccountBizException ACCOUNT_SUB_AMOUNT_OUTLIMIT = new AccountBizException(10010002, "余额不足,减款超限"); public static final AccountBizException ACCOUNT_UN_FROZEN_AMOUNT_OUTLIMIT = new AccountBizException(10010003, "解冻金额超限"); public static final AccountBizException ACCOUNT_FROZEN_AMOUNT_OUTLIMIT = new AccountBizException(10010004, "冻结金额超限"); public static final AccountBizException ACCOUNT_TYPE_IS_NULL = new AccountBizException(10010005, "账户类型不能为空"); public AccountBizException() { } public AccountBizException(int code, String msgFormat, Object... args) { super(code, msgFormat, args); } public AccountBizException(int code, String msg) { super(code, msg);
} /** * 实例化异常 * * @param msgFormat * @param args * @return */ public AccountBizException newInstance(String msgFormat, Object... args) { return new AccountBizException(this.code, msgFormat, args); } public AccountBizException print() { logger.info("==>BizException, code:" + this.code + ", msg:" + this.msg); return this; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\exception\AccountBizException.java
2
请在Spring Boot框架中完成以下Java代码
private class JwtCsrfValidatorFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // NOTE: A real implementation should have a nonce cache so the token cannot be reused CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); if ( // only care if it's a POST "POST".equals(request.getMethod()) && // ignore if the request path is in our list Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && // make sure we have a token token != null) { // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
try { Jwts.parser() .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(token.getToken()); } catch (JwtException e) { // most likely an ExpiredJwtException, but this will handle any request.setAttribute("exception", e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); RequestDispatcher dispatcher = request.getRequestDispatcher("expired-jwt"); dispatcher.forward(request, response); } } filterChain.doFilter(request, response); } } }
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\config\WebSecurityConfig.java
2
请完成以下Java代码
public MessagePayloadMappingProvider getMessagePayloadMappingProvider() { return messagePayloadMappingProvider; } protected String evaluateExpression(String expression, DelegateExecution execution) { return Optional.ofNullable(expressionManager.createExpression(expression)) .map(it -> it.getValue(execution)) .map(Object::toString) .orElseThrow(() -> new ActivitiIllegalArgumentException("Expression '" + expression + "' is null")); } protected void assertNoExistingDuplicateEventSubscriptions( String messageName, String correlationKey, CommandContext commandContext ) { List<EventSubscriptionEntity> existing = commandContext
.getEventSubscriptionEntityManager() .findEventSubscriptionsByName("message", messageName, null); existing .stream() .filter(subscription -> Objects.equals(subscription.getConfiguration(), correlationKey)) .findFirst() .ifPresent(subscription -> { throw new ActivitiIllegalArgumentException( "Duplicate message subscription '" + subscription.getEventName() + "' with correlation key '" + subscription.getConfiguration() + "'" ); }); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultMessageExecutionContext.java
1
请完成以下Java代码
public List<Exception> doExport() { final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); final I_C_Invoice document = getDocument(); final List<Exception> feedback = ediDocumentBL.isValidInvoice(document); final String EDIStatus = document.getEDI_ExportStatus(); final ValidationState validationState = ediDocumentBL.updateInvalid(document, EDIStatus, feedback, true); // saveLocally=true if (ValidationState.ALREADY_VALID != validationState) { // otherwise, it's either INVALID, or freshly updated (which, keeping the old logic, must be dealt with in one more step) return feedback; } assertEligible(document); // Mark the invoice as: EDI starting document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_SendingStarted); InterfaceWrapperHelper.save(document); try {
exportEDI(I_EDI_cctop_invoic_v.class, C_InvoiceExport.CST_INVOICE_EXP_FORMAT, I_EDI_cctop_invoic_v.Table_Name, I_EDI_cctop_invoic_v.COLUMNNAME_C_Invoice_ID); } catch (final Exception e) { document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_Error); final ITranslatableString errorMsgTrl = TranslatableStrings.parse(e.getLocalizedMessage()); document.setEDIErrorMsg(errorMsgTrl.translate(Env.getAD_Language())); InterfaceWrapperHelper.save(document); throw AdempiereException .wrapIfNeeded(e) .markAsUserValidationError(); } return Collections.emptyList(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\impl\C_InvoiceExport.java
1
请完成以下Java代码
public class MyDto { private String stringValue; private int intValue; private boolean booleanValue; public MyDto() { super(); } public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { super(); this.stringValue = stringValue; this.intValue = intValue; this.booleanValue = booleanValue; } // API public String getStringValue() { return stringValue; } public void setStringValue(final String stringValue) { this.stringValue = stringValue; } public int getIntValue() { return intValue;
} public void setIntValue(final int intValue) { this.intValue = intValue; } public boolean isBooleanValue() { return booleanValue; } public void setBooleanValue(final boolean booleanValue) { this.booleanValue = booleanValue; } // @Override public String toString() { return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; } }
repos\tutorials-master\jackson-modules\jackson-annotations-2\src\main\java\com\baeldung\jackson\jsonproperty\MyDto.java
1
请完成以下Java代码
public ClientId getClientId() { return ClientId.ofRepoId(po.getAD_Client_ID()); } @Override public OrgId getOrgId() {return OrgId.ofRepoId(po.getAD_Org_ID());} @Override public UserId getUpdatedBy() {return UserId.ofRepoIdOrSystem(po.getUpdatedBy());} @Override @Nullable public DocStatus getDocStatus() { final int index = po.get_ColumnIndex("DocStatus"); return index >= 0 ? DocStatus.ofNullableCodeOrUnknown((String)po.get_Value(index)) : null; } @Override public boolean isProcessing() {return po.get_ValueAsBoolean("Processing");} @Override public boolean isProcessed() {return po.get_ValueAsBoolean("Processed");} @Override public boolean isActive() {return po.isActive();} @Override public PostingStatus getPostingStatus() {return PostingStatus.ofNullableCode(po.get_ValueAsString("Posted"));} @Override public boolean hasColumnName(final String columnName) {return po.getPOInfo().hasColumnName(columnName);} @Override public int getValueAsIntOrZero(final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Integer ii = (Integer)po.get_Value(index); if (ii != null) { return ii; } } return 0; } @Override @Nullable public <T extends RepoIdAware> T getValueAsIdOrNull(final String columnName, final IntFunction<T> idOrNullMapper) { final int index = po.get_ColumnIndex(columnName); if (index < 0) { return null; } final Object valueObj = po.get_Value(index); final Integer valueInt = NumberUtils.asInteger(valueObj, null); if (valueInt == null) {
return null; } return idOrNullMapper.apply(valueInt); } @Override @Nullable public LocalDateAndOrgId getValueAsLocalDateOrNull(@NonNull final String columnName, @NonNull final Function<OrgId, ZoneId> timeZoneMapper) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Timestamp ts = po.get_ValueAsTimestamp(index); if (ts != null) { final OrgId orgId = OrgId.ofRepoId(po.getAD_Org_ID()); return LocalDateAndOrgId.ofTimestamp(ts, orgId, timeZoneMapper); } } return null; } @Override @Nullable public Boolean getValueAsBooleanOrNull(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return DisplayType.toBoolean(valueObj, null); } return null; } @Override @Nullable public String getValueAsString(@NonNull final String columnName) { final int index = po.get_ColumnIndex(columnName); if (index != -1) { final Object valueObj = po.get_Value(index); return valueObj != null ? valueObj.toString() : null; } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\POAcctDocModel.java
1
请在Spring Boot框架中完成以下Java代码
public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setOpenAmt (final BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } @Override public BigDecimal getOpenAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPaidAmt (final BigDecimal PaidAmt) { set_Value (COLUMNNAME_PaidAmt, PaidAmt); } @Override public BigDecimal getPaidAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PaidAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); }
@Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } /** * Status AD_Reference_ID=541890 * Reference name: C_POS_Order_Status */ public static final int STATUS_AD_Reference_ID=541890; /** Drafted = DR */ public static final String STATUS_Drafted = "DR"; /** WaitingPayment = WP */ public static final String STATUS_WaitingPayment = "WP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; /** Voided = VO */ public static final String STATUS_Voided = "VO"; /** Closed = CL */ public static final String STATUS_Closed = "CL"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java
2
请完成以下Java代码
public class TaxForChangeNotFoundException extends AdempiereException { /** * */ private static final long serialVersionUID = 6553174922970467775L; private static final String AD_Message = "TaxForChargeNotFound"; // TODO : translate public TaxForChangeNotFoundException(int C_Charge_ID, int AD_Org_ID, int M_Warehouse_ID, int billC_BPartner_Location_ID, int shipC_BPartner_Location_ID, String additionalMsg) { super(buildMessage(C_Charge_ID, AD_Org_ID, M_Warehouse_ID, billC_BPartner_Location_ID, shipC_BPartner_Location_ID, additionalMsg)); }
private static final String buildMessage(int C_Charge_ID, int AD_Org_ID, int M_Warehouse_ID, int billC_BPartner_Location_ID, int shipC_BPartner_Location_ID, String additionalMsg) { StringBuffer msg = new StringBuffer("@").append(AD_Message).append("@"); if (!Check.isEmpty(additionalMsg, true)) { msg.append(" ").append(additionalMsg).append(" - "); } msg.append(" @C_Charge_ID@:").append(C_Charge_ID); msg.append(", @AD_Org_ID@:").append(AD_Org_ID); msg.append(", @M_Warehouse_ID@:").append(M_Warehouse_ID); msg.append(", @C_BPartner_Location_ID@:").append(billC_BPartner_Location_ID) .append("/").append(shipC_BPartner_Location_ID); // return msg.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\TaxForChangeNotFoundException.java
1
请完成以下Java代码
public static List<AttributesKeyMatcher> extractAttributesKeyMatchers(@NonNull final List<AttributesKeyPattern> patterns) { if (patterns.isEmpty()) { return ImmutableList.of(matchingAll()); } else if (!patterns.contains(AttributesKeyPattern.OTHER)) { return patterns.stream() .map(AttributesKeyPatternsUtil::matching) .collect(ImmutableList.toImmutableList()); } else { final ImmutableSet<AttributesKeyMatcher> otherMatchers = patterns.stream() .filter(AttributesKeyPattern::isSpecific) .map(AttributesKeyPatternsUtil::matching) .collect(ImmutableSet.toImmutableSet()); final AttributesKeyMatcher othersMatcher = ExcludeAttributesKeyMatcher.of(otherMatchers); return patterns.stream() .map(pattern -> pattern.isOther() ? othersMatcher : matching(pattern)) .collect(ImmutableList.toImmutableList()); } } public static AttributesKeyMatcher matchingAll() {
return AcceptAllAttributesKeyMatcher.instance; } public static AttributesKeyMatcher matching(@NonNull final AttributesKeyPattern pattern) { if (pattern.isAll()) { return AcceptAllAttributesKeyMatcher.instance; } return StandardAttributesKeyPatternMatcher.of(pattern); } public static AttributesKeyMatcher matching(@NonNull final AttributesKey attributesKey) { return matching(ofAttributeKey(attributesKey)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPatternsUtil.java
1
请在Spring Boot框架中完成以下Java代码
public OidcProviderConfigurationEndpointConfigurer providerConfigurationCustomizer( Consumer<OidcProviderConfiguration.Builder> providerConfigurationCustomizer) { this.providerConfigurationCustomizer = providerConfigurationCustomizer; return this; } void addDefaultProviderConfigurationCustomizer( Consumer<OidcProviderConfiguration.Builder> defaultProviderConfigurationCustomizer) { this.defaultProviderConfigurationCustomizer = (this.defaultProviderConfigurationCustomizer == null) ? defaultProviderConfigurationCustomizer : this.defaultProviderConfigurationCustomizer.andThen(defaultProviderConfigurationCustomizer); } @Override void init(HttpSecurity httpSecurity) { AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils .getAuthorizationServerSettings(httpSecurity); String oidcProviderConfigurationEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed() ? "/**/.well-known/openid-configuration" : "/.well-known/openid-configuration"; this.requestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, oidcProviderConfigurationEndpointUri); } @Override void configure(HttpSecurity httpSecurity) { OidcProviderConfigurationEndpointFilter oidcProviderConfigurationEndpointFilter = new OidcProviderConfigurationEndpointFilter(); Consumer<OidcProviderConfiguration.Builder> providerConfigurationCustomizer = getProviderConfigurationCustomizer(); if (providerConfigurationCustomizer != null) { oidcProviderConfigurationEndpointFilter.setProviderConfigurationCustomizer(providerConfigurationCustomizer); } httpSecurity.addFilterBefore(postProcess(oidcProviderConfigurationEndpointFilter), AbstractPreAuthenticatedProcessingFilter.class); }
private Consumer<OidcProviderConfiguration.Builder> getProviderConfigurationCustomizer() { Consumer<OidcProviderConfiguration.Builder> providerConfigurationCustomizer = null; if (this.defaultProviderConfigurationCustomizer != null || this.providerConfigurationCustomizer != null) { if (this.defaultProviderConfigurationCustomizer != null) { providerConfigurationCustomizer = this.defaultProviderConfigurationCustomizer; } if (this.providerConfigurationCustomizer != null) { providerConfigurationCustomizer = (providerConfigurationCustomizer != null) ? providerConfigurationCustomizer.andThen(this.providerConfigurationCustomizer) : this.providerConfigurationCustomizer; } } return providerConfigurationCustomizer; } @Override RequestMatcher getRequestMatcher() { return this.requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OidcProviderConfigurationEndpointConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public final class ObservationAutoConfiguration { @Bean static ObservationRegistryPostProcessor observationRegistryPostProcessor( ObjectProvider<ObservationRegistryCustomizer<?>> observationRegistryCustomizers, ObjectProvider<ObservationPredicate> observationPredicates, ObjectProvider<GlobalObservationConvention<?>> observationConventions, ObjectProvider<ObservationHandler<?>> observationHandlers, ObjectProvider<ObservationHandlerGroup> observationHandlerGroups, ObjectProvider<ObservationFilter> observationFilters) { return new ObservationRegistryPostProcessor(observationRegistryCustomizers, observationPredicates, observationConventions, observationHandlers, observationHandlerGroups, observationFilters); } @Bean @ConditionalOnMissingBean ObservationRegistry observationRegistry() { return ObservationRegistry.create(); } @Bean @Order(0) PropertiesObservationFilterPredicate propertiesObservationFilter(ObservationProperties properties) { return new PropertiesObservationFilterPredicate(properties); } @Bean @ConditionalOnMissingBean(ValueExpressionResolver.class) SpelValueExpressionResolver spelValueExpressionResolver() { return new SpelValueExpressionResolver(); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(Advice.class) @ConditionalOnBooleanProperty("management.observations.annotations.enabled") static class ObservedAspectConfiguration { @Bean
@ConditionalOnMissingBean ObservedAspect observedAspect(ObservationRegistry observationRegistry, ObjectProvider<ObservationKeyValueAnnotationHandler> observationKeyValueAnnotationHandler) { ObservedAspect observedAspect = new ObservedAspect(observationRegistry); observationKeyValueAnnotationHandler.ifAvailable(observedAspect::setObservationKeyValueAnnotationHandler); return observedAspect; } @Bean @ConditionalOnMissingBean ObservationKeyValueAnnotationHandler observationKeyValueAnnotationHandler(BeanFactory beanFactory, ValueExpressionResolver valueExpressionResolver) { return new ObservationKeyValueAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationAutoConfiguration.java
2
请完成以下Java代码
public HierarchyBuilder addChildren(final HierarchyNode parent, final Collection<HierarchyNode> children) { beneficiary2Node.put(parent.getBeneficiary(), parent); children.forEach(child -> beneficiary2Node.put(child.getBeneficiary(), child)); parent2Children.putAll(parent, children); return this; } public Hierarchy build() { return new Hierarchy( ImmutableMap.copyOf(beneficiary2Node), parent2Children.build()); } } /** * @return the given {@code beneficiary}'s node, followed by its parent, grandparent and so on. */ public Iterable<HierarchyNode> getUpStream(@NonNull final Beneficiary beneficiary) { final HierarchyNode node = beneficiary2Node.get(beneficiary); if (node == null) { throw new AdempiereException("Beneficiary with C_BPartner_ID=" + beneficiary.getBPartnerId().getRepoId() + " is not part of this hierarchy") .appendParametersToMessage() .setParameter("this", this); } return () -> new ParentNodeIterator(child2Parent, node); } public static class ParentNodeIterator implements Iterator<HierarchyNode> { private final ImmutableMap<HierarchyNode, HierarchyNode> child2Parent; private HierarchyNode next; private HierarchyNode previous; private ParentNodeIterator( @NonNull final ImmutableMap<HierarchyNode, HierarchyNode> childAndParent, @NonNull final HierarchyNode first) { this.child2Parent = childAndParent; this.next = first; }
@Override public boolean hasNext() { return next != null; } @Override public HierarchyNode next() { final HierarchyNode result = next; if (result == null) { throw new NoSuchElementException("Previous HierarchyNode=" + previous + " had no parent"); } previous = next; next = child2Parent.get(next); return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\hierarchy\Hierarchy.java
1
请完成以下Java代码
public class SaveProcessDefinitionInfoCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String processDefinitionId; protected ObjectNode infoNode; public SaveProcessDefinitionInfoCmd(String processDefinitionId, ObjectNode infoNode) { this.processDefinitionId = processDefinitionId; this.infoNode = infoNode; } @Override public Void execute(CommandContext commandContext) { if (processDefinitionId == null) { throw new FlowableIllegalArgumentException("process definition id is null"); } if (infoNode == null) { throw new FlowableIllegalArgumentException("process definition info node is null");
} ProcessDefinitionInfoEntityManager definitionInfoEntityManager = CommandContextUtil.getProcessDefinitionInfoEntityManager(commandContext); ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); if (definitionInfoEntity == null) { definitionInfoEntity = definitionInfoEntityManager.create(); definitionInfoEntity.setProcessDefinitionId(processDefinitionId); CommandContextUtil.getProcessDefinitionInfoEntityManager().insertProcessDefinitionInfo(definitionInfoEntity); } try { ObjectWriter writer = CommandContextUtil.getProcessEngineConfiguration(commandContext).getObjectMapper().writer(); CommandContextUtil.getProcessDefinitionInfoEntityManager().updateInfoJson(definitionInfoEntity.getId(), writer.writeValueAsBytes(infoNode)); } catch (Exception e) { throw new FlowableException("Unable to serialize info node " + infoNode, e); } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SaveProcessDefinitionInfoCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class DDOrderLineQuickInputCallout { private final PackingItemProductFieldHelper packingItemProductFieldHelper; public DDOrderLineQuickInputCallout(final PackingItemProductFieldHelper packingItemProductFieldHelper) { this.packingItemProductFieldHelper = packingItemProductFieldHelper; } public void onProductChange(@NonNull final ICalloutField calloutField) { final QuickInput quickInput = QuickInput.getQuickInputOrNull(calloutField); if (quickInput == null) { return; } boolean isPackingInstructionFieldMissing = !quickInput.hasField(IDDOrderLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID); if (isPackingInstructionFieldMissing) { return; } final IDDOrderLineQuickInput ddOrderLineQuickInput = quickInput.getQuickInputDocumentAs(IDDOrderLineQuickInput.class); final ProductId productId = ProductId.ofRepoIdOrNull( ddOrderLineQuickInput.getM_Product_ID() ); if ( productId == null) { return; } final I_DD_Order ddOrder = quickInput.getRootDocumentAs(I_DD_Order.class); final I_M_HU_PI_Item_Product defaultPackingItem = getDefaultPI(ddOrder, productId); if (defaultPackingItem != null) { ddOrderLineQuickInput.setM_HU_PI_Item_Product_ID(defaultPackingItem.getM_HU_PI_Item_Product_ID());
} } @Nullable private I_M_HU_PI_Item_Product getDefaultPI(@NonNull final I_DD_Order ddOrder, @NonNull final ProductId productId) { final BPartnerLocationAndCaptureId bpartnerLocationId = BPartnerLocationAndCaptureId.ofRepoIdOrNull(ddOrder.getC_BPartner_ID(), ddOrder.getC_BPartner_Location_ID()); final ZonedDateTime date = TimeUtil.asZonedDateTime(ddOrder.getDateOrdered()); final ClientId clientId = ClientId.ofRepoId(ddOrder.getAD_Client_ID()); final DefaultPackingItemCriteria defaultPackingItemCriteria = DefaultPackingItemCriteria .builder() .productId(productId) .bPartnerLocationId(bpartnerLocationId) .date(date) .clientId(clientId) .build(); return packingItemProductFieldHelper.getDefaultPackingMaterial(defaultPackingItemCriteria).orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\ddorderline\DDOrderLineQuickInputCallout.java
2
请在Spring Boot框架中完成以下Java代码
public String getOperatorLoginname() { return operatorLoginname; } /** * 操作员登录名 * * @param operatorLoginname */ public void setOperatorLoginname(String operatorLoginname) { this.operatorLoginname = operatorLoginname == null ? null : operatorLoginname.trim(); } /** * 操作员姓名 * * @return */ public String getOperatorRealname() { return operatorRealname;
} /** * 操作员姓名 * * @param operatorRealname */ public void setOperatorRealname(String operatorRealname) { this.operatorRealname = operatorRealname == null ? null : operatorRealname.trim(); } public String getSettStatusDesc() { return SettRecordStatusEnum.getEnum(this.getSettStatus()).getDesc(); } public String getCreateTimeDesc() { return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss"); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettRecord.java
2
请完成以下Java代码
public final String toString() { return interceptor.toString(); } @Override public final int hashCode() { return interceptor.hashCode(); } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof ModelInterceptor2ModelValidatorWrapper) { final ModelInterceptor2ModelValidatorWrapper wrapper = (ModelInterceptor2ModelValidatorWrapper)obj; return interceptor.equals(wrapper.interceptor); } else if (obj instanceof IModelInterceptor) { final IModelInterceptor interceptor2 = (IModelInterceptor)obj; return interceptor.equals(interceptor2); } return false; } @Override public final void initialize(final ModelValidationEngine engine, final MClient client) { interceptor.initialize(engine, client); } @Override public final int getAD_Client_ID() { return interceptor.getAD_Client_ID(); } @Override public final String modelChange(final PO po, final int changeTypeCode) throws Exception { final ModelChangeType changeType = ModelChangeType.valueOf(changeTypeCode); interceptor.onModelChange(po, changeType); return null; } @Override public final String docValidate(final PO po, final int timingCode) throws Exception
{ final DocTimingType timing = DocTimingType.valueOf(timingCode); interceptor.onDocValidate(po, timing); return null; } @Override public final String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); return null; } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); } @Override public void beforeLogout(final MFSession session) { if (userLoginListener != null) { userLoginListener.beforeLogout(session); } } @Override public void afterLogout(final MFSession session) { if (userLoginListener != null) { userLoginListener.afterLogout(session); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelInterceptor2ModelValidatorWrapper.java
1
请完成以下Java代码
public void send(@Nullable String exchange, @Nullable String routingKey, Message message, @Nullable CorrelationData correlationData) throws AmqpException { this.lock.lock(); try { if (correlationData != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Cannot use batching with correlation data"); } super.send(exchange, routingKey, message, correlationData); } else { if (this.scheduledTask != null) { this.scheduledTask.cancel(false); } MessageBatch batch = this.batchingStrategy.addToBatch(exchange, routingKey, message); if (batch != null) { super.send(batch.exchange(), batch.routingKey(), batch.message(), null); } Date next = this.batchingStrategy.nextRelease(); if (next != null) { this.scheduledTask = this.scheduler.schedule(this::releaseBatches, next.toInstant()); } } } finally { this.lock.unlock(); } } /** * Flush any partial in-progress batches. */ public void flush() { releaseBatches(); }
private void releaseBatches() { this.lock.lock(); try { for (MessageBatch batch : this.batchingStrategy.releaseBatches()) { super.send(batch.exchange(), batch.routingKey(), batch.message(), null); } } finally { this.lock.unlock(); } } @Override public void doStart() { } @Override public void doStop() { flush(); } @Override public boolean isRunning() { return true; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BatchingRabbitTemplate.java
1
请完成以下Java代码
public void onDateDoc(final I_SAP_GLJournal glJournal) { final Timestamp dateDoc = glJournal.getDateDoc(); if (dateDoc == null) { return; } glJournal.setDateAcct(dateDoc); } @CalloutMethod(columnNames = { I_SAP_GLJournal.COLUMNNAME_DateAcct, I_SAP_GLJournal.COLUMNNAME_Acct_Currency_ID, I_SAP_GLJournal.COLUMNNAME_C_Currency_ID, I_SAP_GLJournal.COLUMNNAME_C_ConversionType_ID }) public void updateCurrencyRate(final I_SAP_GLJournal glJournal) { final BigDecimal currencyRate = computeCurrencyRate(glJournal); if (currencyRate == null) { return; } glJournal.setCurrencyRate(currencyRate); } @Nullable private BigDecimal computeCurrencyRate(final I_SAP_GLJournal glJournal) { // // Extract data from source Journal final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID()); if (currencyId == null) { // not set yet return null; } final CurrencyId acctCurrencyId = CurrencyId.ofRepoIdOrNull(glJournal.getAcct_Currency_ID()); if (acctCurrencyId == null) { return null; } final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID());
Instant dateAcct = TimeUtil.asInstant(glJournal.getDateAcct()); if (dateAcct == null) { dateAcct = SystemTime.asInstant(); } final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID()); final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID()); return currencyBL.getCurrencyRateIfExists( currencyId, acctCurrencyId, dateAcct, conversionTypeId, adClientId, adOrgId) .map(CurrencyRate::getConversionRate) .orElse(BigDecimal.ZERO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournal.java
1
请完成以下Java代码
public static String stripBpmnFileSuffix(String bpmnFileResource) { for (String suffix : BPMN_RESOURCE_SUFFIXES) { if (bpmnFileResource.endsWith(suffix)) { return bpmnFileResource.substring(0, bpmnFileResource.length() - suffix.length()); } } return bpmnFileResource; } public static String getProcessDiagramResourceName( String bpmnFileResource, String processKey, String diagramSuffix ) { String bpmnFileResourceBase = ResourceNameUtil.stripBpmnFileSuffix(bpmnFileResource); return bpmnFileResourceBase + processKey + "." + diagramSuffix; } /** * Finds the name of a resource for the diagram for a process definition. Assumes that the * process definition's key and (BPMN) resource name are already set. * * <p>It will first look for an image resource which matches the process specifically, before * resorting to an image resource which matches the BPMN 2.0 xml file resource. * * <p>Example: if the deployment contains a BPMN 2.0 xml resource called 'abc.bpmn20.xml' * containing only one process with key 'myProcess', then this method will look for an image resources * called'abc.myProcess.png' (or .jpg, or .gif, etc.) or 'abc.png' if the previous one wasn't * found. * * <p>Example 2: if the deployment contains a BPMN 2.0 xml resource called 'abc.bpmn20.xml' * containing three processes (with keys a, b and c), then this method will first look for an image resource * called 'abc.a.png' before looking for 'abc.png' (likewise for b and c). Note that if abc.a.png, * abc.b.png and abc.c.png don't exist, all processes will have the same image: abc.png. *
* @return name of an existing resource, or null if no matching image resource is found in the resources. */ public static String getProcessDiagramResourceNameFromDeployment( ProcessDefinitionEntity processDefinition, Map<String, ResourceEntity> resources ) { if (StringUtils.isEmpty(processDefinition.getResourceName())) { throw new IllegalStateException("Provided process definition must have its resource name set."); } String bpmnResourceBase = stripBpmnFileSuffix(processDefinition.getResourceName()); String key = processDefinition.getKey(); for (String diagramSuffix : DIAGRAM_SUFFIXES) { String possibleName = bpmnResourceBase + key + "." + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } possibleName = bpmnResourceBase + diagramSuffix; if (resources.containsKey(possibleName)) { return possibleName; } } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\ResourceNameUtil.java
1
请完成以下Java代码
public void setA_Period (int A_Period) { set_Value (COLUMNNAME_A_Period, Integer.valueOf(A_Period)); } /** Get Period/Yearly. @return Period/Yearly */ public int getA_Period () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Period); if (ii == null) return 0; return ii.intValue(); } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Expense. @param Expense Expense */ public void setExpense (BigDecimal Expense) { set_Value (COLUMNNAME_Expense, Expense); } /** Get Expense. @return Expense */ public BigDecimal getExpense () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Expense); if (bd == null) return Env.ZERO; return bd; } /** Set Depreciate. @param IsDepreciated The asset will be depreciated */ public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); } /** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set PostingType. @param PostingType The type of posted amount for the transaction */ public void setPostingType (String PostingType) { set_Value (COLUMNNAME_PostingType, PostingType); } /** Get PostingType. @return The type of posted amount for the transaction */ public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Exp.java
1
请在Spring Boot框架中完成以下Java代码
public void pushReports( @RequestHeader("apiKey") final String apiKey, @RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId, @RequestParam(name = "productId", required = false, defaultValue = "0") final long productId, @RequestParam("dateFrom") final String dateFromStr, @RequestParam("dateTo") final String dateToStr) { assertValidApiKey(apiKey); final LocalDate dateFrom = LocalDate.parse(dateFromStr); final LocalDate dateTo = LocalDate.parse(dateToStr); pushDailyReports(bpartnerId, productId, dateFrom, dateTo); pushWeeklyReports(bpartnerId, productId, dateFrom, dateTo); } private void pushDailyReports( final long bpartnerId, final long productId, final LocalDate dateFrom, final LocalDate dateTo) { final List<ProductSupply> productSupplies = productSuppliesService.getProductSupplies( bpartnerId, productId, dateFrom, dateTo); senderToMetasfreshService.pushDailyReportsAsync(productSupplies); }
private void pushWeeklyReports( final long bpartnerId, final long productId, final LocalDate dateFrom, final LocalDate dateTo) { final List<WeekSupply> records = productSuppliesService.getWeeklySupplies( bpartnerId, productId, dateFrom, dateTo); senderToMetasfreshService.pushWeeklyReportsAsync(records); } @GetMapping("/pushActiveRfQs") public void pushActiveRfQs( @RequestHeader("apiKey") final String apiKey, @RequestParam(name = "bpartnerId", required = false, defaultValue = "0") final long bpartnerId) { assertValidApiKey(apiKey); final BPartner bpartner = bpartnerId > 0 ? bpartnersRepository.getOne(bpartnerId) : null; final List<Rfq> rfqs = rfqService.getActiveRfqs(bpartner); senderToMetasfreshService.pushRfqsAsync(rfqs); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\MetasfreshSyncRestController.java
2