instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public int getCarrier_ShipmentOrder_Log_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Log_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestID (final java.lang.String RequestID) { set_Value (COLUMNNAME_RequestID, RequestID); } @Override public java.lang.String getRequestID()
{ return get_ValueAsString(COLUMNNAME_RequestID); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); } @Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Log.java
1
请完成以下Java代码
public void setup() { map = new HashMap<>(); iterableMap = new HashedMap<>(); mutableMap = UnifiedMap.newMap(); for (int i = 0; i < size; i++) { map.put(i, i); iterableMap.put(i, i); mutableMap.put(i, i); } } @Benchmark public long iterateUsingIteratorAndValues() { return mapIteration.iterateUsingIteratorAndValues(map); } @Benchmark public long iterateUsingEnhancedForLoopAndEntrySet() { return mapIteration.iterateUsingEnhancedForLoopAndEntrySet(map); } @Benchmark public long iterateByKeysUsingLambdaAndForEach() { return mapIteration.iterateByKeysUsingLambdaAndForEach(map); } @Benchmark public long iterateValuesUsingLambdaAndForEach() { return mapIteration.iterateValuesUsingLambdaAndForEach(map); } @Benchmark public long iterateUsingIteratorAndKeySet() { return mapIteration.iterateUsingIteratorAndKeySet(map); } @Benchmark public long iterateUsingIteratorAndEntrySet() { return mapIteration.iterateUsingIteratorAndEntrySet(map); } @Benchmark public long iterateUsingKeySetAndEnhanceForLoop() { return mapIteration.iterateUsingKeySetAndEnhanceForLoop(map); }
@Benchmark public long iterateUsingStreamAPIAndEntrySet() { return mapIteration.iterateUsingStreamAPIAndEntrySet(map); } @Benchmark public long iterateUsingStreamAPIAndKeySet() { return mapIteration.iterateUsingStreamAPIAndKeySet(map); } @Benchmark public long iterateKeysUsingKeySetAndEnhanceForLoop() { return mapIteration.iterateKeysUsingKeySetAndEnhanceForLoop(map); } @Benchmark public long iterateUsingMapIteratorApacheCollection() { return mapIteration.iterateUsingMapIteratorApacheCollection(iterableMap); } @Benchmark public long iterateEclipseMap() throws IOException { return mapIteration.iterateEclipseMap(mutableMap); } @Benchmark public long iterateMapUsingParallelStreamApi() throws IOException { return mapIteration.iterateMapUsingParallelStreamApi(map); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\iteration\MapIterationBenchmark.java
1
请完成以下Java代码
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) { Optional<State> newState = currentStackList.stream() .filter(stack -> stack != currentStack) .map(stack -> { return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack); }) .filter(Objects::nonNull) .findFirst(); return newState.orElse(null); } /** * This method pushes a block to the stack and returns new state if its closer to goal */ private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) { stack.push(block); int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack); if (newStateHeuristics > currentStateHeuristics) { return new State(currentStackList, newStateHeuristics); } stack.pop(); return null; } /** * This method returns heuristics value for given state with respect to goal * state */ public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) { Integer heuristicValue; heuristicValue = currentState.stream() .mapToInt(stack -> { return getHeuristicsValueForStack(stack, currentState, goalStateStack);
}) .sum(); return heuristicValue; } /** * This method returns heuristics value for a particular stack */ public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) { int stackHeuristics = 0; boolean isPositioneCorrect = true; int goalStartIndex = 0; for (String currentBlock : stack) { if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) { stackHeuristics += goalStartIndex; } else { stackHeuristics -= goalStartIndex; isPositioneCorrect = false; } goalStartIndex++; } return stackHeuristics; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\hillclimbing\HillClimbing.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Character getGender() { return gender; } public void setGender(Character gender) { this.gender = gender; } public Date getBirthDate() {
return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Float getPercentage() { return percentage; } public void setPercentage(Float percentage) { this.percentage = percentage; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\model\Student.java
1
请在Spring Boot框架中完成以下Java代码
public boolean hasAllocationsForSlot(@NonNull final PickingSlotId slotId) { return pickingJobRepository.hasDraftJobsUsingPickingSlot(slotId, null); } public void addToPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIds) { pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIds); } public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final Set<DocumentLocation> deliveryLocations) { if (deliveryLocations.isEmpty()) { return PickingSlotSuggestions.EMPTY; } final ImmutableMap<BPartnerLocationId, DocumentLocation> deliveryLocationsById = Maps.uniqueIndex(deliveryLocations, DocumentLocation::getBpartnerLocationId); final List<I_M_PickingSlot> pickingSlots = pickingSlotService.list(PickingSlotQuery.builder().assignedToBPartnerLocationIds(deliveryLocationsById.keySet()).build()); if (pickingSlots.isEmpty()) { return PickingSlotSuggestions.EMPTY; } final PickingSlotQueuesSummary queues = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(extractPickingSlotIds(pickingSlots))); return pickingSlots.stream() .map(pickingSlotIdAndCaption -> toPickingSlotSuggestion(pickingSlotIdAndCaption, deliveryLocationsById, queues)) .collect(PickingSlotSuggestions.collect()); } private static PickingSlotSuggestion toPickingSlotSuggestion( @NonNull final I_M_PickingSlot pickingSlot, @NonNull final ImmutableMap<BPartnerLocationId, DocumentLocation> deliveryLocationsById, @NonNull final PickingSlotQueuesSummary queues) { final PickingSlotIdAndCaption pickingSlotIdAndCaption = toPickingSlotIdAndCaption(pickingSlot);
final BPartnerLocationId deliveryLocationId = BPartnerLocationId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID(), pickingSlot.getC_BPartner_Location_ID()); final DocumentLocation deliveryLocation = deliveryLocationsById.get(deliveryLocationId); return PickingSlotSuggestion.builder() .pickingSlotIdAndCaption(pickingSlotIdAndCaption) .deliveryLocation(deliveryLocation) .countHUs(queues.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0)) .build(); } private static ImmutableSet<PickingSlotId> extractPickingSlotIds(final List<I_M_PickingSlot> pickingSlots) { return pickingSlots.stream() .map(pickingSlot -> PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID())) .collect(ImmutableSet.toImmutableSet()); } private static PickingSlotIdAndCaption toPickingSlotIdAndCaption(@NonNull final I_M_PickingSlot record) { return PickingSlotIdAndCaption.of(PickingSlotId.ofRepoId(record.getM_PickingSlot_ID()), record.getPickingSlot()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobSlotService.java
2
请完成以下Java代码
public CarrierProduct getOrCreateCarrierProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name) { final CarrierProduct cachedShipperProductByCode = getCachedShipperProductByCode(shipperId, code); if (cachedShipperProductByCode != null) { return cachedShipperProductByCode; } return createShipperProduct(shipperId, code, name); } @Nullable private CarrierProduct getCachedShipperProductByCode(@NonNull final ShipperId shipperId, @Nullable final String code) { if (code == null) { return null; } return carrierProductsByExternalId.getOrLoad(shipperId + code, () -> queryBL.createQueryBuilder(I_Carrier_Product.class) .addEqualsFilter(I_Carrier_Product.COLUMNNAME_M_Shipper_ID, shipperId) .addEqualsFilter(I_Carrier_Product.COLUMNNAME_ExternalId, code) .firstOptional() .map(CarrierProductRepository::fromProductRecord) .orElse(null)); } @Nullable public CarrierProduct getCachedShipperProductById(@Nullable final CarrierProductId productId) { if (productId == null) { return null; } return carrierProductsById.getOrLoad(productId.toString(), () -> queryBL.createQueryBuilder(I_Carrier_Product.class) .addEqualsFilter(I_Carrier_Product.COLUMNNAME_Carrier_Product_ID, productId) .firstOptional()
.map(CarrierProductRepository::fromProductRecord) .orElse(null)); } @NonNull private CarrierProduct createShipperProduct(@NonNull final ShipperId shipperId, @NonNull final String code, @NonNull final String name) { final I_Carrier_Product po = InterfaceWrapperHelper.newInstance(I_Carrier_Product.class); po.setM_Shipper_ID(shipperId.getRepoId()); po.setExternalId(code); po.setName(name); InterfaceWrapperHelper.saveRecord(po); return fromProductRecord(po); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierProductRepository.java
1
请完成以下Java代码
protected List<Fact> createFacts(final AcctSchema as) { if (!AcctSchemaId.equals(as.getId(), costRevaluation.getAcctSchemaId())) { return ImmutableList.of(); } setC_Currency_ID(as.getCurrencyId()); final Fact fact = new Fact(this, as, PostingType.Actual); getDocLines().forEach(line -> createFactsForLine(fact, line)); return ImmutableList.of(fact); } private void createFactsForLine(@NonNull final Fact fact, @NonNull final DocLine_CostRevaluation docLine) { final AcctSchema acctSchema = fact.getAcctSchema(); final CostAmount costs = docLine.getCreateCosts(acctSchema); // // Revenue // ------------------- // Product Asset DR // Revenue CR if (costs.signum() >= 0) { fact.createLine() .setDocLine(docLine) .setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema)) .setAmtSource(costs, null) // .locatorId(line.getM_Locator_ID()) // N/A atm .buildAndAdd();
fact.createLine() .setDocLine(docLine) .setAccount(docLine.getAccount(ProductAcctType.P_Revenue_Acct, acctSchema)) .setAmtSource(null, costs) // .locatorId(line.getM_Locator_ID()) // N/A atm .buildAndAdd(); } // // Expense // ------------------------------------ // Product Asset CR // Expense DR else // deltaAmountToBook.signum() < 0 { fact.createLine() .setDocLine(docLine) .setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema)) .setAmtSource(null, costs.negate()) // .locatorId(line.getM_Locator_ID()) // N/A atm .buildAndAdd(); fact.createLine() .setDocLine(docLine) .setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema)) .setAmtSource(costs.negate(), null) // .locatorId(line.getM_Locator_ID()) // N/A atm .buildAndAdd(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_CostRevaluation.java
1
请完成以下Java代码
public void setF_BGOFFICEID(String f_BGOFFICEID) { F_BGOFFICEID = f_BGOFFICEID; } public String getF_INFOMOBIL() { return F_INFOMOBIL; } public void setF_INFOMOBIL(String f_INFOMOBIL) { F_INFOMOBIL = f_INFOMOBIL; } public String getF_INFOMAN() { return F_INFOMAN; } public void setF_INFOMAN(String f_INFOMAN) { F_INFOMAN = f_INFOMAN; } public String getF_LOGPASS() { return F_LOGPASS; } public void setF_LOGPASS(String f_LOGPASS) { F_LOGPASS = f_LOGPASS; } public String getF_STARTDATE() { return F_STARTDATE; } public void setF_STARTDATE(String f_STARTDATE) { F_STARTDATE = f_STARTDATE; } public String getF_STOPDATE() { return F_STOPDATE; } public void setF_STOPDATE(String f_STOPDATE) { F_STOPDATE = f_STOPDATE; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_MEMO() { return F_MEMO; }
public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() { return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; } public Integer getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISPRINTBILL() { return F_ISPRINTBILL; } public void setF_ISPRINTBILL(String f_ISPRINTBILL) { F_ISPRINTBILL = f_ISPRINTBILL; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
1
请完成以下Java代码
public void instanceVariableMultithreading() { executor.execute(() -> { while (run) { // do operation } }); run = false; } /** * WARNING: always avoid this workaround!! */ public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]); holder[0] = 0; System.out.println(sums.sum()); } /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() {
int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0]) .sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请在Spring Boot框架中完成以下Java代码
public Document updatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; return this; } /** * Der Zeitstempel der letzten Änderung * @return updatedAt **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Document document = (Document) o; return Objects.equals(this._id, document._id) && Objects.equals(this.name, document.name) && Objects.equals(this.patientId, document.patientId) && Objects.equals(this.therapyId, document.therapyId) && Objects.equals(this.therapyTypeId, document.therapyTypeId) && Objects.equals(this.archived, document.archived) && Objects.equals(this.createdBy, document.createdBy) && Objects.equals(this.updatedBy, document.updatedBy) && Objects.equals(this.createdAt, document.createdAt) && Objects.equals(this.updatedAt, document.updatedAt); } @Override public int hashCode() { return Objects.hash(_id, name, patientId, therapyId, therapyTypeId, archived, createdBy, updatedBy, createdAt, updatedAt); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Document {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" updatedBy: ").append(toIndentedString(updatedBy)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Document.java
2
请在Spring Boot框架中完成以下Java代码
static class ExplicitType { } @Conditional(PooledDataSourceAvailableCondition.class) static class PooledDataSourceAvailable { } } /** * {@link Condition} to test if a supported connection pool is available. */ static class PooledDataSourceAvailableCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("PooledDataSource"); if (DataSourceBuilder.findType(context.getClassLoader()) != null) { return ConditionOutcome.match(message.foundExactly("supported DataSource")); } return ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll()); } } /** * {@link Condition} to detect when an embedded {@link DataSource} type can be used. * If a pooled {@link DataSource} is available, it will always be preferred to an * {@code EmbeddedDatabase}. */ static class EmbeddedDatabaseCondition extends SpringBootCondition { private static final String DATASOURCE_URL_PROPERTY = "spring.datasource.url"; private static final String EMBEDDED_DATABASE_TYPE = "org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType"; private final SpringBootCondition pooledCondition = new PooledDataSourceCondition(); @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource"); if (hasDataSourceUrlProperty(context)) { return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is set"));
} if (anyMatches(context, metadata, this.pooledCondition)) { return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source")); } if (!ClassUtils.isPresent(EMBEDDED_DATABASE_TYPE, context.getClassLoader())) { return ConditionOutcome .noMatch(message.didNotFind("required class").items(Style.QUOTE, EMBEDDED_DATABASE_TYPE)); } EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType(); if (type == null) { return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll()); } return ConditionOutcome.match(message.found("embedded database").items(type)); } private boolean hasDataSourceUrlProperty(ConditionContext context) { Environment environment = context.getEnvironment(); if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) { try { return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY)); } catch (IllegalArgumentException ex) { // NOTE: This should be PlaceholderResolutionException // Ignore unresolvable placeholder errors } } return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceAutoConfiguration.java
2
请完成以下Java代码
private ToInvoiceExclOverride computeInvoicableQtysPicked() { Check.assume(soTrx.isSales(), "QtyToInvoice should not be calculated based on QtyPicked in a purchase flow. soTrx={}", soTrx); final StockQtyAndUOMQty qtysToInvoiceCalc = computeQtysPicked(); return new ToInvoiceExclOverride( ToInvoiceExclOverride.InvoicedQtys.NOT_SUBTRACTED, qtysToInvoiceCalc, qtysToInvoiceCalc); } private ToInvoiceExclOverride computeInvoicableQtysDelivered() { final StockQtyAndUOMQty qtysToInvoiceRaw; final StockQtyAndUOMQty qtysToInvoiceCalc; if (soTrx.isSales()) { qtysToInvoiceRaw = deliveredData.getShipmentData().computeInvoicableQtyDelivered(invoicableQtyBasedOn); qtysToInvoiceCalc = qtysToInvoiceRaw; } else { qtysToInvoiceRaw = deliveredData.getReceiptData().getQtysTotal(invoicableQtyBasedOn); qtysToInvoiceCalc = deliveredData.getReceiptData().computeInvoicableQtyDelivered(qualityDiscountOverride, invoicableQtyBasedOn); } logger.debug("IsSales={} -> return delivered quantity={}", soTrx.isSales(), qtysToInvoiceCalc); return new ToInvoiceExclOverride( ToInvoiceExclOverride.InvoicedQtys.NOT_SUBTRACTED, qtysToInvoiceRaw, qtysToInvoiceCalc); } public StockQtyAndUOMQty computeQtysDelivered() { final StockQtyAndUOMQty qtysDelivered; if (soTrx.isSales()) { qtysDelivered = deliveredData.getShipmentData().computeInvoicableQtyDelivered(invoicableQtyBasedOn); } else
{ qtysDelivered = deliveredData.getReceiptData().getQtysTotal(invoicableQtyBasedOn); } return qtysDelivered; } @lombok.Value public static class ToInvoiceExclOverride { enum InvoicedQtys { SUBTRACTED, NOT_SUBTRACTED } InvoicedQtys invoicedQtys; /** * Excluding possible receipt quantities with quality issues */ StockQtyAndUOMQty qtysRaw; /** * Computed including possible receipt quality issues, not overridden by a possible qtyToInvoice override. */ StockQtyAndUOMQty qtysCalc; private ToInvoiceExclOverride( @NonNull final InvoicedQtys invoicedQtys, @NonNull final StockQtyAndUOMQty qtysRaw, @NonNull final StockQtyAndUOMQty qtysCalc) { this.qtysRaw = qtysRaw; this.qtysCalc = qtysCalc; this.invoicedQtys = invoicedQtys; StockQtyAndUOMQtys.assumeCommonProductAndUom(qtysRaw, qtysCalc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoiceCandidate.java
1
请完成以下Java代码
public static String getCookie(final Cookie[] cookies, final String name) { if (cookies == null || cookies.length == 0) { return null; } Check.assumeNotEmpty(name, "name is not empty"); for (final Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } public static boolean setCookie(final HttpServletResponse response, final String name, final String value, final String description, final int maxAge) { Check.assume(response != null, "response not null"); Check.assume(!Check.isEmpty(name), "name not empty"); if (response.isCommitted()) { final AdempiereException ex = new AdempiereException("Response '" + response + "' was already committed. Cannot set the cookie anymore (name=" + name + ", value=" + value + ")"); logger.warn(ex.getLocalizedMessage(), ex); return false; }
final Cookie cookie = new Cookie(name, value); cookie.setMaxAge(maxAge); // 1year (in seconds) cookie.setSecure(false); // send cookie even if not using HTTPS (default) // Leaving the Domain empty (domain from Request will be used) to prevent browser rejecting the cookie // See http://www.ietf.org/rfc/rfc2109.txt, chapter 4.3.2 // cookie.setDomain(null); if (description != null) { cookie.setComment(description); } response.addCookie(cookie); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\hostkey\spi\impl\CookieUtil.java
1
请完成以下Java代码
public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public boolean isIncludeChildExecutionsWithBusinessKeyQuery() { return includeChildExecutionsWithBusinessKeyQuery; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public boolean isActive() { return isActive; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) { this.involvedUser = involvedUser; } public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; }
public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public void setInvolvedGroups(List<String> involvedGroups) { this.involvedGroups = involvedGroups; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public CorrelationData getCorrelationData() { return this.correlationData; } /** * @return The time the message was sent. */ public long getTimestamp() { return this.timestamp; } /** * When the confirmation is nacked, set the cause when available. * @param cause The cause. * @since 1.4 */ public void setCause(String cause) { this.cause = cause; } /** * @return the cause. * @since 1.4 */ public @Nullable String getCause() { return this.cause; } /** * True if a returned message has been received. * @return true if there is a return. * @since 2.2.10 */ public boolean isReturned() { return this.returned; }
/** * Indicate that a returned message has been received. * @param isReturned true if there is a return. * @since 2.2.10 */ public void setReturned(boolean isReturned) { this.returned = isReturned; } /** * Return true if a return has been passed to the listener or if no return has been * received. * @return false if an expected returned message has not been passed to the listener. * @throws InterruptedException if interrupted. * @since 2.2.10 */ public boolean waitForReturnIfNeeded() throws InterruptedException { return !this.returned || this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS); } /** * Count down the returned message latch; call after the listener has been called. * @since 2.2.10 */ public void countDown() { this.latch.countDown(); } @Override public String toString() { return "PendingConfirm [correlationData=" + this.correlationData + (this.cause == null ? "" : " cause=" + this.cause) + "]"; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\PendingConfirm.java
1
请完成以下Java代码
private final class LocationPart { private final JLabel label; private final JComponent field; private final String partName; private boolean enabledCustom = true; private boolean enabledByCaptureSequence = false; public LocationPart(final String partName, final String label, final JComponent field) { super(); this.partName = partName; this.field = field; this.field.setName(label); this.label = new CLabel(Check.isEmpty(label) ? "" : msgBL.translate(Env.getCtx(), label)); this.label.setHorizontalAlignment(SwingConstants.RIGHT); this.label.setLabelFor(field); update(); } public void setEnabledCustom(final boolean enabledCustom) { if (this.enabledCustom == enabledCustom) { return; } this.enabledCustom = enabledCustom; update(); } public void setEnabledByCaptureSequence(final LocationCaptureSequence captureSequence) { final boolean enabled = captureSequence.hasPart(partName); setEnabledByCaptureSequence(enabled); } private void setEnabledByCaptureSequence(final boolean enabledByCaptureSequence) { if (this.enabledByCaptureSequence == enabledByCaptureSequence) {
return; } this.enabledByCaptureSequence = enabledByCaptureSequence; update(); } private final void update() { final boolean enabled = enabledCustom && enabledByCaptureSequence; label.setEnabled(enabled); label.setVisible(enabled); field.setEnabled(enabled); field.setVisible(enabled); } public void setLabelText(final String labelText) { label.setText(labelText); } public JLabel getLabel() { return label; } public JComponent getField() { return field; } } } // VLocationDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocationDialog.java
1
请完成以下Java代码
public void writeValue(FileValue fileValue, TypedValueField typedValueField) { Map<String, Object> valueInfo = new HashMap<>(); valueInfo.put(VALUE_INFO_FILE_NAME, fileValue.getFilename()); if (fileValue.getEncoding() != null) { valueInfo.put(VALUE_INFO_FILE_ENCODING, fileValue.getEncoding()); } if (fileValue.getMimeType() != null) { valueInfo.put(VALUE_INFO_FILE_MIME_TYPE, fileValue.getMimeType()); } typedValueField.setValueInfo(valueInfo); byte[] bytes = ((FileValueImpl) fileValue).getByteArray(); if (bytes != null) { typedValueField.setValue(Base64.encodeBase64String(bytes)); } } protected boolean canWriteValue(TypedValue typedValue) { if (typedValue == null || typedValue.getType() == null) {
// untyped value return false; } return typedValue.getType().getName().equals(valueType.getName()) && !isDeferred(typedValue); } protected boolean canReadValue(TypedValueField typedValueField) { Object value = typedValueField.getValue(); return value == null || value instanceof String; } protected boolean isDeferred(Object variableValue) { return variableValue instanceof DeferredFileValue && !((DeferredFileValue) variableValue).isLoaded(); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\mapper\FileValueMapper.java
1
请完成以下Java代码
public byte[] getBinaryData(final I_AD_Archive archive) { checkContext(); Check.assumeNotNull(archive, "archive not null"); final int archiveId = archive.getAD_Archive_ID(); if (archiveId <= 0) { // FIXME: handle the case when adArchiveId <= 0 throw new IllegalStateException("Retrieving data from a not saved archived is not supported: " + archive); } final ArchiveGetDataRequest request = new ArchiveGetDataRequest(); request.setAdArchiveId(archiveId); final ArchiveGetDataResponse response = endpoint.getArchiveData(request); return response.getData(); } @Override public void setBinaryData(final I_AD_Archive archive, final byte[] data) { checkContext(); Check.assumeNotNull(archive, "archive not null"); final int archiveId = archive.getAD_Archive_ID(); final ArchiveSetDataRequest request = new ArchiveSetDataRequest(); request.setAdArchiveId(archiveId); request.setData(data); final ArchiveSetDataResponse response = endpoint.setArchiveData(request); final int tempArchiveId = response.getAdArchiveId(); transferData(archive, tempArchiveId); }
private void transferData(final I_AD_Archive archive, final int fromTempArchiveId) { Check.assume(fromTempArchiveId > 0, "fromTempArchiveId > 0"); final Properties ctx = InterfaceWrapperHelper.getCtx(archive); final String trxName = InterfaceWrapperHelper.getTrxName(archive); final I_AD_Archive tempArchive = InterfaceWrapperHelper.create(ctx, fromTempArchiveId, I_AD_Archive.class, trxName); Check.assumeNotNull(tempArchive, "Temporary archive not found for AD_Archive_ID={}", fromTempArchiveId); transferData(archive, tempArchive); InterfaceWrapperHelper.delete(tempArchive); } private void transferData(final I_AD_Archive archive, final I_AD_Archive fromTempArchive) { Check.assume(fromTempArchive.isFileSystem(), "Temporary archive {} shall be saved in filesystem", fromTempArchive); archive.setIsFileSystem(fromTempArchive.isFileSystem()); archive.setBinaryData(fromTempArchive.getBinaryData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RemoteArchiveStorage.java
1
请完成以下Java代码
public ChannelDefinitionEntity findLatestChannelDefinitionByKey(String channelDefinitionKey) { return dataManager.findLatestChannelDefinitionByKey(channelDefinitionKey); } @Override public void deleteChannelDefinitionsByDeploymentId(String deploymentId) { dataManager.deleteChannelDefinitionsByDeploymentId(deploymentId); } @Override public List<ChannelDefinition> findChannelDefinitionsByQueryCriteria(ChannelDefinitionQueryImpl channelQuery) { return dataManager.findChannelDefinitionsByQueryCriteria(channelQuery); } @Override public long findChannelDefinitionCountByQueryCriteria(ChannelDefinitionQueryImpl channelQuery) { return dataManager.findChannelDefinitionCountByQueryCriteria(channelQuery); } @Override public ChannelDefinitionEntity findChannelDefinitionByDeploymentAndKey(String deploymentId, String channelDefinitionKey) { return dataManager.findChannelDefinitionByDeploymentAndKey(deploymentId, channelDefinitionKey); } @Override public ChannelDefinitionEntity findChannelDefinitionByDeploymentAndKeyAndTenantId(String deploymentId, String channelDefinitionKey, String tenantId) { return dataManager.findChannelDefinitionByDeploymentAndKeyAndTenantId(deploymentId, channelDefinitionKey, tenantId); } @Override public ChannelDefinitionEntity findLatestChannelDefinitionByKeyAndTenantId(String channelDefinitionKey, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findLatestChannelDefinitionByKey(channelDefinitionKey); } else { return dataManager.findLatestChannelDefinitionByKeyAndTenantId(channelDefinitionKey, tenantId); } }
@Override public ChannelDefinitionEntity findChannelDefinitionByKeyAndVersionAndTenantId(String channelDefinitionKey, Integer eventVersion, String tenantId) { if (tenantId == null || EventRegistryEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findChannelDefinitionByKeyAndVersion(channelDefinitionKey, eventVersion); } else { return dataManager.findChannelDefinitionByKeyAndVersionAndTenantId(channelDefinitionKey, eventVersion, tenantId); } } @Override public List<ChannelDefinition> findChannelDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findChannelDefinitionsByNativeQuery(parameterMap); } @Override public long findChannelDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findChannelDefinitionCountByNativeQuery(parameterMap); } @Override public void updateChannelDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateChannelDefinitionTenantIdForDeployment(deploymentId, newTenantId); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ChannelDefinitionEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Pageable getPageable() { return this.pageable; } public Sort getSort() { return this.sort; } /** * Pageable properties. */ public static class Pageable { /** * Page index parameter name. */ private String pageParameter = "page"; /** * Page size parameter name. */ private String sizeParameter = "size"; /** * Whether to expose and assume 1-based page number indexes. Defaults to "false", * meaning a page number of 0 in the request equals the first page. */ private boolean oneIndexedParameters; /** * General prefix to be prepended to the page number and page size parameters. */ private String prefix = ""; /** * Delimiter to be used between the qualifier and the actual page number and size * properties. */ private String qualifierDelimiter = "_"; /** * Default page size. */ private int defaultPageSize = 20; /** * Maximum page size to be accepted. */ private int maxPageSize = 2000; /** * Configures how to render Spring Data Pageable instances. */ private PageSerializationMode serializationMode = PageSerializationMode.DIRECT; public String getPageParameter() { return this.pageParameter; } public void setPageParameter(String pageParameter) { this.pageParameter = pageParameter; } public String getSizeParameter() { return this.sizeParameter; } public void setSizeParameter(String sizeParameter) { this.sizeParameter = sizeParameter; } public boolean isOneIndexedParameters() { return this.oneIndexedParameters; }
public void setOneIndexedParameters(boolean oneIndexedParameters) { this.oneIndexedParameters = oneIndexedParameters; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getQualifierDelimiter() { return this.qualifierDelimiter; } public void setQualifierDelimiter(String qualifierDelimiter) { this.qualifierDelimiter = qualifierDelimiter; } public int getDefaultPageSize() { return this.defaultPageSize; } public void setDefaultPageSize(int defaultPageSize) { this.defaultPageSize = defaultPageSize; } public int getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode; } public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort { /** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class UserAuthQRCode { @NonNull String token; @NonNull UserId userId; public static boolean equals(@Nullable final UserAuthQRCode o1, @Nullable final UserAuthQRCode o2) { return Objects.equals(o1, o2); } @NonNull public static UserAuthQRCode ofGlobalQRCodeJsonString(final String json) { return UserAuthQRCodeJsonConverter.fromGlobalQRCodeJsonString(json); } @NonNull public static UserAuthQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) { return UserAuthQRCodeJsonConverter.fromGlobalQRCode(globalQRCode); } @NonNull public static UserAuthQRCode ofAuthToken(@NonNull final UserAuthToken authToken) { return builder() .userId(authToken.getUserId()) .token(authToken.getAuthToken()) .build(); } @NonNull public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString()) .bottomText(getDisplayableQrCode()) .build(); } public String getDisplayableQrCode() { return String.valueOf(userId.getRepoId()); } @NonNull public String toGlobalQRCodeJsonString() { return UserAuthQRCodeJsonConverter.toGlobalQRCodeJsonString(this); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return UserAuthQRCodeJsonConverter.isTypeMatching(globalQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\qr\UserAuthQRCode.java
2
请在Spring Boot框架中完成以下Java代码
public class BotConfiguration { private static final Logger log = LoggerFactory.getLogger( BotConfiguration.class ); @Value("${token}") private String token; @Bean public <T extends Event> GatewayDiscordClient gatewayDiscordClient(List<EventListener<T>> eventListeners) { GatewayDiscordClient client = null; try { client = DiscordClientBuilder.create(token) .build() .login() .block();
for(EventListener<T> listener : eventListeners) { client.on(listener.getEventType()) .flatMap(listener::execute) .onErrorResume(listener::handleError) .subscribe(); } } catch ( Exception exception ) { log.error( "Be sure to use a valid bot token!", exception ); } return client; } }
repos\tutorials-master\saas-modules\discord4j\src\main\java\com\baeldung\discordbot\BotConfiguration.java
2
请完成以下Java代码
public class TableColumnPathElement implements ITableColumnPathElement { private String tableName; private String columnName; private String parentTableName; private String parentColumnName; private String parentColumnSQL; public TableColumnPathElement(String tableName, String columnName, String parentTableName, String parentColumnName, String parentColumnSQL) { super(); this.tableName = tableName; this.columnName = columnName; this.parentTableName = parentTableName; this.parentColumnName = parentColumnName; this.parentColumnSQL = parentColumnSQL; } @Override public String getTableName() { return tableName; } @Override public String getColumnName() { return columnName; } @Override public String getParentTableName() { return parentTableName; }
@Override public String getParentColumnName() { return parentColumnName; } @Override public String getParentColumnSQL() { return parentColumnSQL; } @Override public String toString() { return "TableColumnPathElement [" +"tableName=" + tableName + ", columnName=" + columnName + ", parentTableName=" + parentTableName + ", parentColumnName=" + parentColumnName + ", parentColumnSQL=" + parentColumnSQL + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\model\TableColumnPathElement.java
1
请完成以下Java代码
class MProductPriceCloningCommand { private final int source_PriceList_Version_ID; private final int target_PriceList_Version_ID; private final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final public void cloneProductPrice() { final IQueryBL queryBL = Services.get(IQueryBL.class); final String trxName = ITrx.TRXNAME_None; final IQuery<I_M_ProductPrice> existentProductPrices = queryBL.createQueryBuilder(I_M_ProductPrice.class, trxName) .addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID, target_PriceList_Version_ID) .create(); queryBL.createQueryBuilder(I_M_ProductPrice.class, trxName) .addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID, source_PriceList_Version_ID) .addNotInSubQueryFilter(I_M_ProductPrice.COLUMNNAME_M_Product_ID, I_M_ProductPrice.COLUMNNAME_M_Product_ID, existentProductPrices) .create() .iterateAndStream() .forEach(this::createProductPrice); }
private void createProductPrice(@NonNull final I_M_ProductPrice productPrice) { final I_M_ProductPrice pp = InterfaceWrapperHelper.copy() .setFrom(productPrice) .copyToNew(I_M_ProductPrice.class); pp.setM_PriceList_Version_ID(target_PriceList_Version_ID); cloneASI(productPrice); InterfaceWrapperHelper.save(pp); } private void cloneASI(@NonNull final I_M_ProductPrice productPrice) { if (!productPrice.isAttributeDependant()) { return; } final I_M_AttributeSetInstance sourceASI = productPrice.getM_AttributeSetInstance(); final I_M_AttributeSetInstance targetASI = sourceASI == null ? null : asiBL.copy(sourceASI); productPrice.setM_AttributeSetInstance(targetASI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\MProductPriceCloningCommand.java
1
请完成以下Java代码
public static boolean getDefaultFilterState() { return filter_state; } /** Should we filter the value of the element attributes */ public static boolean getDefaultFilterAttributeState() { return filter_attribute_state; } /** What is the equality character for an attribute. */ public static char getDefaultAttributeEqualitySign() { return attribute_equality_sign; } /** What the start modifier should be */ public static char getDefaultBeginStartModifier() { return begin_start_modifier; } /** What the start modifier should be */ public static char getDefaultEndStartModifier() { return end_start_modifier; } /** What the end modifier should be */ public static char getDefaultBeginEndModifier() { return begin_end_modifier; } /** What the end modifier should be */ public static char getDefaultEndEndModifier() { return end_end_modifier; } /* What character should we use for quoting attributes. */ public static char getDefaultAttributeQuoteChar() { return attribute_quote_char; } /* Should we wrap quotes around an attribute? */ public static boolean getDefaultAttributeQuote() { return attribute_quote; } /** Does this element need a closing tag? */ public static boolean getDefaultEndElement()
{ return end_element; } /** What codeset are we going to use the default is 8859_1 */ public static String getDefaultCodeset() { return codeset; } /** position of tag relative to start and end. */ public static int getDefaultPosition() { return position; } /** Default value to set case type */ public static int getDefaultCaseType() { return case_type; } public static char getDefaultStartTag() { return start_tag; } public static char getDefaultEndTag() { return end_tag; } /** Should we print html in a more readable format? */ public static boolean getDefaultPrettyPrint() { return pretty_print; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ECSDefaults.java
1
请完成以下Java代码
public Builder setOrgId(final OrgId orgId) { this.orgId = orgId; return this; } public Builder setDocTypeName(final String docTypeName) { this.docTypeName = docTypeName; return this; } public Builder setC_Payment_ID(final int C_Payment_ID) { this.C_Payment_ID = C_Payment_ID; return this; } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setBPartnerName(final String bPartnerName) { BPartnerName = bPartnerName; return this; } public Builder setPaymentDate(final Date paymentDate) { this.paymentDate = paymentDate; return this; } /** * task 09643: separate transaction date from the accounting date * * @param dateAcct * @return */ public Builder setDateAcct(final Date dateAcct) { this.dateAcct = dateAcct; return this; } public Builder setCurrencyISOCode(@Nullable final CurrencyCode currencyISOCode) { this.currencyISOCode = currencyISOCode; return this; } public Builder setPayAmt(final BigDecimal payAmt) { this.payAmt = payAmt; return this; }
public Builder setPayAmtConv(final BigDecimal payAmtConv) { this.payAmtConv = payAmtConv; return this; } public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setOpenAmtConv(final BigDecimal openAmtConv) { this.openAmtConv = openAmtConv; return this; } public Builder setMultiplierAP(final BigDecimal multiplierAP) { this.multiplierAP = multiplierAP; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentRow.java
1
请完成以下Java代码
protected ProviderConfig parseProvider(String provider, DubboProperties properties, Environment environment, String... errors) { ProviderConfig providerConfig = null; if (provider == null || "".equals(provider)) { providerConfig = properties.getProvider(); } else { provider = environment.resolvePlaceholders(provider); Map<String, AbstractConfig> providerMap = ID_CONFIG_MAP.get(PROVIDERS_KEY); providerConfig = (ProviderConfig) providerMap.get(provider); if (providerConfig == null) { providerConfig = properties.getProviders().get(provider); if (providerConfig == null) { throw new NullPointerException(this.buildErrorMsg(errors)); } } } return providerConfig; } protected ConsumerConfig parseConsumer(String consumer, DubboProperties properties, Environment environment, String... errors) { ConsumerConfig consumerConfig = null; if (consumer == null || "".equals(consumer)) {
consumerConfig = properties.getConsumer(); } else { consumer = environment.resolvePlaceholders(consumer); Map<String, AbstractConfig> consumerMap = ID_CONFIG_MAP.get(CONSUMERS_KEY); consumerConfig = (ConsumerConfig) consumerMap.get(consumer); if (consumerConfig == null) { consumerConfig = properties.getConsumers().get(consumer); if (consumerConfig == null) { throw new NullPointerException(this.buildErrorMsg(errors)); } } } return consumerConfig; } }
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboCommonAutoConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public class Doc_InOut_Factory implements IAcctDocProvider { private final IInOutBL inOutBL = Services.get(IInOutBL.class); private final IOrderBL orderBL = Services.get(IOrderBL.class); @Override public Set<String> getDocTableNames() {return ImmutableSet.of(I_M_InOut.Table_Name);} @Override public Doc<?> getOrNull(final AcctDocRequiredServicesFacade services, final List<AcctSchema> acctSchemas, final TableRecordReference documentRef) { final InOutId inoutId = documentRef.getIdAssumingTableName(I_M_InOut.Table_Name, InOutId::ofRepoId); return new Doc_InOut( inOutBL,
orderBL, AcctDocContext.builder() .services(services) .acctSchemas(acctSchemas) .documentModel(retrieveDocumentModel(documentRef)) .build()); } private AcctDocModel retrieveDocumentModel(final TableRecordReference documentRef) { final InOutId inoutId = documentRef.getIdAssumingTableName(I_M_InOut.Table_Name, InOutId::ofRepoId); final I_M_InOut inoutRecord = inOutBL.getById(inoutId); return new POAcctDocModel(LegacyAdapters.convertToPO(inoutRecord)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\de\metas\acct\doc\Doc_InOut_Factory.java
2
请完成以下Java代码
public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic
/** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic @Override public boolean isAutoCommit() { return true; } } // VCheckBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCheckBox.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Attribute_Value[") .append(get_ID()).append("]"); return sb.toString(); } /** Set System Attribute. @param AD_Attribute_ID System Attribute */ public void setAD_Attribute_ID (int AD_Attribute_ID) { if (AD_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, Integer.valueOf(AD_Attribute_ID)); } /** Get System Attribute. @return System Attribute */ public int getAD_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set V_Date. @param V_Date V_Date */ public void setV_Date (Timestamp V_Date) { set_Value (COLUMNNAME_V_Date, V_Date);
} /** Get V_Date. @return V_Date */ public Timestamp getV_Date () { return (Timestamp)get_Value(COLUMNNAME_V_Date); } /** Set V_Number. @param V_Number V_Number */ public void setV_Number (String V_Number) { set_Value (COLUMNNAME_V_Number, V_Number); } /** Get V_Number. @return V_Number */ public String getV_Number () { return (String)get_Value(COLUMNNAME_V_Number); } /** Set V_String. @param V_String V_String */ public void setV_String (String V_String) { set_Value (COLUMNNAME_V_String, V_String); } /** Get V_String. @return V_String */ public String getV_String () { return (String)get_Value(COLUMNNAME_V_String); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute_Value.java
1
请在Spring Boot框架中完成以下Java代码
public class GithubOAuth2ClientMapper extends AbstractOAuth2ClientMapper implements OAuth2ClientMapper { private static final String EMAIL_URL_KEY = "emailUrl"; private static final String AUTHORIZATION = "Authorization"; private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); @Autowired private OAuth2Configuration oAuth2Configuration; @Override public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client oAuth2Client) { OAuth2MapperConfig config = oAuth2Client.getMapperConfig(); Map<String, String> githubMapperConfig = oAuth2Configuration.getGithubMapper(); String email = getEmail(githubMapperConfig.get(EMAIL_URL_KEY), providerAccessToken); Map<String, Object> attributes = token.getPrincipal().getAttributes(); OAuth2User oAuth2User = BasicMapperUtils.getOAuth2User(email, attributes, config); return getOrCreateSecurityUserFromOAuth2User(oAuth2User, oAuth2Client); } private synchronized String getEmail(String emailUrl, String oauth2Token) { restTemplateBuilder = restTemplateBuilder.defaultHeader(AUTHORIZATION, "token " + oauth2Token); RestTemplate restTemplate = restTemplateBuilder.build(); GithubEmailsResponse githubEmailsResponse; try { githubEmailsResponse = restTemplate.getForEntity(emailUrl, GithubEmailsResponse.class).getBody(); if (githubEmailsResponse == null){ throw new RuntimeException("Empty Github response!"); } } catch (Exception e) { log.error("There was an error during connection to Github API", e); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } Optional<String> emailOpt = githubEmailsResponse.stream() .filter(GithubEmailResponse::isPrimary)
.map(GithubEmailResponse::getEmail) .findAny(); if (emailOpt.isPresent()){ return emailOpt.get(); } else { log.error("Could not find primary email from {}.", githubEmailsResponse); throw new RuntimeException("Unable to login. Please contact your Administrator!"); } } private static class GithubEmailsResponse extends ArrayList<GithubEmailResponse> {} @Data @ToString private static class GithubEmailResponse { private String email; private boolean verified; private boolean primary; private String visibility; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\GithubOAuth2ClientMapper.java
2
请完成以下Java代码
public String getSelectedOutcome() { return selectedOutcome; } public void setSelectedOutcome(String selectedOutcome) { this.selectedOutcome = selectedOutcome; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeType() { return scopeType; }
public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-form-api\src\main\java\org\flowable\form\api\FormInstanceInfo.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isPersistent() { return this.persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } public @Nullable String getDataDirectory() { return this.dataDirectory; } public void setDataDirectory(@Nullable String dataDirectory) { this.dataDirectory = dataDirectory; } public String[] getQueues() { return this.queues; } public void setQueues(String[] queues) { this.queues = queues; } public String[] getTopics() { return this.topics; } public void setTopics(String[] topics) { this.topics = topics; } public String getClusterPassword() { return this.clusterPassword; } public void setClusterPassword(String clusterPassword) { this.clusterPassword = clusterPassword; this.defaultClusterPassword = false; }
public boolean isDefaultClusterPassword() { return this.defaultClusterPassword; } /** * Creates the minimal transport parameters for an embedded transport * configuration. * @return the transport parameters * @see TransportConstants#SERVER_ID_PROP_NAME */ public Map<String, Object> generateTransportParameters() { Map<String, Object> parameters = new HashMap<>(); parameters.put(TransportConstants.SERVER_ID_PROP_NAME, getServerId()); return parameters; } } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisProperties.java
2
请完成以下Java代码
public String getReplicationFactor() { return replicationFactor; } public void setReplicationFactor(String replicationFactor) { this.replicationFactor = replicationFactor; } } public static class NonBlockingRetryBackOff { protected String delay; protected String maxDelay; protected String multiplier; protected String random; public String getDelay() { return delay; } public void setDelay(String delay) { this.delay = delay; } public String getMaxDelay() { return maxDelay; } public void setMaxDelay(String maxDelay) { this.maxDelay = maxDelay; } public String getMultiplier() { return multiplier; } public void setMultiplier(String multiplier) { this.multiplier = multiplier; } public String getRandom() { return random; }
public void setRandom(String random) { this.random = random; } } public static class TopicPartition { protected String topic; protected Collection<String> partitions; public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public Collection<String> getPartitions() { return partitions; } public void setPartitions(Collection<String> partitions) { this.partitions = partitions; } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java
1
请完成以下Java代码
protected List<Integer> convertValuesToInteger(List<TypedValue> typedValues) throws IllegalArgumentException { List<Integer> intValues = new ArrayList<Integer>(); for (TypedValue typedValue : typedValues) { if (ValueType.INTEGER.equals(typedValue.getType())) { intValues.add((Integer) typedValue.getValue()); } else if (typedValue.getType() == null) { // check if it is an integer Object value = typedValue.getValue(); if (value instanceof Integer) { intValues.add((Integer) value); } else { throw new IllegalArgumentException(); } } else { // reject other typed values throw new IllegalArgumentException(); } } return intValues; } protected List<Long> convertValuesToLong(List<TypedValue> typedValues) throws IllegalArgumentException { List<Long> longValues = new ArrayList<Long>(); for (TypedValue typedValue : typedValues) { if (ValueType.LONG.equals(typedValue.getType())) { longValues.add((Long) typedValue.getValue()); } else if (typedValue.getType() == null) { // check if it is a long or a string of a number Object value = typedValue.getValue(); if (value instanceof Long) { longValues.add((Long) value); } else { Long longValue = Long.valueOf(value.toString()); longValues.add(longValue); } } else { // reject other typed values throw new IllegalArgumentException(); } } return longValues; }
protected List<Double> convertValuesToDouble(List<TypedValue> typedValues) throws IllegalArgumentException { List<Double> doubleValues = new ArrayList<Double>(); for (TypedValue typedValue : typedValues) { if (ValueType.DOUBLE.equals(typedValue.getType())) { doubleValues.add((Double) typedValue.getValue()); } else if (typedValue.getType() == null) { // check if it is a double or a string of a decimal number Object value = typedValue.getValue(); if (value instanceof Double) { doubleValues.add((Double) value); } else { Double doubleValue = Double.valueOf(value.toString()); doubleValues.add(doubleValue); } } else { // reject other typed values throw new IllegalArgumentException(); } } return doubleValues; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\hitpolicy\AbstractCollectNumberHitPolicyHandler.java
1
请完成以下Java代码
public de.metas.tourplanning.model.I_M_TourVersion getM_TourVersion() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class); } @Override public void setM_TourVersion(de.metas.tourplanning.model.I_M_TourVersion M_TourVersion) { set_ValueFromPO(COLUMNNAME_M_TourVersion_ID, de.metas.tourplanning.model.I_M_TourVersion.class, M_TourVersion); } /** Set Tour Version. @param M_TourVersion_ID Tour Version */ @Override public void setM_TourVersion_ID (int M_TourVersion_ID) { if (M_TourVersion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, Integer.valueOf(M_TourVersion_ID)); } /** Get Tour Version. @return Tour Version */ @Override public int getM_TourVersion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Tour Version Line. @param M_TourVersionLine_ID Tour Version Line */ @Override public void setM_TourVersionLine_ID (int M_TourVersionLine_ID) { if (M_TourVersionLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, Integer.valueOf(M_TourVersionLine_ID)); } /** Get Tour Version Line. @return Tour Version Line */
@Override public int getM_TourVersionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersionLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersionLine.java
1
请完成以下Java代码
private String convertLessThanOneThousand (int number) { String soFar; // Below 20 if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) return soFar; return numNames[number] + "Ratus " + soFar; } // convertLessThanOneThousand /** * Convert * @param number * @return amt */ private String convert (long number) { /* special case */ if (number == 0) { return "Kosong"; } String prefix = ""; if (number < 0) { number = -number; prefix = "Negatif "; } String soFar = ""; int place = 0; do { long n = number % 1000; if (n != 0) { String s = convertLessThanOneThousand ((int)n); soFar = s + majorNames[place] + soFar; } place++; number /= 1000; } while (number > 0); return (prefix + soFar).trim (); } // convert /************************************************************************** * Get Amount in Words * @param amount numeric amount (352.80) * @return amount in words (three*five*two 80/100) * @throws Exception */ public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; // StringBuffer sb = new StringBuffer (); sb.append("RINGGIT "); int pos = amount.lastIndexOf ('.'); int pos2 = amount.lastIndexOf (','); if (pos2 > pos) pos = pos2; String oldamt = amount; amount = amount.replaceAll (",", ""); int newpos = amount.lastIndexOf ('.'); long dollars = Long.parseLong(amount.substring (0, newpos)); sb.append (convert (dollars)); for (int i = 0; i < oldamt.length (); i++) { if (pos == i) // we are done {
String cents = oldamt.substring (i + 1); long sen = Long.parseLong(cents); //red1 convert cents to words sb.append(" dan SEN"); sb.append (' ').append (convert(sen)); break; } } return sb.toString (); } // getAmtInWords /** * Test Print * @param amt amount */ private void print (String amt) { try { System.out.println(amt + " = " + getAmtInWords(amt)); } catch (Exception e) { e.printStackTrace(); } } // print /** * Test * @param args ignored */ public static void main (String[] args) { AmtInWords_MS aiw = new AmtInWords_MS(); // aiw.print (".23"); Error aiw.print ("0.23"); aiw.print ("1.23"); aiw.print ("12.34"); aiw.print ("123.45"); aiw.print ("1,234.56"); aiw.print ("12,345.78"); aiw.print ("123,457.89"); aiw.print ("1,234,578.90"); aiw.print ("100.00"); } // main } // AmtInWords_MY
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_MS.java
1
请完成以下Java代码
public Map<String, HalLink> get_links() { return _links; } public Map<String, Object> get_embedded() { return _embedded; } public void addLink(String rel, String href) { if(_links == null) { _links = new TreeMap<String, HalLink>(); } _links.put(rel, new HalLink(href)); } public void addLink(String rel, URI hrefUri) { addLink(rel, hrefUri.toString()); } public void addEmbedded(String name, HalResource<?> embedded) { linker.mergeLinks(embedded); addEmbeddedObject(name, embedded); } private void addEmbeddedObject(String name, Object embedded) { if(_embedded == null) { _embedded = new TreeMap<String, Object>(); } _embedded.put(name, embedded); } public void addEmbedded(String name, List<HalResource<?>> embeddedCollection) { for (HalResource<?> resource : embeddedCollection) { linker.mergeLinks(resource); }
addEmbeddedObject(name, embeddedCollection); } public Object getEmbedded(String name) { return _embedded.get(name); } /** * Can be used to embed a relation. Embedded all linked resources in the given relation. * * @param relation the relation to embedded * @param processEngine used to resolve the resources * @return the resource itself. */ @SuppressWarnings("unchecked") public T embed(HalRelation relation, ProcessEngine processEngine) { List<HalResource<?>> resolvedLinks = linker.resolve(relation, processEngine); if(resolvedLinks != null && resolvedLinks.size() > 0) { addEmbedded(relation.relName, resolvedLinks); } return (T) this; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalResource.java
1
请在Spring Boot框架中完成以下Java代码
public class DateTimeValues { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private Date date; private LocalDate localDate; private LocalDateTime localDateTime; private Instant instant; private ZonedDateTime zonedDateTime; private LocalTime localTime; private OffsetDateTime offsetDateTime; private java.sql.Date sqlDate; @Column(columnDefinition = "date") private Instant instantAsDate; private String zoneId; public DateTimeValues() { Clock clock = Clock.fixed(Instant.parse("2024-08-01T14:15:00Z"), ZoneId.of("UTC")); this.date = new Date(clock.millis()); this.localDate = LocalDate.now(clock); this.localDateTime = LocalDateTime.now(clock); this.zonedDateTime = ZonedDateTime.now(clock);
this.instant = Instant.now(clock); this.localTime = LocalTime.now(clock); this.offsetDateTime = OffsetDateTime.now(clock); this.instantAsDate = Instant.now(clock); this.sqlDate = java.sql.Date.valueOf(LocalDate.now(clock)); this.zoneId = ZoneId.systemDefault().getId(); } public Integer getId() { return id; } public Instant getInstantAsDate() { return instantAsDate; } }
repos\tutorials-master\persistence-modules\spring-boot-postgresql\src\main\java\com\baeldung\postgres\datetime\DateTimeValues.java
2
请完成以下Java代码
public java.lang.String getOrderByClause () { return (java.lang.String)get_Value(COLUMNNAME_OrderByClause); } /** Set Inaktive Werte anzeigen. @param ShowInactiveValues Inaktive Werte anzeigen */ @Override public void setShowInactiveValues (boolean ShowInactiveValues) { set_Value (COLUMNNAME_ShowInactiveValues, Boolean.valueOf(ShowInactiveValues)); } /** Get Inaktive Werte anzeigen. @return Inaktive Werte anzeigen */ @Override public boolean isShowInactiveValues () { Object oo = get_Value(COLUMNNAME_ShowInactiveValues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql WHERE. @param WhereClause
Fully qualified SQL WHERE clause */ @Override public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java
1
请完成以下Java代码
public class DiscountESRActionHandler extends AbstractESRActionHandler { final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class); final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class); final ITrxManager trxManager = Services.get(ITrxManager.class); @Override public boolean process(final I_ESR_ImportLine line, final String message) { super.process(line, message); Check.assumeNotNull(line.getESR_Payment_Action(), "@" + ESRConstants.ERR_ESR_LINE_WITH_NO_PAYMENT_ACTION + "@"); final I_C_Invoice invoice = line.getC_Invoice(); if (invoice == null) { // We have nothing to do, but the line should still be flagged as processed. return true; } // sanity check: there must be an payment with a negative OverUnderAmt final PaymentId esrImportLinePaymentId = PaymentId.ofRepoIdOrNull(line.getC_Payment_ID()); final I_C_Payment payment = esrImportLinePaymentId == null ? null : paymentDAO.getById(esrImportLinePaymentId); Check.assumeNotNull(payment, "Null payment for line {}", line.getESR_ImportLine_ID());
Check.errorIf(payment.getOverUnderAmt().signum() > 0, "Exces payment for line {}. Can't discount this", line.getESR_ImportLine_ID()); final Amount discount = invoiceDAO.retrieveOpenAmt(InvoiceId.ofRepoId(invoice.getC_Invoice_ID())); trxManager.runInThreadInheritedTrx(new TrxRunnable() { @Override public void run(String trxName) throws Exception { invoiceBL.discountInvoice(invoice, discount, payment.getDateAcct()); } }); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\actionhandler\impl\DiscountESRActionHandler.java
1
请完成以下Java代码
static I_C_UOM extractUOMOrNull(@NonNull final I_M_HU_PI_Item_Product itemProduct) { final UomId uomId = extractUomIdOrNull(itemProduct); final IUOMDAO uomDAO = Services.get(IUOMDAO.class); return uomId != null ? uomDAO.getById(uomId) : null; } static @Nullable UomId extractUomIdOrNull(final @NotNull I_M_HU_PI_Item_Product itemProduct) { return UomId.ofRepoIdOrNull(itemProduct.getC_UOM_ID()); } static I_C_UOM extractUOM(@NonNull final I_M_HU_PI_Item_Product itemProduct) { final I_C_UOM uom = extractUOMOrNull(itemProduct); if (uom == null) { throw new AdempiereException("Cannot determine UOM of " + itemProduct.getName()); } return uom; } I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine); int getRequiredLUCount(@NonNull Quantity qty, I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM); static StockQtyAndUOMQty getMaxQtyCUsPerLU(final @NonNull StockQtyAndUOMQty qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM, final ProductId productId) { final StockQtyAndUOMQty maxQtyCUsPerLU; if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU()) { maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert( qty.getStockQty(), productId, qty.getUOMQtyNotNull().getUomId()); }
else { maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert( lutuConfigurationInStockUOM.getQtyCUsPerTU().multiply(lutuConfigurationInStockUOM.getQtyTU()), productId, qty.getUOMQtyNotNull().getUomId()); } return maxQtyCUsPerLU; } static Quantity getQtyCUsPerTUInStockUOM(final @NonNull I_C_OrderLine orderLineRecord, final @NonNull Quantity stockQty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM) { final Quantity qtyCUsPerTUInStockUOM; if (orderLineRecord.getQtyItemCapacity().signum() > 0) { // we use the capacity which the goods were ordered in qtyCUsPerTUInStockUOM = Quantitys.of(orderLineRecord.getQtyItemCapacity(), stockQty.getUomId()); } else if (!lutuConfigurationInStockUOM.isInfiniteQtyCU()) { // we make an educated guess, based on the packing-instruction's information qtyCUsPerTUInStockUOM = Quantitys.of(lutuConfigurationInStockUOM.getQtyCUsPerTU(), stockQty.getUomId()); } else { // we just don't have the info. So we assume that everything was put into one TU qtyCUsPerTUInStockUOM = stockQty; } return qtyCUsPerTUInStockUOM; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUPIItemProductBL.java
1
请在Spring Boot框架中完成以下Java代码
public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public String getDerivedCaseDefinitionUrl() { return derivedCaseDefinitionUrl; } public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) { this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl; }
public String getStageInstanceUrl() { return stageInstanceUrl; } public void setStageInstanceUrl(String stageInstanceUrl) { this.stageInstanceUrl = stageInstanceUrl; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java
2
请完成以下Java代码
public class UnsynchronizedSender implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(UnsynchronizedSender.class); private final Data data; private boolean illegalMonitorStateExceptionOccurred; public UnsynchronizedSender(Data data) { this.data = data; } @Override public void run() { try { Thread.sleep(1000); data.send("test");
data.notifyAll(); } catch (InterruptedException e) { LOG.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { LOG.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } public boolean hasIllegalMonitorStateExceptionOccurred() { return illegalMonitorStateExceptionOccurred; } }
repos\tutorials-master\core-java-modules\core-java-exceptions-3\src\main\java\com\baeldung\exceptions\illegalmonitorstate\UnsynchronizedSender.java
1
请在Spring Boot框架中完成以下Java代码
class PropertiesObservationFilterPredicate implements ObservationFilter, ObservationPredicate { private final ObservationFilter commonKeyValuesFilter; private final ObservationProperties properties; PropertiesObservationFilterPredicate(ObservationProperties properties) { this.properties = properties; this.commonKeyValuesFilter = createCommonKeyValuesFilter(properties); } @Override public Context map(Context context) { return this.commonKeyValuesFilter.map(context); } @Override public boolean test(String name, Context context) { return lookupWithFallbackToAll(this.properties.getEnable(), name, true); } private static <T> T lookupWithFallbackToAll(Map<String, T> values, String name, T defaultValue) { if (values.isEmpty()) { return defaultValue; } return doLookup(values, name, () -> values.getOrDefault("all", defaultValue)); }
private static <T> T doLookup(Map<String, T> values, String name, Supplier<T> defaultValue) { while (StringUtils.hasLength(name)) { T result = values.get(name); if (result != null) { return result; } int lastDot = name.lastIndexOf('.'); name = (lastDot != -1) ? name.substring(0, lastDot) : ""; } return defaultValue.get(); } private static ObservationFilter createCommonKeyValuesFilter(ObservationProperties properties) { if (properties.getKeyValues().isEmpty()) { return (context) -> context; } KeyValues keyValues = KeyValues.of(properties.getKeyValues().entrySet(), Entry::getKey, Entry::getValue); return (context) -> context.addLowCardinalityKeyValues(keyValues); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\PropertiesObservationFilterPredicate.java
2
请完成以下Java代码
private XmlReminder createReminder(@NonNull final DunningToExport dunning) { final XmlReminder createReminder = XmlReminder.builder() .requestDate(asXmlCalendar(dunning.getDunningDate())) .requestTimestamp(BigInteger.valueOf(dunning.getDunningTimestamp().getEpochSecond())) .requestId(dunning.getDocumentNumber()) .reminderText(dunning.getDunningText()) .reminderLevel("1") .build(); return createReminder; } private BodyMod createBodyMod( @NonNull final DunningToExport dunning) { return BodyMod .builder() .prologMod(createPrologMod(dunning.getMetasfreshVersion())) .balanceMod(createBalanceMod(dunning)) .build(); } private PrologMod createPrologMod(@NonNull final MetasfreshVersion metasfreshVersion) { final SoftwareMod softwareMod = createSoftwareMod(metasfreshVersion); return PrologMod.builder() .pkgMod(softwareMod) .generatorMod(createSoftwareMod(metasfreshVersion)) .build(); } private XMLGregorianCalendar asXmlCalendar(@NonNull final Calendar cal) { try { final GregorianCalendar gregorianCal = new GregorianCalendar(cal.getTimeZone()); gregorianCal.setTime(cal.getTime()); return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCal);
} catch (final DatatypeConfigurationException e) { throw new AdempiereException(e).appendParametersToMessage() .setParameter("cal", cal); } } private SoftwareMod createSoftwareMod(@NonNull final MetasfreshVersion metasfreshVersion) { final long versionNumber = metasfreshVersion.getMajor() * 100 + metasfreshVersion.getMinor(); // .. as advised in the documentation return SoftwareMod .builder() .name("metasfresh") .version(versionNumber) .description(metasfreshVersion.getFullVersion()) .id(0L) .copyright("Copyright (C) 2018 metas GmbH") .build(); } private BalanceMod createBalanceMod(@NonNull final DunningToExport dunning) { final Money amount = dunning.getAmount(); final Money alreadyPaidAmount = dunning.getAlreadyPaidAmount(); final BigDecimal amountDue = amount.getAmount().subtract(alreadyPaidAmount.getAmount()); return BalanceMod.builder() .currency(amount.getCurrency()) .amount(amount.getAmount()) .amountDue(amountDue) .build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\dunning\DunningExportClientImpl.java
1
请完成以下Java代码
public @NonNull ShipmentScheduleId getShipmentScheduleId() {return packageable.getShipmentScheduleId();} public @Nullable PickingJobScheduleId getPickingJobScheduleId() {return schedule != null ? schedule.getId() : null;} public @NonNull BPartnerId getCustomerId() {return packageable.getCustomerId();} public @NonNull String getCustomerName() {return packageable.getCustomerName();} public @NonNull BPartnerLocationId getCustomerLocationId() {return packageable.getCustomerLocationId();} public BPartnerLocationId getHandoverLocationId() {return packageable.getHandoverLocationId();} public String getCustomerAddress() {return packageable.getCustomerAddress();} public @NonNull InstantAndOrgId getPreparationDate() {return packageable.getPreparationDate();} public @NonNull InstantAndOrgId getDeliveryDate() {return packageable.getDeliveryDate();} public @Nullable OrderId getSalesOrderId() {return packageable.getSalesOrderId();} public @Nullable String getSalesOrderDocumentNo() {return packageable.getSalesOrderDocumentNo();} public @Nullable OrderAndLineId getSalesOrderAndLineIdOrNull() {return packageable.getSalesOrderAndLineIdOrNull();} public @Nullable WarehouseTypeId getWarehouseTypeId() {return packageable.getWarehouseTypeId();} public boolean isPartiallyPickedOrDelivered() { return packageable.getQtyPickedPlanned().signum() != 0 || packageable.getQtyPickedNotDelivered().signum() != 0 || packageable.getQtyPickedAndDelivered().signum() != 0; } public @NonNull ProductId getProductId() {return packageable.getProductId();} public @NonNull String getProductName() {return packageable.getProductName();}
public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();} public @NonNull Quantity getQtyToDeliver() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToDeliver(); } public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} public @NonNull Quantity getQtyToPick() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToPick(); } public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();} public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();} public @Nullable ShipperId getShipperId() {return packageable.getShipperId();} public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();} public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();} public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
1
请完成以下Java代码
public void debugNotAllowedToResolveCalledProcess(String calledProcessId, String callingProcessId, String callActivityId, Throwable cause) { logDebug("046", "Resolving a called process definition {} for {} in {} was not possible. Reason: {}", calledProcessId, callActivityId, callingProcessId, cause.getMessage()); } public void warnFilteringDuplicatesEnabledWithNullDeploymentName() { logWarn("047", "Deployment name set to null. Filtering duplicates will not work properly."); } public void warnReservedErrorCode(int initialCode) { logWarn("048", "With error code {} you are using a reserved error code. Falling back to default error code 0. " + "If you want to override built-in error codes, please disable the built-in error code provider.", initialCode); } public void warnResetToBuiltinCode(Integer builtinCode, int initialCode) { logWarn("049", "You are trying to override the built-in code {} with {}. " + "Falling back to built-in code. If you want to override built-in error codes, " + "please disable the built-in error code provider.", builtinCode, initialCode); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoJobsSpecified() { return new ProcessEngineException(exceptionMessage( "050", "You must specify at least one of jobIds or jobQuery.")); } public ProcessEngineException exceptionSettingJobRetriesAsyncNoProcessesSpecified() { return new ProcessEngineException(exceptionMessage( "051", "You must specify at least one of or one of processInstanceIds, processInstanceQuery, or historicProcessInstanceQuery.")); } public ProcessEngineException exceptionSettingJobRetriesJobsNotSpecifiedCorrectly() { return new ProcessEngineException(exceptionMessage( "052", "You must specify exactly one of jobId, jobIds or jobDefinitionId as parameter. The parameter can not be null."));
} public ProcessEngineException exceptionNoJobFoundForId(String jobId) { return new ProcessEngineException(exceptionMessage( "053", "No job found with id '{}'.'", jobId)); } public ProcessEngineException exceptionJobRetriesMustNotBeNegative(Integer retries) { return new ProcessEngineException(exceptionMessage( "054", "The number of job retries must be a non-negative Integer, but '{}' has been provided.", retries)); } public ProcessEngineException exceptionWhileRetrievingDiagnosticsDataRegistryNull() { return new ProcessEngineException( exceptionMessage("055", "Error while retrieving diagnostics data. Diagnostics registry was not initialized.")); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CommandLogger.java
1
请完成以下Java代码
public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunEntry.java
1
请完成以下Java代码
public static List<Integer> iterateConvert(int[] input) { List<Integer> output = new ArrayList<Integer>(); for (int value : input) { output.add(value); } return output; } public static List<Integer> streamConvert(int[] input) { List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList()); return output; } public static List<Integer> streamConvertIntStream(int[] input) { List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList());
return output; } public static List<Integer> guavaConvert(int[] input) { List<Integer> output = Ints.asList(input); return output; } public static List<Integer> apacheCommonConvert(int[] input) { Integer[] outputBoxed = ArrayUtils.toObject(input); List<Integer> output = Arrays.asList(outputBoxed); return output; } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\convertarrayprimitives\ConvertPrimitivesArrayToList.java
1
请在Spring Boot框架中完成以下Java代码
public class PatientHospital { @SerializedName("hospitalId") private String hospitalId = null; @SerializedName("dischargeDate") private LocalDate dischargeDate = null; public PatientHospital hospitalId(String hospitalId) { this.hospitalId = hospitalId; return this; } /** * Id der entlassenden Klinik (Voraussetzung, Alberta-Id ist bereits durch initialen Abgleich in WaWi vorhanden) * @return hospitalId **/ @Schema(example = "5ab2379c9d69c74b68cee819", description = "Id der entlassenden Klinik (Voraussetzung, Alberta-Id ist bereits durch initialen Abgleich in WaWi vorhanden)") public String getHospitalId() { return hospitalId; } public void setHospitalId(String hospitalId) { this.hospitalId = hospitalId; } public PatientHospital dischargeDate(LocalDate dischargeDate) { this.dischargeDate = dischargeDate; return this; } /** * letztes Entlassdatum aus der Klinik * @return dischargeDate **/ @Schema(example = "Thu Nov 21 00:00:00 GMT 2019", description = "letztes Entlassdatum aus der Klinik") public LocalDate getDischargeDate() { return dischargeDate; } public void setDischargeDate(LocalDate dischargeDate) { this.dischargeDate = dischargeDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientHospital patientHospital = (PatientHospital) o; return Objects.equals(this.hospitalId, patientHospital.hospitalId) && Objects.equals(this.dischargeDate, patientHospital.dischargeDate);
} @Override public int hashCode() { return Objects.hash(hospitalId, dischargeDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientHospital {\n"); sb.append(" hospitalId: ").append(toIndentedString(hospitalId)).append("\n"); sb.append(" dischargeDate: ").append(toIndentedString(dischargeDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientHospital.java
2
请完成以下Java代码
public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getExceptionStacktrace() { if (exceptionByteArrayRef == null) { return null; } byte[] bytes = exceptionByteArrayRef.getBytes(); if (bytes == null) { return null; } try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new ActivitiException("UTF-8 is not a supported encoding"); } } public void setExceptionStacktrace(String exception) { if (exceptionByteArrayRef == null) { exceptionByteArrayRef = new ByteArrayRef(); } exceptionByteArrayRef.setValue("stacktrace", getUtf8Bytes(exception)); } public String getExceptionMessage() { return exceptionMessage; }
public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } public ByteArrayRef getExceptionByteArrayRef() { return exceptionByteArrayRef; } protected byte[] getUtf8Bytes(String str) { if (str == null) { return null; } try { return str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new ActivitiException("UTF-8 is not a supported encoding"); } } @Override public String toString() { return getClass().getName() + " [id=" + id + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntityImpl.java
1
请完成以下Java代码
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_Value (COLUMNNAME_M_HazardSymbol_ID, null); else set_Value (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID() { return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID); } @Override public void setM_Product_HazardSymbol_ID (final int M_Product_HazardSymbol_ID) { if (M_Product_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_HazardSymbol_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_HazardSymbol_ID, M_Product_HazardSymbol_ID); } @Override public int getM_Product_HazardSymbol_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Product_HazardSymbol_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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_HazardSymbol.java
1
请在Spring Boot框架中完成以下Java代码
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public List<IdentityLinkEntity> getQueryIdentityLinks() { if (queryIdentityLinks == null) { queryIdentityLinks = new LinkedList<>(); } return queryIdentityLinks; } public void setQueryIdentityLinks(List<IdentityLinkEntity> identityLinks) { queryIdentityLinks = identityLinks; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("Task["); strb.append("id=").append(id); strb.append(", key=").append(taskDefinitionKey); strb.append(", name=").append(name); if (executionId != null) { strb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId) .append(", processDefinitionId=").append(processDefinitionId); } else if (scopeId != null) { strb.append(", scopeInstanceId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeDefinitionId=").append(scopeDefinitionId); } strb.append("]"); return strb.toString(); } @Override public boolean isCountEnabled() { return isCountEnabled; } public boolean getIsCountEnabled() { return isCountEnabled; } @Override public void setCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } public void setIsCountEnabled(boolean isCountEnabled) { this.isCountEnabled = isCountEnabled; } @Override public void setVariableCount(int variableCount) { this.variableCount = variableCount; } @Override public int getVariableCount() {
return variableCount; } @Override public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; } @Override public int getIdentityLinkCount() { return identityLinkCount; } @Override public int getSubTaskCount() { return subTaskCount; } @Override public void setSubTaskCount(int subTaskCount) { this.subTaskCount = subTaskCount; } @Override public boolean isIdentityLinksInitialized() { return isIdentityLinksInitialized; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\TaskEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class ResultDTO { @Id private Long customer_id; @Id private Long order_id; @Id private Long product_id; public void setCustomer_id(Long customer_id) { this.customer_id = customer_id; } public Long getProduct_id() { return product_id; } public void setProduct_id(Long product_id) { this.product_id = product_id; } public ResultDTO(Long customer_id, Long order_id, Long product_id, String customerName, String customerEmail, LocalDate orderDate, String productName, Double productPrice) { this.customer_id = customer_id; this.order_id = order_id; this.product_id = product_id; this.customerName = customerName; this.customerEmail = customerEmail; this.orderDate = orderDate; this.productName = productName; this.productPrice = productPrice; } private String customerName; private String customerEmail; private LocalDate orderDate; private String productName; private Double productPrice; public Long getCustomer_id() { return customer_id; } public void setCustoemr_id(Long custoemr_id) { this.customer_id = custoemr_id; } public String getCustomerName() {
return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerEmail() { return customerEmail; } public void setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; } public Long getOrder_id() { return order_id; } public void setOrder_id(Long order_id) { this.order_id = order_id; } public LocalDate getOrderDate() { return orderDate; } public void setOrderDate(LocalDate orderDate) { this.orderDate = orderDate; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getProductPrice() { return productPrice; } public void setProductPrice(Double productPrice) { this.productPrice = productPrice; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO.java
2
请完成以下Java代码
public class RandomGLNGenerator { private final Random random = new Random(); public GLN next() { StringBuilder gln = new StringBuilder(); // Step 1: Generate 12 random digits for (int i = 0; i < 12; i++) { gln.append(random.nextInt(10)); // Append a random digit (0-9) } // Step 2: Calculate the checksum digit int checksum = calculateChecksum(gln.toString()); // Step 3: Append the checksum to form the complete GLN gln.append(checksum); return GLN.ofString(gln.toString()); } private static int calculateChecksum(String gln) { int sum = 0; // Apply the EAN-13 checksum algorithm
for (int i = 0; i < gln.length(); i++) { int digit = Character.getNumericValue(gln.charAt(i)); //noinspection PointlessArithmeticExpression sum += (i % 2 == 0) ? digit * 1 : digit * 3; // Odd-position digits multiplied by 1, even by 3 } // Calculate the difference to the next multiple of 10 int nearestMultipleOfTen = (int)(Math.ceil(sum / 10.0) * 10); return nearestMultipleOfTen - sum; } public static void main(String[] args) { // Example usage final RandomGLNGenerator generator = new RandomGLNGenerator(); for(int i = 1; i <= 10; i++) { final GLN randomGLN = generator.next(); System.out.println("Random GLN: " + randomGLN); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\RandomGLNGenerator.java
1
请完成以下Java代码
class FixedBatchTrxItemProcessor<IT, RT> implements ITrxItemChunkProcessor<IT, RT> { /** * * @param processor the processor to be wrapped into the new instance. * @param itemsPerBatch the maximum number of items per chunk. If less or equal zero, then the given <code>processor</code> is not wrapped but just returned as-is * * @return an instance of this class that wraps the given <code>processor</code> (if <code>itemsPerBatch>0</code>). */ public static <IT, RT> ITrxItemProcessor<IT, RT> of(final ITrxItemProcessor<IT, RT> processor, final int itemsPerBatch) { if (itemsPerBatch <= 0) { return processor; } // in case of itemsPerBatch == 1 we might return the given processor *if* that given processor is not a ITrxItem*Chunk*Processor. return new FixedBatchTrxItemProcessor<>(processor, itemsPerBatch); } // Parameters private final ITrxItemChunkProcessor<IT, RT> processor; private final boolean ignoreProcessorIsSameChunkMethod; private final int maxItemsPerBatch; // State private int itemsPerBatch = 0; private FixedBatchTrxItemProcessor(final ITrxItemProcessor<IT, RT> processor, final int itemsPerBatch) { super(); Check.assumeNotNull(processor, "processor not null"); this.processor = TrxItemProcessor2TrxItemChunkProcessorWrapper.wrapIfNeeded(processor); this.ignoreProcessorIsSameChunkMethod = (this.processor instanceof TrxItemProcessor2TrxItemChunkProcessorWrapper); Check.assume(itemsPerBatch > 0, "itemsPerBatch > 0"); this.maxItemsPerBatch = itemsPerBatch; } @Override public String toString() { return "FixedBatchTrxItemProcessor[" + "itemsPerBatch=" + itemsPerBatch + "/" + maxItemsPerBatch + ", " + processor + "]"; } @Override public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx) { processor.setTrxItemProcessorCtx(processorCtx); } @Override public RT getResult() { return processor.getResult(); } @Override public void process(final IT item) throws Exception { itemsPerBatch++; processor.process(item); } @Override public boolean isSameChunk(final IT item) {
// If we are about to exceed the maximum number of items per batch // => return false (we need a new chunk/batch) if (itemsPerBatch >= maxItemsPerBatch) { return false; } // // Ask processor is the item is on the same chunk, if this is allowed. if (!ignoreProcessorIsSameChunkMethod) { return processor.isSameChunk(item); } // Consider this item on same chunk return true; } @Override public void newChunk(final IT item) { itemsPerBatch = 0; processor.newChunk(item); } @Override public void completeChunk() { processor.completeChunk(); } @Override public void cancelChunk() { processor.cancelChunk(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\FixedBatchTrxItemProcessor.java
1
请完成以下Java代码
public static int factorial(int i) { if (i == 0) { return 1; } return i * factorial(i - 1); } private static void printUseRecursion(int n) { for (int i = 0; i <= n; i++) { for (int j = 0; j <= n - i; j++) { System.out.print(" "); } for (int k = 0; k <= i; k++) { System.out.print(" " + factorial(i) / (factorial(i - k) * factorial(k))); } System.out.println(); } } public static void printUseBinomialExpansion(int n) { for (int line = 1; line <= n; line++) { for (int j = 0; j <= n - line; j++) { System.out.print(" "); } int k = 1;
for (int i = 1; i <= line; i++) { System.out.print(k + " "); k = k * (line - i) / i; } System.out.println(); } } public static void main(String[] args) { int n = 5; printUseRecursion(n); // printUseBinomialExpansion(n); } }
repos\tutorials-master\core-java-modules\core-java-lang-math-3\src\main\java\com\baeldung\math\pascaltriangle\PascalTriangle.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getServerPort() { return serverPort; } public ClusterClientConfig setServerPort(Integer serverPort) { this.serverPort = serverPort; return this; } public Integer getRequestTimeout() { return requestTimeout; } public ClusterClientConfig setRequestTimeout(Integer requestTimeout) { this.requestTimeout = requestTimeout; return this; }
public Integer getConnectTimeout() { return connectTimeout; } public ClusterClientConfig setConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; return this; } @Override public String toString() { return "ClusterClientConfig{" + "serverHost='" + serverHost + '\'' + ", serverPort=" + serverPort + ", requestTimeout=" + requestTimeout + ", connectTimeout=" + connectTimeout + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\config\ClusterClientConfig.java
2
请完成以下Java代码
protected final void addListenersToAttributeStorage(final IAttributeStorage attributeStorage) { // // Add listeners to our storage for (final IAttributeStorageListener listener : attributeStorageListeners) { attributeStorage.addListener(listener); } } /** * Removes current listeners from given {@link IAttributeStorage}. * * @param attributeStorage */ protected final void removeListenersFromAttributeStorage(final IAttributeStorage attributeStorage) { for (final IAttributeStorageListener listener : attributeStorageListeners) { attributeStorage.removeListener(listener); } } @Override public final IHUAttributesDAO getHUAttributesDAO() { Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null"); return huAttributesDAO; } @Override public final void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO();
} @Override public IHUStorageFactory getHUStorageFactory() { Check.assumeNotNull(huStorageFactory, "IHUStorageFactory member of AbstractAttributeStorageFactory {} is not null", this); return huStorageFactory; } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; } @Override public String toString() { final ToStringHelper stringHelper = MoreObjects.toStringHelper(this); toString(stringHelper); return stringHelper.toString(); } protected void toString(final ToStringHelper stringHelper) { // nothing on this level } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractAttributeStorageFactory.java
1
请完成以下Java代码
public void performSchemaOperationsProcessEngineClose() { String databaseSchemaUpdate = Context.getProcessEngineConfiguration().getDatabaseSchemaUpdate(); if (org.activiti.engine.ProcessEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP.equals(databaseSchemaUpdate)) { dbSchemaDrop(); } } public <T> T getCustomMapper(Class<T> type) { return sqlSession.getMapper(type); } public boolean isMysql() { return dbSqlSessionFactory.getDatabaseType().equals("mysql"); } public boolean isMariaDb() { return dbSqlSessionFactory.getDatabaseType().equals("mariadb"); } public boolean isOracle() { return dbSqlSessionFactory.getDatabaseType().equals("oracle"); } // query factory methods // //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ModelQueryImpl createModelQueryImpl() { return new ModelQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); }
public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); } public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请在Spring Boot框架中完成以下Java代码
public List<JobDto> queryAll(JobQueryCriteria criteria) { List<Job> list = jobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)); return jobMapper.toDto(list); } @Override public JobDto findById(Long id) { String key = CacheKey.JOB_ID + id; Job job = redisUtils.get(key, Job.class); if(job == null){ job = jobRepository.findById(id).orElseGet(Job::new); ValidationUtil.isNull(job.getId(),"Job","id",id); redisUtils.set(key, job, 1, TimeUnit.DAYS); } return jobMapper.toDto(job); } @Override @Transactional(rollbackFor = Exception.class) public void create(Job resources) { Job job = jobRepository.findByName(resources.getName()); if(job != null){ throw new EntityExistException(Job.class,"name",resources.getName()); } jobRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(Job resources) { Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new); Job old = jobRepository.findByName(resources.getName()); if(old != null && !old.getId().equals(resources.getId())){ throw new EntityExistException(Job.class,"name",resources.getName()); } ValidationUtil.isNull( job.getId(),"Job","id",resources.getId()); resources.setId(job.getId()); jobRepository.save(resources); // 删除缓存 delCaches(resources.getId()); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { jobRepository.deleteAllByIdIn(ids); // 删除缓存 redisUtils.delByKeys(CacheKey.JOB_ID, ids); }
@Override public void download(List<JobDto> jobDtos, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (JobDto jobDTO : jobDtos) { Map<String,Object> map = new LinkedHashMap<>(); map.put("岗位名称", jobDTO.getName()); map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用"); map.put("创建日期", jobDTO.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } @Override public void verification(Set<Long> ids) { if(userRepository.countByJobs(ids) > 0){ throw new BadRequestException("所选的岗位中存在用户关联,请解除关联再试!"); } } /** * 删除缓存 * @param id / */ public void delCaches(Long id){ redisUtils.del(CacheKey.JOB_ID + id); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\JobServiceImpl.java
2
请完成以下Java代码
private @NotNull String getAdLanguage() {return Env.getADLanguageOrBaseLanguage();} @PutMapping("/{warehouseId}/outOfStockNotice") public ResponseEntity<?> createShippingPackages( @PathVariable("warehouseId") @NonNull final String warehouseId, @RequestBody final JsonOutOfStockNoticeRequest request) { try { final JsonOutOfStockResponse response = warehouseService.handleOutOfStockRequest(warehouseId, request); return ResponseEntity.ok(response); } catch (final Exception ex) { Loggables.addLog(ex.getLocalizedMessage(), ex); return ResponseEntity.badRequest().body(JsonErrors.ofThrowable(ex, getAdLanguage())); } } @Operation(summary = "Create or update warehouses.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Successfully created or updated warehouse(s)"), @ApiResponse(responseCode = "401", description = "You are not authorized to create or update the resource"), @ApiResponse(responseCode = "403", description = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(responseCode = "422", description = "The request entity could not be processed") }) @PutMapping("{orgCode}")
public ResponseEntity<JsonResponseUpsert> upsertWarehouses( @Parameter(required = true, description = ORG_CODE_PARAMETER_DOC) @PathVariable("orgCode") @Nullable final String orgCode, // may be null if called from other metasfresh-code @RequestBody @NonNull final JsonRequestWarehouseUpsert request) { final JsonResponseUpsert responseUpsert = warehouseRestService.upsertWarehouses(orgCode, request); return ResponseEntity.ok(responseUpsert); } @GetMapping("/resolveLocator") @NonNull public JsonResolveLocatorResponse resolveLocatorScannedCode( @RequestParam("scannedBarcode") final String scannedBarcode) { try { return JsonResolveLocatorResponse.ok(warehouseRestService.resolveLocatorScannedCode(ScannedCode.ofString(scannedBarcode))); } catch (final Exception ex) { return JsonResolveLocatorResponse.error(ex, getAdLanguage()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\warehouse\WarehouseRestController.java
1
请完成以下Java代码
private DefaultMetadataElement parseVersionMetadata(JsonNode node) { String versionId = node.get("version").textValue(); Version version = VersionParser.DEFAULT.safeParse(versionId); if (version == null) { return null; } DefaultMetadataElement versionMetadata = new DefaultMetadataElement(); versionMetadata.setId(versionId); versionMetadata.setName(determineDisplayName(version)); versionMetadata.setDefault(node.get("current").booleanValue()); return versionMetadata; } private String determineDisplayName(Version version) { StringBuilder sb = new StringBuilder(); sb.append(version.getMajor()).append(".").append(version.getMinor()).append(".").append(version.getPatch()); if (version.getQualifier() != null) { sb.append(determineSuffix(version.getQualifier())); } return sb.toString(); } private String determineSuffix(Qualifier qualifier) { String id = qualifier.getId(); if (id.equals("RELEASE")) { return ""; } StringBuilder sb = new StringBuilder(" ("); if (id.contains("SNAPSHOT")) { sb.append("SNAPSHOT"); } else {
sb.append(id); if (qualifier.getVersion() != null) { sb.append(qualifier.getVersion()); } } sb.append(")"); return sb.toString(); } private static final class VersionMetadataElementComparator implements Comparator<DefaultMetadataElement> { private static final VersionParser versionParser = VersionParser.DEFAULT; @Override public int compare(DefaultMetadataElement o1, DefaultMetadataElement o2) { Version o1Version = versionParser.parse(o1.getId()); Version o2Version = versionParser.parse(o2.getId()); return o1Version.compareTo(o2Version); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\support\SpringBootMetadataReader.java
1
请完成以下Java代码
public T next() throws DBException { if (currentPO != null) { T po = currentPO; currentPO = null; return po; } try { if ( resultSet.next() ) { final PO o = TableModelLoader.instance.getPO(ctx, tableName, resultSet, trxName); if (clazz != null && !o.getClass().isAssignableFrom(clazz)) { return InterfaceWrapperHelper.create(o, clazz); } else { @SuppressWarnings("unchecked") final T retValue = (T)o; return retValue; } } else { this.close(); // close it if there is no more data to read return null; } } catch (SQLException e) { if (this.closeOnError) { this.close(); } throw new DBException(e); } // Catching any RuntimeException, and close the resultset (if closeOnError is set) catch (RuntimeException e) { if (this.closeOnError) { this.close(); } throw e; } }
/** * Should we automatically close the {@link PreparedStatement} and {@link ResultSet} in case * we get an error. * @param closeOnError */ public void setCloseOnError(boolean closeOnError) { this.closeOnError = closeOnError; } /** * Will be the {@link PreparedStatement} and {@link ResultSet} closed on any database exception * @return true if yes, false otherwise */ public boolean isCloseOnError() { return this.closeOnError; } /** * Release database resources. */ public void close() { DB.close(this.resultSet, this.statement); this.resultSet = null; this.statement = null; currentPO = null; } @Override public void remove() { throw new UnsupportedOperationException("Remove is not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POResultSet.java
1
请完成以下Java代码
public void setPP_Order_Candidate_ID (final int PP_Order_Candidate_ID) { if (PP_Order_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Candidate_ID, PP_Order_Candidate_ID); } @Override public int getPP_Order_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID); } @Override public org.eevolution.model.I_PP_Product_BOMVersions getPP_Product_BOMVersions() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class); } @Override public void setPP_Product_BOMVersions(final org.eevolution.model.I_PP_Product_BOMVersions PP_Product_BOMVersions) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMVersions_ID, org.eevolution.model.I_PP_Product_BOMVersions.class, PP_Product_BOMVersions); } @Override public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID) { if (PP_Product_BOMVersions_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID); }
@Override public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID); } @Override public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Maturing_Candidates_v.java
1
请在Spring Boot框架中完成以下Java代码
public void setCInvoiceID(BigInteger value) { this.cInvoiceID = value; } /** * Gets the value of the ediCctop120VID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getEDICctop120VID() { return ediCctop120VID; } /** * Sets the value of the ediCctop120VID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop120VID(BigInteger value) { this.ediCctop120VID = value; } /** * Gets the value of the isoCode property. * * @return * possible object is * {@link String } * */ public String getISOCode() { return isoCode; } /** * Sets the value of the isoCode property. * * @param value * allowed object is * {@link String } * */ public void setISOCode(String value) { this.isoCode = value; } /** * Gets the value of the netdate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getNetdate() { return netdate; } /** * Sets the value of the netdate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setNetdate(XMLGregorianCalendar value) { this.netdate = value; } /** * Gets the value of the netDays property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNetDays() { return netDays; } /** * Sets the value of the netDays property. * * @param value * allowed object is * {@link BigInteger }
* */ public void setNetDays(BigInteger value) { this.netDays = value; } /** * Gets the value of the singlevat property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSinglevat() { return singlevat; } /** * Sets the value of the singlevat property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSinglevat(BigDecimal value) { this.singlevat = value; } /** * Gets the value of the taxfree property. * * @return * possible object is * {@link String } * */ public String getTaxfree() { return taxfree; } /** * Sets the value of the taxfree property. * * @param value * allowed object is * {@link String } * */ public void setTaxfree(String value) { this.taxfree = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java
2
请完成以下Java代码
private AttributeSetInstanceId createAttributeSetInstance(@NonNull final CustomerReturnLineCandidate customerReturnLineCandidate) { final List<CreateAttributeInstanceReq> attributes = customerReturnLineCandidate.getCreateAttributeInstanceReqs(); if (attributes == null || attributes.isEmpty()) { return null; } final AddAttributesRequest addAttributesRequest = AddAttributesRequest.builder() .productId(customerReturnLineCandidate.getProductId()) .existingAttributeSetIdOrNone(AttributeSetInstanceId.NONE) .attributeInstanceBasicInfos(attributes) .build(); return attributeSetInstanceBL.addAttributes(addAttributesRequest); } private WarehouseId getWarehouseIdForReceivingReturnedGoods(@NonNull final ReturnedGoodsWarehouseType warehouseType) { final WarehouseId targetWarehouseId; switch (warehouseType) { case QUARANTINE: targetWarehouseId = warehousesRepo.retrieveQuarantineWarehouseId(); break; case QUALITY_ISSUE: targetWarehouseId = huWarehouseDAO.retrieveFirstQualityReturnWarehouseId(); break; default: throw new AdempiereException("The given ReturnedGoodsWarehouseType is not supported!") .appendParametersToMessage() .setParameter("ReturnedGoodsWarehouseType", warehouseType); } return targetWarehouseId; } @Value @Builder private static class CustomerReturnLineGroupingKey {
@NonNull OrgId orgId; @NonNull BPartnerLocationId bPartnerLocationId; @NonNull ReturnedGoodsWarehouseType warehouseType; @Nullable OrderId orderId; @Nullable LocalDate movementDate; @Nullable ZonedDateTime dateReceived; @Nullable String externalId; @Nullable String externalResourceURL; public static CustomerReturnLineGroupingKey of(@NonNull final CustomerReturnLineCandidate returnLineCandidate) { return CustomerReturnLineGroupingKey.builder() .orgId(returnLineCandidate.getOrgId()) .bPartnerLocationId(returnLineCandidate.getBPartnerLocationId()) .orderId(returnLineCandidate.getOrderId()) .movementDate(returnLineCandidate.getMovementDate()) .dateReceived(returnLineCandidate.getDateReceived()) .externalId(returnLineCandidate.getExternalId()) .externalResourceURL(returnLineCandidate.getExternalResourceURL()) .warehouseType(returnLineCandidate.getReturnedGoodsWarehouseType()) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnsWithoutHUsProducer.java
1
请完成以下Java代码
public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore;
} public List<String> getTenantIds() { return tenantIds; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public Collection<String> getProcessInstanceIds() { return processInstanceIds; } public Set<String> getCalledProcessInstanceIds() { return calledProcessInstanceIds; } public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) { this.calledProcessInstanceIds = calledProcessInstanceIds; } public List<List<String>> getSafeCalledProcessInstanceIds() { return safeCalledProcessInstanceIds; } public void setSafeCalledProcessInstanceIds(List<List<String>> safeCalledProcessInstanceIds) { this.safeCalledProcessInstanceIds = safeCalledProcessInstanceIds; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public class SecureChannelProcessor implements InitializingBean, ChannelProcessor { private ChannelEntryPoint entryPoint = new RetryWithHttpsEntryPoint(); private String secureKeyword = "REQUIRES_SECURE_CHANNEL"; @Override public void afterPropertiesSet() { Assert.hasLength(this.secureKeyword, "secureKeyword required"); Assert.notNull(this.entryPoint, "entryPoint required"); } @Override public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException { Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided"); for (ConfigAttribute attribute : config) { if (supports(attribute)) { if (!invocation.getHttpRequest().isSecure()) { HttpServletResponse response = invocation.getResponse(); Assert.notNull(response, "HttpServletResponse is required"); this.entryPoint.commence(invocation.getRequest(), response); } } } } public ChannelEntryPoint getEntryPoint() {
return this.entryPoint; } public String getSecureKeyword() { return this.secureKeyword; } public void setEntryPoint(ChannelEntryPoint entryPoint) { this.entryPoint = entryPoint; } public void setSecureKeyword(String secureKeyword) { this.secureKeyword = secureKeyword; } @Override public boolean supports(ConfigAttribute attribute) { return (attribute != null) && (attribute.getAttribute() != null) && attribute.getAttribute().equals(getSecureKeyword()); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\SecureChannelProcessor.java
1
请完成以下Java代码
public ColorUIResource getMenuItemBackground() { return WHITE; } @Override public ColorUIResource getToggleButtonCheckColor() { return new ColorUIResource(220, 241, 203); } @Override public void addCustomEntriesToTable(final UIDefaults table) { super.addCustomEntriesToTable(table); final Object[] uiDefaults = { "ScrollBar.thumbHighlight", getPrimaryControlHighlight(), PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(22), PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(30),
// TabbedPane // "TabbedPane.selected", getWhite(), "TabbedPane.selectHighlight", new ColorUIResource(231, 218, 188), "TabbedPane.unselectedBackground", null, // let AdempiereTabbedPaneUI calculate it AdempiereLookAndFeel.ERROR_BG_KEY, error, AdempiereLookAndFeel.ERROR_FG_KEY, txt_error, AdempiereLookAndFeel.INACTIVE_BG_KEY, inactive, AdempiereLookAndFeel.INFO_BG_KEY, info, AdempiereLookAndFeel.MANDATORY_BG_KEY, mandatory }; table.putDefaults(uiDefaults); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereTheme.java
1
请完成以下Java代码
public static boolean isClassField(String field, Class clazz){ Field[] fields = clazz.getDeclaredFields(); for(int i=0;i<fields.length;i++){ String fieldName = fields[i].getName(); String tableColumnName = oConvertUtils.camelToUnderline(fieldName); if(fieldName.equalsIgnoreCase(field) || tableColumnName.equalsIgnoreCase(field)){ return true; } } return false; } /** * 获取class的 包括父类的 * @param clazz * @return */ public static List<Field> getClassFields(Class<?> clazz) { List<Field> list = new ArrayList<Field>(); Field[] fields; do{ fields = clazz.getDeclaredFields(); for(int i = 0;i<fields.length;i++){ list.add(fields[i]); } clazz = clazz.getSuperclass(); }while(clazz!= Object.class&&clazz!=null); return list; } /** * 获取表字段名 * @param clazz * @param name * @return */ public static String getTableFieldName(Class<?> clazz, String name) { try { //如果字段加注解了@TableField(exist = false),不走DB查询 Field field = null; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { //e.printStackTrace(); } //如果为空,则去父类查找字段 if (field == null) { List<Field> allFields = getClassFields(clazz);
List<Field> searchFields = allFields.stream().filter(a -> a.getName().equals(name)).collect(Collectors.toList()); if(searchFields!=null && searchFields.size()>0){ field = searchFields.get(0); } } if (field != null) { TableField tableField = field.getAnnotation(TableField.class); if (tableField != null){ if(tableField.exist() == false){ //如果设置了TableField false 这个字段不需要处理 return null; }else{ String column = tableField.value(); //如果设置了TableField value 这个字段是实体字段 if(!"".equals(column)){ return column; } } } } } catch (Exception e) { e.printStackTrace(); } return name; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\ReflectHelper.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class HttpClientSettingsProperties { /** * Handling for HTTP redirects. */ private @Nullable HttpRedirects redirects; /** * Default connect timeout for a client HTTP request. */ private @Nullable Duration connectTimeout; /** * Default read timeout for a client HTTP request. */ private @Nullable Duration readTimeout; /** * Default SSL configuration for a client HTTP request. */ private final Ssl ssl = new Ssl(); public @Nullable HttpRedirects getRedirects() { return this.redirects; } public void setRedirects(@Nullable HttpRedirects redirects) { this.redirects = redirects; } public @Nullable Duration getConnectTimeout() { return this.connectTimeout; } public void setConnectTimeout(@Nullable Duration connectTimeout) { this.connectTimeout = connectTimeout; }
public @Nullable Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(@Nullable Duration readTimeout) { this.readTimeout = readTimeout; } public Ssl getSsl() { return this.ssl; } /** * SSL configuration. */ @ConfigurationPropertiesSource public static class Ssl { /** * SSL bundle to use. */ private @Nullable String bundle; public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\HttpClientSettingsProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class ApiRequestAudit { @Nullable // null, when the entity was not persisted yet ApiRequestAuditId apiRequestAuditId; @NonNull OrgId orgId; @NonNull RoleId roleId; @NonNull UserId userId; @NonNull ApiAuditConfigId apiAuditConfigId; @NonNull Status status; boolean isErrorAcknowledged; @Nullable String body; @Nullable HttpMethod method; @Nullable String path; @Nullable String remoteAddress; @Nullable String remoteHost; @NonNull Instant time; @Nullable String httpHeaders; @Nullable String requestURI; @Nullable PInstanceId pInstanceId; @Nullable UITraceExternalId uiTraceExternalId; @NonNull public ApiRequestAuditId getIdNotNull() { if (this.apiRequestAuditId == null) { throw new AdempiereException("getIdNotNull() should be called only for already persisted ApiRequestAudit objects!") .appendParametersToMessage() .setParameter("ApiRequestAudit", this); } return apiRequestAuditId; } @NonNull
public Optional<HttpHeadersWrapper> getRequestHeaders(@NonNull final ObjectMapper objectMapper) { if (Check.isBlank(httpHeaders)) { return Optional.empty(); } try { return Optional.of(objectMapper.readValue(httpHeaders, HttpHeadersWrapper.class)); } catch (final JsonProcessingException e) { throw new AdempiereException("Failed to parse httpHeaders!") .appendParametersToMessage() .setParameter("ApiAuditRequest", this); } } @NonNull public Optional<Object> getRequestBody(@NonNull final ObjectMapper objectMapper) { if (Check.isBlank(body)) { return Optional.empty(); } try { return Optional.of(objectMapper.readValue(body, Object.class)); } catch (final JsonProcessingException e) { throw new AdempiereException("Failed to parse body!") .appendParametersToMessage() .setParameter("ApiAuditRequest", this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\request\ApiRequestAudit.java
2
请完成以下Java代码
public int getPP_Order_Report_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Report_ID); if (ii == null) return 0; return ii.intValue(); } /** * ProductionMaterialType AD_Reference_ID=540506 * Reference name: PP_Order_Report_ProductionMaterialType */ public static final int PRODUCTIONMATERIALTYPE_AD_Reference_ID=540506; /** RawMaterial = R */ public static final String PRODUCTIONMATERIALTYPE_RawMaterial = "R"; /** ProducedMaterial = P */ public static final String PRODUCTIONMATERIALTYPE_ProducedMaterial = "P"; /** ProducedMaterial = S */ public static final String PRODUCTIONMATERIALTYPE_Scrap = "S"; /** Set Production Material Type. @param ProductionMaterialType Production Material Type */ @Override public void setProductionMaterialType (java.lang.String ProductionMaterialType) { set_Value (COLUMNNAME_ProductionMaterialType, ProductionMaterialType); } /** Get Production Material Type. @return Production Material Type */ @Override public java.lang.String getProductionMaterialType () { return (java.lang.String)get_Value(COLUMNNAME_ProductionMaterialType); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null) return Env.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set VariantGroup. @param VariantGroup VariantGroup */ @Override public void setVariantGroup (java.lang.String VariantGroup) { set_Value (COLUMNNAME_VariantGroup, VariantGroup); } /** Get VariantGroup. @return VariantGroup */ @Override public java.lang.String getVariantGroup () { return (java.lang.String)get_Value(COLUMNNAME_VariantGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Report.java
1
请完成以下Java代码
public boolean isEMUMember () { Object oo = get_Value(COLUMNNAME_IsEMUMember); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set The Euro Currency. @param IsEuro This currency is the Euro */ @Override public void setIsEuro (boolean IsEuro) { set_Value (COLUMNNAME_IsEuro, Boolean.valueOf(IsEuro)); } /** Get The Euro Currency. @return This currency is the Euro */ @Override public boolean isEuro () { Object oo = get_Value(COLUMNNAME_IsEuro); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Währungscode. @param ISO_Code Three letter ISO 4217 Code of the Currency */ @Override public void setISO_Code (java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code); } /** Get ISO Währungscode. @return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Round Off Factor. @param RoundOffFactor Used to Round Off Payment Amount */ @Override public void setRoundOffFactor (java.math.BigDecimal RoundOffFactor) { set_Value (COLUMNNAME_RoundOffFactor, RoundOffFactor);
} /** Get Round Off Factor. @return Used to Round Off Payment Amount */ @Override public java.math.BigDecimal getRoundOffFactor () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoundOffFactor); if (bd == null) return Env.ZERO; return bd; } /** Set Standardgenauigkeit. @param StdPrecision Rule for rounding calculated amounts */ @Override public void setStdPrecision (int StdPrecision) { set_Value (COLUMNNAME_StdPrecision, Integer.valueOf(StdPrecision)); } /** Get Standardgenauigkeit. @return Rule for rounding calculated amounts */ @Override public int getStdPrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_StdPrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getAllowedOrigins() { return this.allowedOrigins; } public void setAllowedOrigins(List<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public List<String> getAllowedOriginPatterns() { return this.allowedOriginPatterns; } public void setAllowedOriginPatterns(List<String> allowedOriginPatterns) { this.allowedOriginPatterns = allowedOriginPatterns; } public List<String> getAllowedMethods() { return this.allowedMethods; } public void setAllowedMethods(List<String> allowedMethods) { this.allowedMethods = allowedMethods; } public List<String> getAllowedHeaders() { return this.allowedHeaders; } public void setAllowedHeaders(List<String> allowedHeaders) { this.allowedHeaders = allowedHeaders; } public List<String> getExposedHeaders() { return this.exposedHeaders; } public void setExposedHeaders(List<String> exposedHeaders) { this.exposedHeaders = exposedHeaders; } public @Nullable Boolean getAllowCredentials() { return this.allowCredentials; }
public void setAllowCredentials(@Nullable Boolean allowCredentials) { this.allowCredentials = allowCredentials; } public Duration getMaxAge() { return this.maxAge; } public void setMaxAge(Duration maxAge) { this.maxAge = maxAge; } public @Nullable CorsConfiguration toCorsConfiguration() { if (CollectionUtils.isEmpty(this.allowedOrigins) && CollectionUtils.isEmpty(this.allowedOriginPatterns)) { return null; } PropertyMapper map = PropertyMapper.get(); CorsConfiguration configuration = new CorsConfiguration(); map.from(this::getAllowedOrigins).to(configuration::setAllowedOrigins); map.from(this::getAllowedOriginPatterns).to(configuration::setAllowedOriginPatterns); map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedHeaders); map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedMethods); map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setExposedHeaders); map.from(this::getMaxAge).as(Duration::getSeconds).to(configuration::setMaxAge); map.from(this::getAllowCredentials).to(configuration::setAllowCredentials); return configuration; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\CorsEndpointProperties.java
2
请完成以下Java代码
public String getTitle() { return title; } public String getAuthor() { return author; } @Override public String toString() { return "Book [title=" + title + ", author=" + author + "]"; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
final Book book = (Book) o; if (!Objects.equals(title, book.title)) { return false; } return Objects.equals(author, book.author); } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (author != null ? author.hashCode() : 0); return result; } }
repos\tutorials-master\core-java-modules\core-java-9-jigsaw\library-core\src\main\java\com\baeldung\library\core\Book.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() {
return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final PInstanceId selectionId = createSelection(); ddOrderCandidateService.enqueueToProcess(selectionId); return MSG_OK; } protected PInstanceId createSelection() { final IQueryBuilder<I_DD_Order_Candidate> queryBuilder = selectionQueryBuilder(); final PInstanceId adPInstanceId = Check.assumeNotNull(getPinstanceId(), "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); final int count = queryBuilder .create() .setRequiredAccess(Access.READ) .createSelection(adPInstanceId); if (count <= 0) { throw new AdempiereException("@NoSelection@"); } return adPInstanceId; }
protected IQueryBuilder<I_DD_Order_Candidate> selectionQueryBuilder() { final IQueryFilter<I_DD_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_DD_Order_Candidate.class) .addEqualsFilter(I_DD_Order_Candidate.COLUMNNAME_Processed, false) .addCompareFilter(I_DD_Order_Candidate.COLUMNNAME_QtyToProcess, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter() .orderBy(I_DD_Order_Candidate.COLUMNNAME_DD_Order_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\distribution\webui\process\DD_Order_Candidate_EnqueueToProcess.java
1
请完成以下Java代码
public class TimerFiredListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNTimerFiredEvent>> processRuntimeEventListeners; private ToTimerFiredConverter converter; public TimerFiredListenerDelegate( List<BPMNElementEventListener<BPMNTimerFiredEvent>> processRuntimeEventListeners, ToTimerFiredConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override
public void onEvent(ActivitiEvent event) { converter .from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerFiredEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TimerFiredListenerDelegate.java
1
请完成以下Java代码
protected ValueNamePair[] getCount (String DateFormat) { ArrayList<ValueNamePair> list = new ArrayList<ValueNamePair>(); String sql = "SELECT TRUNC(Created, '" + DateFormat + "'), Count(*) " + "FROM W_Click " + "WHERE W_ClickCount_ID=? " + "GROUP BY TRUNC(Created, '" + DateFormat + "')"; // PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, getW_ClickCount_ID()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String value = m_dateFormat.format(rs.getTimestamp(1)); String name = m_intFormat.format(rs.getInt(2)); ValueNamePair pp = ValueNamePair.of(value, name); list.add(pp); } rs.close(); pstmt.close(); pstmt = null; } catch (SQLException ex) { log.error(sql, ex); } try { if (pstmt != null) pstmt.close(); } catch (SQLException ex1) { } pstmt = null; // ValueNamePair[] retValue = new ValueNamePair[list.size()]; list.toArray(retValue); return retValue; } // getCount /** * Get Monthly Count * @return monthly count */ public ValueNamePair[] getCountQuarter () { return getCount("Q"); } // getCountQuarter /** * Get Monthly Count * @return monthly count
*/ public ValueNamePair[] getCountMonth () { return getCount("MM"); } // getCountMonth /** * Get Weekly Count * @return weekly count */ public ValueNamePair[] getCountWeek () { return getCount("DY"); } // getCountWeek /** * Get Daily Count * @return dailt count */ public ValueNamePair[] getCountDay () { return getCount("J"); } // getCountDay } // MClickCount
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClickCount.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isRunning() { return false; } @Override public void afterPropertiesSet() { Assert.notNull(debeziumEngine, "DebeZiumEngine 不能为空!"); } public enum ThreadPoolEnum { /** * 实例 */ INSTANCE; public static final String SQL_SERVER_LISTENER_POOL = "sql-server-listener-pool"; /** * 线程池单例 */ private final ExecutorService es; /** * 枚举 (构造器默认为私有) */ ThreadPoolEnum() { final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(SQL_SERVER_LISTENER_POOL + "-%d").build(); es = new ThreadPoolExecutor(8, 16, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(256),
threadFactory, new ThreadPoolExecutor.DiscardPolicy()); } /** * 公有方法 * * @return ExecutorService */ public ExecutorService getInstance() { return es; } } } }
repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\config\ChangeEventConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class DecisionServiceImpl extends ServiceImpl implements DecisionService { public DmnDecisionTableResult evaluateDecisionTableById(String decisionDefinitionId, Map<String, Object> variables) { return evaluateDecisionTableById(decisionDefinitionId) .variables(variables) .evaluate(); } public DmnDecisionTableResult evaluateDecisionTableByKey(String decisionDefinitionKey, Map<String, Object> variables) { return evaluateDecisionTableByKey(decisionDefinitionKey) .variables(variables) .evaluate(); } public DmnDecisionTableResult evaluateDecisionTableByKeyAndVersion(String decisionDefinitionKey, Integer version, Map<String, Object> variables) { return evaluateDecisionTableByKey(decisionDefinitionKey) .version(version) .variables(variables) .evaluate();
} public DecisionEvaluationBuilder evaluateDecisionTableByKey(String decisionDefinitionKey) { return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableByKey(commandExecutor, decisionDefinitionKey); } public DecisionEvaluationBuilder evaluateDecisionTableById(String decisionDefinitionId) { return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableById(commandExecutor, decisionDefinitionId); } public DecisionsEvaluationBuilder evaluateDecisionByKey(String decisionDefinitionKey) { return DecisionEvaluationBuilderImpl.evaluateDecisionByKey(commandExecutor, decisionDefinitionKey); } public DecisionsEvaluationBuilder evaluateDecisionById(String decisionDefinitionId) { return DecisionEvaluationBuilderImpl.evaluateDecisionById(commandExecutor, decisionDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DecisionServiceImpl.java
2
请完成以下Java代码
public List<HistoricActivityInstance> findHistoricActivityInstancesByQueryCriteria(HistoricActivityInstanceQueryImpl historicActivityInstanceQuery, Page page) { configureQuery(historicActivityInstanceQuery); return getDbEntityManager().selectList("selectHistoricActivityInstancesByQueryCriteria", historicActivityInstanceQuery, page); } @SuppressWarnings("unchecked") public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return getDbEntityManager().selectListWithRawParameter("selectHistoricActivityInstanceByNativeQuery", parameterMap, firstResult, maxResults); } public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbEntityManager().selectOne("selectHistoricActivityInstanceCountByNativeQuery", parameterMap); } protected void configureQuery(HistoricActivityInstanceQueryImpl query) { getAuthorizationManager().configureHistoricActivityInstanceQuery(query); getTenantManager().configureQuery(query); } public DbOperation addRemovalTimeToActivityInstancesByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToActivityInstancesByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByProcessInstanceId", parameters);
} public DbOperation deleteHistoricActivityInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(HistoricActivityInstanceEntity.class, "deleteHistoricActivityInstancesByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityInstanceManager.java
1
请完成以下Java代码
public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return getSqlParams(); } public List<Object> getSqlParams() { buildSqlIfNeeded(); return sqlParams; } private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql();
} else { sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请完成以下Java代码
public class MHUProcessDAO implements IMHUProcessDAO { private final CCache<Integer, IndexedHUProcessDescriptors> huProcessDescriptors = CCache.newCache(I_M_HU_Process.Table_Name, 1, CCache.EXPIREMINUTES_Never); @Override public Collection<HUProcessDescriptor> getHUProcessDescriptors() { return getIndexedHUProcessDescriptors().getAsCollection(); } @Override public HUProcessDescriptor getByProcessIdOrNull(@NonNull final AdProcessId processId) { return getIndexedHUProcessDescriptors().getByProcessIdOrNull(processId); } private IndexedHUProcessDescriptors getIndexedHUProcessDescriptors() { return huProcessDescriptors.getOrLoad(0, this::retrieveIndexedHUProcessDescriptors); } private IndexedHUProcessDescriptors retrieveIndexedHUProcessDescriptors() { final ImmutableList<HUProcessDescriptor> huProcessDescriptors = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_M_HU_Process.class) .addOnlyActiveRecordsFilter() .create() .stream(I_M_HU_Process.class) .map(MHUProcessDAO::toHUProcessDescriptor) .collect(ImmutableList.toImmutableList()); return new IndexedHUProcessDescriptors(huProcessDescriptors); } private static HUProcessDescriptor toHUProcessDescriptor(final I_M_HU_Process huProcessRecord) { final HUProcessDescriptorBuilder builder = HUProcessDescriptor.builder() .processId(AdProcessId.ofRepoId(huProcessRecord.getAD_Process_ID())) .internalName(huProcessRecord.getAD_Process().getValue());
if (huProcessRecord.isApplyToLUs()) { builder.acceptHUUnitType(HuUnitType.LU); } if (huProcessRecord.isApplyToTUs()) { builder.acceptHUUnitType(HuUnitType.TU); } if (huProcessRecord.isApplyToCUs()) { builder.acceptHUUnitType(HuUnitType.VHU); } builder.provideAsUserAction(huProcessRecord.isProvideAsUserAction()); builder.acceptOnlyTopLevelHUs(huProcessRecord.isApplyToTopLevelHUsOnly()); return builder.build(); } private static final class IndexedHUProcessDescriptors { private final ImmutableMap<AdProcessId, HUProcessDescriptor> huProcessDescriptorsByProcessId; private IndexedHUProcessDescriptors(final List<HUProcessDescriptor> huProcessDescriptors) { huProcessDescriptorsByProcessId = Maps.uniqueIndex(huProcessDescriptors, HUProcessDescriptor::getProcessId); } public Collection<HUProcessDescriptor> getAsCollection() { return huProcessDescriptorsByProcessId.values(); } public HUProcessDescriptor getByProcessIdOrNull(final AdProcessId processId) { return huProcessDescriptorsByProcessId.get(processId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\api\impl\MHUProcessDAO.java
1
请完成以下Java代码
public void planOperation(Runnable operation) { operations.add(operation); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Operation {} added to agenda", operation.getClass()); } } @Override public <V> void planFutureOperation(CompletableFuture<V> future, BiConsumer<V, Throwable> completeAction) { ExecuteFutureActionOperation<V> operation = new ExecuteFutureActionOperation<>(future, completeAction); if (future.isDone()) { // If the future is done, then plan the operation first (this makes sure that the complete action is invoked before any other operation is run) operations.addFirst(operation); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Operation {} added to agenda", operation.getClass()); } } else { futureOperations.add(operation); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Future {} with action {} added to agenda", future, completeAction.getClass()); } } } protected Duration getFutureMaxWaitTimeout() { AgendaFutureMaxWaitTimeoutProvider futureOperationTimeoutProvider = getAgendaFutureMaxWaitTimeoutProvider();
return futureOperationTimeoutProvider != null ? futureOperationTimeoutProvider.getMaxWaitTimeout(commandContext) : null; } public LinkedList<Runnable> getOperations() { return operations; } public CommandContext getCommandContext() { return commandContext; } public void setCommandContext(CommandContext commandContext) { this.commandContext = commandContext; } protected abstract AgendaFutureMaxWaitTimeoutProvider getAgendaFutureMaxWaitTimeoutProvider(); @Override public void flush() { } @Override public void close() { } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\agenda\AbstractAgenda.java
1
请在Spring Boot框架中完成以下Java代码
public class StockChangeDetailRepo { @Nullable public StockChangeDetail getSingleForCandidateRecordOrNull(@NonNull final CandidateId candidateId) { final I_MD_Candidate_StockChange_Detail stockChangeDetailRecord = RepositoryCommons .createCandidateDetailQueryBuilder(candidateId, I_MD_Candidate_StockChange_Detail.class) .firstOnly(I_MD_Candidate_StockChange_Detail.class); return ofRecord(stockChangeDetailRecord); } public void saveOrUpdate( @Nullable final StockChangeDetail stockChangeDetail, @NonNull final I_MD_Candidate candidateRecord) { if (stockChangeDetail == null) { return; } final CandidateId candidateId = CandidateId.ofRepoId(candidateRecord.getMD_Candidate_ID()); I_MD_Candidate_StockChange_Detail recordToUpdate = RepositoryCommons.retrieveSingleCandidateDetail( candidateId, I_MD_Candidate_StockChange_Detail.class); if (recordToUpdate == null) { recordToUpdate = newInstance(I_MD_Candidate_StockChange_Detail.class, candidateRecord); recordToUpdate.setMD_Candidate_ID(candidateId.getRepoId()); } recordToUpdate.setFresh_QtyOnHand_ID(NumberUtils.asInteger(stockChangeDetail.getFreshQuantityOnHandRepoId(), -1)); recordToUpdate.setFresh_QtyOnHand_Line_ID(NumberUtils.asInteger(stockChangeDetail.getFreshQuantityOnHandLineRepoId(), -1)); recordToUpdate.setM_Inventory_ID(NumberUtils.asInteger(stockChangeDetail.getInventoryId(), -1)); recordToUpdate.setM_InventoryLine_ID(NumberUtils.asInteger(stockChangeDetail.getInventoryLineId(), -1)); recordToUpdate.setIsReverted(Boolean.TRUE.equals(stockChangeDetail.getIsReverted()));
recordToUpdate.setEventDateMaterialDispo(TimeUtil.asTimestamp(stockChangeDetail.getEventDate())); saveRecord(recordToUpdate); } @Nullable private StockChangeDetail ofRecord(@Nullable final I_MD_Candidate_StockChange_Detail record) { if (record == null) { return null; } final Integer computedFreshQtyOnHandId = NumberUtils.asIntegerOrNull(record.getFresh_QtyOnHand_ID()); final Integer computedFreshQtyOnHandLineId = NumberUtils.asIntegerOrNull(record.getFresh_QtyOnHand_Line_ID()); return StockChangeDetail.builder() .candidateStockChangeDetailId(CandidateStockChangeDetailId.ofRepoId(record.getMD_Candidate_StockChange_Detail_ID())) .candidateId(CandidateId.ofRepoId(record.getMD_Candidate_ID())) .freshQuantityOnHandRepoId(computedFreshQtyOnHandId) .freshQuantityOnHandLineRepoId(computedFreshQtyOnHandLineId) .inventoryId(InventoryId.ofRepoIdOrNull(record.getM_Inventory_ID())) .inventoryLineId(InventoryLineId.ofRepoIdOrNull(record.getM_InventoryLine_ID())) .isReverted(record.isReverted()) .eventDate(TimeUtil.asInstantNonNull(record.getEventDateMaterialDispo())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\repohelpers\StockChangeDetailRepo.java
2
请完成以下Java代码
public void cacheReset() { final int size = cache.size(); cache.clear(); logger.trace("cacheReset: {} entries after cleanup", size); } public Optional<KPIZoomIntoDetailsInfo> getZoomIntoDetailsInfo(@NonNull final KPIDataRequest request) { final KPIDataContext context = request.getContext(); final KPITimeRangeDefaults timeRangeDefaults = request.getTimeRangeDefaults(); final TimeRange timeRange = timeRangeDefaults.createTimeRange(context.getFrom(), context.getTo()); final KPI kpi = kpiRepository.getKPI(request.getKpiId()); final KPIDatasourceType dataSourceType = kpi.getDatasourceType(); if (dataSourceType == KPIDatasourceType.SQL) { return Optional.of( SQLKPIDataLoader.builder() .permissionsProvider(kpiPermissionsProvider) .kpi(kpi) .timeRange(timeRange) .context(context) .build() .getKPIZoomIntoDetailsInfo()); } else { return Optional.empty(); } } // // // ----------------------------------------- // // @Value @Builder private static class KPIDataCacheKey { @NonNull KPIId kpiId;
@NonNull KPITimeRangeDefaults timeRangeDefaults; @NonNull KPIDataContext context; } @Value @ToString(exclude = "data" /* because it's too big */) private static class KPIDataCacheValue { public static KPIDataCacheValue ok(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted) { return new KPIDataCacheValue(data, defaultMaxStaleAccepted); } @NonNull Instant created = SystemTime.asInstant(); @NonNull Duration defaultMaxStaleAccepted; KPIDataResult data; public KPIDataCacheValue(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted) { this.data = data; this.defaultMaxStaleAccepted = defaultMaxStaleAccepted; } public boolean isExpired() { return isExpired(null); } public boolean isExpired(@Nullable final Duration maxStaleAccepted) { final Duration maxStaleAcceptedEffective = maxStaleAccepted != null ? maxStaleAccepted : defaultMaxStaleAccepted; final Instant now = SystemTime.asInstant(); final Duration staleActual = Duration.between(created, now); final boolean expired = staleActual.compareTo(maxStaleAcceptedEffective) > 0; logger.trace("isExpired={}, now={}, maxStaleAcceptedEffective={}, staleActual={}, cacheValue={}", expired, now, maxStaleAcceptedEffective, staleActual, this); return expired; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataProvider.java
1
请完成以下Java代码
public class V1_1__FixUsername extends BaseJavaMigration { private Logger logger = LoggerFactory.getLogger(getClass()); @Override public void migrate(Context context) throws Exception { // 创建 JdbcTemplate ,方便 JDBC 操作 JdbcTemplate template = new JdbcTemplate(context.getConfiguration().getDataSource()); // 查询所有用户,如果用户名为 yudaoyuanma ,则变更成 yutou template.query("SELECT id, username, password, create_time FROM users", new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { // 遍历返回的结果 do { String username = rs.getString("username"); if ("yudaoyuanma".equals(username)) { Integer id = rs.getInt("id"); template.update("UPDATE users SET username = ? WHERE id = ?", "yutou", id); logger.info("[migrate][更新 user({}) 的用户名({} => {})", id, username, "yutou"); } } while (rs.next()); } }); }
@Override public Integer getChecksum() { return 11; // 默认返回,是 null 。 } @Override public boolean canExecuteInTransaction() { return true; // 默认返回,也是 true } @Override public MigrationVersion getVersion() { return super.getVersion(); // 默认按照约定的规则,从类名中解析获得。可以自定义 } }
repos\SpringBoot-Labs-master\lab-20\lab-20-database-version-control-flyway\src\main\java\cn\iocoder\springboot\lab20\databaseversioncontrol\migration\V1_1__FixUsername.java
1
请完成以下Java代码
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Nullable public ProductId getProductId() { return product != null ? ProductId.ofRepoIdOrNull(product.getKeyAsInt()) : null; } @Nullable public UomId getUomId() { return uom == null ? null : UomId.ofRepoIdOrNull(uom.getKeyAsInt()); } private JSONLookupValue getClearanceStatus() { return clearanceStatus; } @Nullable public I_C_UOM getUom() { final UomId uomId = getUomId(); if (uomId == null) { return null; } final IUOMDAO uomDAO = Services.get(IUOMDAO.class); return uomDAO.getById(uomId); } @NonNull public I_C_UOM getUomNotNull() { return Check.assumeNotNull(getUom(), "Expecting UOM to always be present when using this method!"); } public boolean isReceipt() { return getType().canReceive(); } public boolean isIssue() { return getType().canIssue(); } public boolean isHUStatusActive() { return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey()); } @Override
public boolean hasAttributes() { return attributesSupplier != null; } @Override public IViewRowAttributes getAttributes() throws EntityNotFoundException { if (attributesSupplier == null) { throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this); } final IViewRowAttributes attributes = attributesSupplier.get(); if (attributes == null) { throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this); } return attributes; } @Override public HuUnitType getHUUnitTypeOrNull() {return huUnitType;} @Override public BPartnerId getBpartnerId() {return huBPartnerId;} @Override public boolean isTopLevel() {return topLevelHU;} @Override public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);} private HUReportAwareViewRow toHUReportAwareViewRow() {return this;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java
1
请完成以下Java代码
public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] params ) { return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params); } @Override public String toString() { return name; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name); } public int getIndex() {
return index; } public String getName() { return name; } public int getCardinality() { return 0; } public AstNode getChild(int i) { return null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java
1
请完成以下Java代码
public void missingIsExecutableAttribute(String elementId) { logInfo("003", "Process with id '{}' has no attribute isExecutable. Better set the attribute explicitly, " + "especially to be compatible with future engine versions which might change the default behavior.", elementId); } public void parsingFailure(Throwable cause) { logError("004", "Unexpected Exception with message: {} ", cause.getMessage()); } public void intermediateCatchTimerEventWithTimeCycleNotRecommended(String definitionKey, String elementId) { logInfo("005", "definitionKey: {}; It is not recommended to use an intermediate catch timer event with a time cycle, " + "element with id '{}'.", definitionKey, elementId); } // EXCEPTIONS
public ProcessEngineException parsingProcessException(Exception cause) { return new ProcessEngineException(exceptionMessage("009", "Error while parsing process. {}.", cause.getMessage()), cause); } public void exceptionWhileGeneratingProcessDiagram(Throwable t) { logError( "010", "Error while generating process diagram, image will not be stored in repository", t); } public ProcessEngineException messageEventSubscriptionWithSameNameExists(String resourceName, String eventName) { throw new ProcessEngineException(exceptionMessage( "011", "Cannot deploy process definition '{}': there already is a message event subscription for the message with name '{}'.", resourceName, eventName)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParseLogger.java
1
请完成以下Java代码
public Iterable<Row> currentPage() { return delegate.currentPage(); } @Override public boolean hasMorePages() { return delegate.hasMorePages(); } @NonNull @Override public CompletionStage<AsyncResultSet> fetchNextPage() throws IllegalStateException { return delegate.fetchNextPage(); } @Override public boolean wasApplied() { return delegate.wasApplied(); } public ListenableFuture<List<Row>> allRows(Executor executor) { List<Row> allRows = new ArrayList<>(); SettableFuture<List<Row>> resultFuture = SettableFuture.create(); this.processRows(originalStatement, delegate, allRows, resultFuture, executor); return resultFuture; } private void processRows(Statement statement, AsyncResultSet resultSet, List<Row> allRows, SettableFuture<List<Row>> resultFuture, Executor executor) { allRows.addAll(loadRows(resultSet)); if (resultSet.hasMorePages()) { ByteBuffer nextPagingState = resultSet.getExecutionInfo().getPagingState(); Statement<?> nextStatement = statement.setPagingState(nextPagingState); TbResultSetFuture resultSetFuture = executeAsyncFunction.apply(nextStatement); Futures.addCallback(resultSetFuture, new FutureCallback<TbResultSet>() {
@Override public void onSuccess(@Nullable TbResultSet result) { processRows(nextStatement, result, allRows, resultFuture, executor); } @Override public void onFailure(Throwable t) { resultFuture.setException(t); } }, executor != null ? executor : MoreExecutors.directExecutor() ); } else { resultFuture.set(allRows); } } List<Row> loadRows(AsyncResultSet resultSet) { return Lists.newArrayList(resultSet.currentPage()); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\nosql\TbResultSet.java
1
请完成以下Java代码
public class X_C_BPartner_Attribute2 extends org.compiere.model.PO implements I_C_BPartner_Attribute2, org.compiere.model.I_Persistent { private static final long serialVersionUID = 451491893L; /** Standard Constructor */ public X_C_BPartner_Attribute2 (final Properties ctx, final int C_BPartner_Attribute2_ID, @Nullable final String trxName) { super (ctx, C_BPartner_Attribute2_ID, trxName); } /** Load Constructor */ public X_C_BPartner_Attribute2 (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * Attributes2 AD_Reference_ID=541333 * Reference name: Attributes2 */ public static final int ATTRIBUTES2_AD_Reference_ID=541333; @Override public void setAttributes2 (final java.lang.String Attributes2) { set_Value (COLUMNNAME_Attributes2, Attributes2); } @Override public java.lang.String getAttributes2() { return get_ValueAsString(COLUMNNAME_Attributes2); } @Override public void setC_BPartner_Attribute2_ID (final int C_BPartner_Attribute2_ID) { if (C_BPartner_Attribute2_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute2_ID, null); else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute2_ID, C_BPartner_Attribute2_ID); } @Override public int getC_BPartner_Attribute2_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Attribute2_ID); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Attribute2.java
1
请完成以下Java代码
public Element readInput(Reader input) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { LOG.parsingInput(); return documentBuilder.parse(new InputSource(input)).getDocumentElement(); } catch (SAXException e) { throw LOG.unableToParseInput(e); } catch (IOException e) { throw LOG.unableToParseInput(e); } } /** * @return the DocumentBuilder used by this reader
*/ protected DocumentBuilder getDocumentBuilder() { try { DocumentBuilder docBuilder = dataFormat.getDocumentBuilderFactory().newDocumentBuilder(); LOG.createdDocumentBuilder(); return docBuilder; } catch (ParserConfigurationException e) { throw LOG.unableToCreateParser(e); } } protected Pattern getInputDetectionPattern() { return INPUT_MATCHING_PATTERN; } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatReader.java
1
请在Spring Boot框架中完成以下Java代码
public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEvent() == ComponentLifecycleEvent.DELETED) { EntityId entityId = event.getEntityId(); switch (entityId.getEntityType()) { case NOTIFICATION_REQUEST: cancelAndRemove((NotificationRequestId) entityId); break; case TENANT: Set<NotificationRequestId> toCancel = new HashSet<>(); scheduledNotificationRequests.forEach((notificationRequestId, scheduledRequestMetadata) -> { if (scheduledRequestMetadata.getTenantId().equals(entityId)) { toCancel.add(notificationRequestId); } }); toCancel.forEach(this::cancelAndRemove); break; } } } @Override protected void cleanupEntityOnPartitionRemoval(NotificationRequestId notificationRequestId) { cancelAndRemove(notificationRequestId); } private void cancelAndRemove(NotificationRequestId notificationRequestId) { ScheduledRequestMetadata md = scheduledNotificationRequests.remove(notificationRequestId); if (md != null) { md.getFuture().cancel(false); } } @Override
protected String getServiceName() { return "Notifications scheduler"; } @Override protected String getSchedulerExecutorName() { return "notifications-scheduler"; } @Override @PreDestroy public void stop() { super.stop(); scheduler.shutdownNow(); } @Data private static class ScheduledRequestMetadata { private final TenantId tenantId; private final ScheduledFuture<?> future; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\DefaultNotificationSchedulerService.java
2
请完成以下Java代码
static <C, A> Filter<C, A> allowAll() { return (callbackType, callbackInstance, argument, additionalArguments) -> true; } } /** * {@link Filter} that matches when the callback has a single generic and primary * argument is an instance of it. */ private static final class GenericTypeFilter<C, A> implements Filter<C, A> { @Override public boolean match(Class<C> callbackType, C callbackInstance, A argument, Object[] additionalArguments) { ResolvableType type = ResolvableType.forClass(callbackType, callbackInstance.getClass()); if (type.getGenerics().length == 1 && type.resolveGeneric() != null) { return type.resolveGeneric().isInstance(argument); } return true; } } /** * The result of a callback which may be a value, {@code null} or absent entirely if * the callback wasn't suitable. Similar in design to {@link Optional} but allows for * {@code null} as a valid value. * * @param <R> the result type */ public static final class InvocationResult<R> { private static final InvocationResult<?> NONE = new InvocationResult<>(null); private final R value; private InvocationResult(R value) { this.value = value; } /** * Return true if a result in present. * @return if a result is present */
public boolean hasResult() { return this != NONE; } /** * Return the result of the invocation or {@code null} if the callback wasn't * suitable. * @return the result of the invocation or {@code null} */ public R get() { return this.value; } /** * Return the result of the invocation or the given fallback if the callback * wasn't suitable. * @param fallback the fallback to use when there is no result * @return the result of the invocation or the fallback */ public R get(R fallback) { return (this != NONE) ? this.value : fallback; } /** * Create a new {@link InvocationResult} instance with the specified value. * @param value the value (may be {@code null}) * @param <R> the result type * @return an {@link InvocationResult} */ public static <R> InvocationResult<R> of(R value) { return new InvocationResult<>(value); } /** * Return an {@link InvocationResult} instance representing no result. * @param <R> the result type * @return an {@link InvocationResult} */ @SuppressWarnings("unchecked") public static <R> InvocationResult<R> noResult() { return (InvocationResult<R>) NONE; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\util\LambdaSafe.java
1
请在Spring Boot框架中完成以下Java代码
protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive()); clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); }
@Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2