instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void onComplete(@NonNull final I_PP_Product_BOM productBOMRecord) { final Optional<I_PP_Product_BOM> previousBOMVersion = productBOMDAO.getPreviousVersion(productBOMRecord, DocStatus.Completed); if (!previousBOMVersion.isPresent()) { return; } if (!shouldUpdateExistingPPOrderCandidates(productBOMRecord, previousBOMVersion.get())) { return; } final ProductBOMId previousBOMVersionID = ProductBOMId.ofRepoId(previousBOMVersion.get().getPP_Product_BOM_ID()); trxManager.runAfterCommit(() -> updateBOMOnMatchingOrderCandidates(previousBOMVersionID, productBOMRecord)); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void onReactivate(@NonNull final I_PP_Product_BOM productBOMRecord) { final ProductBOMId productBOMId = ProductBOMId.ofRepoId(productBOMRecord.getPP_Product_BOM_ID()); if (isBOMInUse(productBOMId)) { throw new AdempiereException("Product BOM is already in use (linked to a manufacturing order or candidate). It cannot be reactivated!") .appendParametersToMessage() .setParameter("productBOMId", productBOMId); } } private boolean isBOMInUse(@NonNull final ProductBOMId productBOMId)
{ return !EmptyUtil.isEmpty(ppOrderCandidateDAO.getByProductBOMId(productBOMId)) || !EmptyUtil.isEmpty(ppOrderDAO.getByProductBOMId(productBOMId)); } private void updateBOMOnMatchingOrderCandidates( @NonNull final ProductBOMId previousBOMVersionID, @NonNull final I_PP_Product_BOM productBOMRecord) { ppOrderCandidateDAO.getByProductBOMId(previousBOMVersionID) .stream() .filter(ppOrderCandidate -> PPOrderCandidateService.canAssignBOMVersion(ppOrderCandidate, productBOMRecord)) .peek(ppOrderCandidate -> ppOrderCandidate.setPP_Product_BOM_ID(productBOMRecord.getPP_Product_BOM_ID())) .forEach(ppOrderCandidateDAO::save); } private boolean shouldUpdateExistingPPOrderCandidates(@NonNull final I_PP_Product_BOM currentVersion, @NonNull final I_PP_Product_BOM oldVersion) { final AttributeSetInstanceId orderLineCandidateASIId = AttributeSetInstanceId.ofRepoIdOrNull(currentVersion.getM_AttributeSetInstance_ID()); final AttributeSetInstanceId productBOMLineASIId = AttributeSetInstanceId.ofRepoIdOrNull(oldVersion.getM_AttributeSetInstance_ID()); return asiBL.nullSafeASIEquals(orderLineCandidateASIId, productBOMLineASIId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\interceptor\PP_Product_BOM.java
1
请完成以下Java代码
public AnnotationContainer annotations() { return this.annotations; } /** * Return the modifiers. * @return the modifiers */ public int getModifiers() { return this.modifiers; } /** * Return the name. * @return the name */ public String getName() { return this.name; } /** * Return the return type. * @return the return type */ public String getReturnType() { return this.returnType; } /** * Return the value. * @return the value */ public Object getValue() { return this.value; } /** * Return whether this field is initialized. * @return whether the field is initialized. */ public boolean isInitialized() { return this.initialized; } /** * Builder for creating a {@link JavaFieldDeclaration}. */ public static final class Builder {
private final String name; private String returnType; private int modifiers; private Object value; private boolean initialized; private Builder(String name) { this.name = name; } /** * Sets the modifiers. * @param modifiers the modifiers * @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /** * Sets the value. * @param value the value * @return this for method chaining */ public Builder value(Object value) { this.value = value; this.initialized = true; return this; } /** * Sets the return type. * @param returnType the return type * @return this for method chaining */ public JavaFieldDeclaration returning(String returnType) { this.returnType = returnType; return new JavaFieldDeclaration(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaFieldDeclaration.java
1
请完成以下Java代码
public void setAuthoritiesClaimName(String authoritiesClaimName) { Assert.hasText(authoritiesClaimName, "authoritiesClaimName cannot be empty"); this.authoritiesClaimNames = Collections.singletonList(authoritiesClaimName); } private String getAuthoritiesClaimName(Jwt jwt) { for (String claimName : this.authoritiesClaimNames) { if (jwt.hasClaim(claimName)) { return claimName; } } return null; } private Collection<String> getAuthorities(Jwt jwt) { String claimName = getAuthoritiesClaimName(jwt); if (claimName == null) { this.logger.trace("Returning no authorities since could not find any claims that might contain scopes"); return Collections.emptyList(); } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for scopes in claim %s", claimName)); } Object authorities = jwt.getClaim(claimName); if (authorities instanceof String) { if (StringUtils.hasText((String) authorities)) { return Arrays.asList(((String) authorities).split(this.authoritiesClaimDelimiter));
} return Collections.emptyList(); } if (authorities instanceof Collection) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtGrantedAuthoritiesConverter.java
1
请完成以下Java代码
public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host
Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Registration.java
1
请完成以下Java代码
public ArticleRecord value1(Integer value) { setId(value); return this; } @Override public ArticleRecord value2(String value) { setTitle(value); return this; } @Override public ArticleRecord value3(String value) { setDescription(value); return this; } @Override public ArticleRecord value4(Integer value) { setAuthorId(value); return this; } @Override public ArticleRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2);
value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ArticleRecord */ public ArticleRecord() { super(Article.ARTICLE); } /** * Create a detached, initialised ArticleRecord */ public ArticleRecord(Integer id, String title, String description, Integer authorId) { super(Article.ARTICLE); set(0, id); set(1, title); set(2, description); set(3, authorId); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\ArticleRecord.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<Order> handleOrder(Order order) { log.info("Handle order invoked with: {}", order); return Flux.fromIterable(order.getLineItems()) .flatMap(l -> productRepository.findById(l.getProductId())) .flatMap(p -> { int q = order.getLineItems() .stream() .filter(l -> l.getProductId() .equals(p.getId())) .findAny() .get() .getQuantity(); if (p.getStock() >= q) { p.setStock(p.getStock() - q); return productRepository.save(p); } else { return Mono.error(new RuntimeException("Product is out of stock: " + p.getId())); } }) .then(Mono.just(order.setOrderStatus(OrderStatus.SUCCESS))); } @Transactional public Mono<Order> revertOrder(Order order) { log.info("Revert order invoked with: {}", order);
return Flux.fromIterable(order.getLineItems()) .flatMap(l -> productRepository.findById(l.getProductId())) .flatMap(p -> { int q = order.getLineItems() .stream() .filter(l -> l.getProductId() .equals(p.getId())) .collect(Collectors.toList()) .get(0) .getQuantity(); p.setStock(p.getStock() + q); return productRepository.save(p); }) .then(Mono.just(order.setOrderStatus(OrderStatus.SUCCESS))); } public Flux<Product> getProducts() { return productRepository.findAll(); } }
repos\tutorials-master\reactive-systems\inventory-service\src\main\java\com\baeldung\reactive\service\ProductService.java
2
请完成以下Java代码
public List<I_M_HU> getTopLevelHUs(final org.eevolution.model.I_PP_Cost_Collector cc) { final IHUAssignmentDAO huAssignmentDAO = Services.get(IHUAssignmentDAO.class); return huAssignmentDAO.retrieveTopLevelHUsForModel(cc); } @Override public void restoreTopLevelHUs(final I_PP_Cost_Collector costCollector) { Check.assumeNotNull(costCollector, "costCollector not null"); // // Retrieve the HUs which were assigned to original cost collector final List<I_M_HU> hus = getTopLevelHUs(costCollector); if (hus.isEmpty()) { return; } // // Get the snapshot ID. // Make sure it exists, else we would not be able to restore the HUs. final String snapshotId = costCollector.getSnapshot_UUID();
if (Check.isEmpty(snapshotId, true)) { throw new HUException("@NotFound@ @Snapshot_UUID@ (" + costCollector + ")"); } final IContextAware context = InterfaceWrapperHelper.getContextAware(costCollector); Services.get(IHUSnapshotDAO.class).restoreHUs() .setContext(context) .setSnapshotId(snapshotId) .setDateTrx(costCollector.getMovementDate()) .setReferencedModel(costCollector) .addModels(hus) .restoreFromSnapshot(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\HUPPCostCollectorBL.java
1
请完成以下Java代码
private FactLine applyTo(@NonNull final FactLine factLine) { final FactLineMatchKey matchKey = FactLineMatchKey.ofFactLine(factLine); // // Remove line final FactAcctChanges remove = linesToRemoveByKey.remove(matchKey); if (remove != null) { return null; // consider line removed } // // Change line else { final FactAcctChanges change = linesToChangeByKey.remove(matchKey); if (change != null) { factLine.updateFrom(change); } return factLine; } } private void addLinesTo(@NonNull final Fact fact) { final AcctSchemaId acctSchemaId = fact.getAcctSchemaId(); final List<FactAcctChanges> additions = linesToAddGroupedByAcctSchemaId.removeAll(acctSchemaId); additions.forEach(addition -> addLine(fact, addition)); } public void addLine(@NonNull final Fact fact, @NonNull final FactAcctChanges changesToAdd) { if (!changesToAdd.getType().isAdd()) {
throw new AdempiereException("Expected type `Add` but it was " + changesToAdd); } final FactLine factLine = fact.createLine() .alsoAddZeroLine() .setAccount(changesToAdd.getAccountIdNotNull()) .setAmtSource(changesToAdd.getAmtSourceDr(), changesToAdd.getAmtSourceCr()) .setAmtAcct(changesToAdd.getAmtAcctDr(), changesToAdd.getAmtAcctCr()) .setC_Tax_ID(changesToAdd.getTaxId()) .description(changesToAdd.getDescription()) .productId(changesToAdd.getProductId()) .userElementString1(changesToAdd.getUserElementString1()) .salesOrderId(changesToAdd.getSalesOrderId()) .activityId(changesToAdd.getActivityId()) .buildAndAdd(); if (factLine != null) { factLine.updateFrom(changesToAdd); // just to have appliedUserChanges set } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChangesApplier.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Private Note. @param PrivateNote Private Note - not visible to the other parties */ public void setPrivateNote (String PrivateNote) { set_Value (COLUMNNAME_PrivateNote, PrivateNote); } /** Get Private Note. @return Private Note - not visible to the other parties */ public String getPrivateNote () {
return (String)get_Value(COLUMNNAME_PrivateNote); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Bid.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Branch getMainBranch() { return mainBranch; } public void setMainBranch(Branch mainBranch) { this.mainBranch = mainBranch; } public Branch getSubBranch() {
return subBranch; } public void setSubBranch(Branch subBranch) { this.subBranch = subBranch; } public Branch getAdditionalBranch() { return additionalBranch; } public void setAdditionalBranch(Branch additionalBranch) { this.additionalBranch = additionalBranch; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\lazycollection\model\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, JksSslBundleProperties> getJks() { return this.jks; } public Watch getWatch() { return this.watch; } public static class Watch { /** * File watching. */ private final File file = new File(); public File getFile() { return this.file; } public static class File { /** * Quiet period, after which changes are detected.
*/ private Duration quietPeriod = Duration.ofSeconds(10); public Duration getQuietPeriod() { return this.quietPeriod; } public void setQuietPeriod(Duration quietPeriod) { this.quietPeriod = quietPeriod; } } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslProperties.java
2
请完成以下Java代码
final class DockerJson { private static final JsonMapper jsonMapper = JsonMapper.builder() .defaultLocale(Locale.ENGLISH) .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) .build(); private DockerJson() { } /** * Deserialize JSON to a list. Handles JSON arrays and multiple JSON objects in * separate lines. * @param <T> the item type * @param json the source JSON * @param itemType the item type * @return a list of items */ static <T> List<T> deserializeToList(String json, Class<T> itemType) { if (json.startsWith("[")) {
JavaType javaType = jsonMapper.getTypeFactory().constructCollectionType(List.class, itemType); return deserialize(json, javaType); } return json.trim().lines().map((line) -> deserialize(line, itemType)).toList(); } /** * Deserialize JSON to an object instance. * @param <T> the result type * @param json the source JSON * @param type the result type * @return the deserialized result */ static <T> T deserialize(String json, Class<T> type) { return deserialize(json, jsonMapper.getTypeFactory().constructType(type)); } private static <T> T deserialize(String json, JavaType type) { return jsonMapper.readValue(json.trim(), type); } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DockerJson.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeServicesWithRepository implements EmployeeService { @Autowired EmployeeRepository employeeRepository; @Override public void save(Employee employee) { employeeRepository.save(employee); } @Override public Iterable<Employee> fetchAll() { return employeeRepository.findAll(); } @Override public Optional<Employee> get(Integer id) { return employeeRepository.findById(id); } @Override
public void update(Employee employee) { employeeRepository.save(employee); } @Override public void delete(Integer id) { employeeRepository.deleteById(id); } public Iterable<Employee> getSortedListOfEmployeesBySalary() { throw new RuntimeException("Method not supported by CRUDRepository"); } }
repos\tutorials-master\persistence-modules\spring-data-keyvalue\src\main\java\com\baeldung\spring\data\keyvalue\services\impl\EmployeeServicesWithRepository.java
2
请完成以下Java代码
public void setPayPal_PayerApprovalRequest_MailTemplate_ID (final int PayPal_PayerApprovalRequest_MailTemplate_ID) { if (PayPal_PayerApprovalRequest_MailTemplate_ID < 1) set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, null); else set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, PayPal_PayerApprovalRequest_MailTemplate_ID); } @Override public int getPayPal_PayerApprovalRequest_MailTemplate_ID() { return get_ValueAsInt(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID); } @Override public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl) { set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl); } @Override public java.lang.String getPayPal_PaymentApprovedCallbackUrl() { return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl); } @Override public void setPayPal_Sandbox (final boolean PayPal_Sandbox) { set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox); }
@Override public boolean isPayPal_Sandbox() { return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox); } @Override public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl) { set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl); } @Override public java.lang.String getPayPal_WebUrl() { return get_ValueAsString(COLUMNNAME_PayPal_WebUrl); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java
1
请完成以下Java代码
public class GolfCourse { public static final int STANDARD_PAR_FOR_COURSE = 72; public static final Set<Integer> VALID_PARS_FOR_HOLE = Collections.unmodifiableSet(CollectionUtils.asSet(3, 4, 5)); @NonNull private final String name; private final List<Integer> parForHole = new ArrayList<>(18); public int getPar(int hole) { assertValidHoleNumber(hole); return this.parForHole.get(indexForHole(hole)); } public int getParForCourse() { return this.parForHole.stream() .reduce(Integer::sum) .orElse(STANDARD_PAR_FOR_COURSE); } public GolfCourse withHole(int holeNumber, int par) { assertValidHoleNumber(holeNumber); assertValidParForHole(par, holeNumber);
this.parForHole.add(indexForHole(holeNumber), par); return this; } private void assertValidHoleNumber(int hole) { Assert.isTrue(isValidHoleNumber(hole), () -> String.format("Hole number [%d] must be 1 through 18", hole)); } private void assertValidParForHole(int par, int hole) { Assert.isTrue(isValidPar(par), () -> String.format("Par [%1$d] for hole [%2$d] must be in [%3$s]", par, hole, VALID_PARS_FOR_HOLE)); } private int indexForHole(int hole) { return hole - 1; } public boolean isValidHoleNumber(int hole) { return hole >= 1 && hole <= 18; } public boolean isValidPar(int par) { return VALID_PARS_FOR_HOLE.contains(par); } }
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfCourse.java
1
请在Spring Boot框架中完成以下Java代码
private Quantity getTotalQtyReceived() { clearLoadedData(); final I_PP_Order_BOMLine ppOrderBomLine = getCOProductLine(); if (ppOrderBomLine != null) { return loadingAndSavingSupportServices.getQuantities(ppOrderBomLine).getQtyIssuedOrReceived().negate(); } return loadingAndSavingSupportServices.getQuantities(getPPOrder()).getQtyReceived(); } private boolean isCoProduct() { return getCOProductLine() != null; } private void setQRCodeAttribute(@NonNull final I_M_HU hu) { if (barcode == null) {return;} final IAttributeStorage huAttributes = handlingUnitsBL.getAttributeStorage(hu); if (!huAttributes.hasAttribute(HUAttributeConstants.ATTR_QRCode)) {return;} huAttributes.setSaveOnChange(true); huAttributes.setValue(HUAttributeConstants.ATTR_QRCode, barcode.getAsString()); }
private void save() { newSaver().saveActivityStatuses(job); } @NonNull private ManufacturingJobLoaderAndSaver newSaver() {return new ManufacturingJobLoaderAndSaver(loadingAndSavingSupportServices);} private void autoIssueForWhatWasReceived() { job = jobService.autoIssueWhatWasReceived(job, RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\receive\ReceiveGoodsCommand.java
2
请完成以下Java代码
private static int nthPadovanTermRecursiveMethodWithMemoization(int n, int[] memo) { if (memo[n] != 0) { return memo[n]; } memo[n] = nthPadovanTermRecursiveMethodWithMemoization(n - 2, memo) + nthPadovanTermRecursiveMethodWithMemoization(n - 3, memo); return memo[n]; } public static int nthPadovanTermIterativeMethodWithArray(int n) { int[] memo = new int[n + 1]; if (n == 0 || n == 1 || n == 2) { return 1; } memo[0] = 1; memo[1] = 1; memo[2] = 1; for (int i = 3; i <= n; i++) { memo[i] = memo[i - 2] + memo[i - 3]; } return memo[n]; } public static int nthPadovanTermIterativeMethodWithVariables(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } int p0 = 1, p1 = 1, p2 = 1;
int tempNthTerm; for (int i = 3; i <= n; i++) { tempNthTerm = p0 + p1; p0 = p1; p1 = p2; p2 = tempNthTerm; } return p2; } public static int nthPadovanTermUsingFormula(int n) { if (n == 0 || n == 1 || n == 2) { return 1; } // Padovan spiral constant (plastic number) - the real root of x^3 - x - 1 = 0 final double PADOVAN_CONSTANT = 1.32471795724474602596; // Normalization factor to approximate Padovan sequence values final double NORMALIZATION_FACTOR = 1.045356793252532962; double p = Math.pow(PADOVAN_CONSTANT, n - 1); return (int) Math.round(p / NORMALIZATION_FACTOR); } }
repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\padovan\PadovanSeriesUtils.java
1
请完成以下Java代码
public col addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public col addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public col addElement(Element element) { addElementToRegistry(element); return(this);
} /** Adds an Element to the element. @param element Adds an Element to the element. */ public col addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public col removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\col.java
1
请完成以下Java代码
public void setMSV3_BaseUrl (java.lang.String MSV3_BaseUrl) { set_Value (COLUMNNAME_MSV3_BaseUrl, MSV3_BaseUrl); } /** Get MSV3 Base URL. @return Beispiel: https://msv3-server:443/msv3/v2.0 */ @Override public java.lang.String getMSV3_BaseUrl () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_BaseUrl); } /** Set MSV3_Vendor_Config. @param MSV3_Vendor_Config_ID MSV3_Vendor_Config */ @Override public void setMSV3_Vendor_Config_ID (int MSV3_Vendor_Config_ID) { if (MSV3_Vendor_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, Integer.valueOf(MSV3_Vendor_Config_ID)); } /** Get MSV3_Vendor_Config. @return MSV3_Vendor_Config */ @Override public int getMSV3_Vendor_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Vendor_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Nutzerkennung. @param UserID Nutzerkennung */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); }
/** * Version AD_Reference_ID=540904 * Reference name: MSV3_Version */ public static final int VERSION_AD_Reference_ID=540904; /** 1 = 1 */ public static final String VERSION_1 = "1"; /** 2 = 2 */ public static final String VERSION_2 = "2"; /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Vendor_Config.java
1
请完成以下Java代码
public boolean isRunning() { this.lock.lock(); try { return this.running; } finally { this.lock.unlock(); } } @Override public int getPhase() { return this.phase; } public void setPhase(int phase) { this.phase = phase; } @Override public boolean isAutoStartup() { return this.autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void onMessage(Message message) { if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties())); } else { if (logger.isWarnEnabled()) { logger.warn("No event publisher available for " + message + "; if the BrokerEventListener " + "is not defined as a bean, you must provide an ApplicationEventPublisher"); } } }
@Override public void onCreate(@Nullable Connection connection) { this.bindingsFailedException = null; TopicExchange exchange = new TopicExchange("amq.rabbitmq.event"); try { this.admin.declareQueue(this.eventQueue); Arrays.stream(this.eventKeys).forEach(k -> { Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k); this.admin.declareBinding(binding); }); } catch (Exception e) { logger.error("failed to declare event queue/bindings - is the plugin enabled?", e); this.bindingsFailedException = e; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaConfig { @Value(value = "${spring.kafka.bootstrap-servers}") private String bootstrapAddress; @Value(value = "${spring.kafka.streams.state.dir}") private String stateStoreLocation; @Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME) KafkaStreamsConfiguration kStreamsConfig() { Map<String, Object> props = new HashMap<>(); props.put(APPLICATION_ID_CONFIG, "streams-app"); props.put(BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress); props.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); props.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
// configure the state location to allow tests to use clean state for every run props.put(STATE_DIR_CONFIG, stateStoreLocation); return new KafkaStreamsConfiguration(props); } @Bean NewTopic inputTopic() { return TopicBuilder.name("input-topic") .partitions(1) .replicas(1) .build(); } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\streams\KafkaConfig.java
2
请完成以下Java代码
protected boolean afterSave(final boolean newRecord, final boolean success) { updateHeader(); return success; } @Override protected boolean afterDelete(final boolean success) { updateHeader(); return success; } private void updateHeader() { final String sql = DB.convertSqlToNative("UPDATE C_Project p " + "SET (PlannedAmt,PlannedQty,PlannedMarginAmt," + " CommittedAmt,CommittedQty," + " InvoicedAmt, InvoicedQty) = "
+ "(SELECT COALESCE(SUM(pl.PlannedAmt),0),COALESCE(SUM(pl.PlannedQty),0),COALESCE(SUM(pl.PlannedMarginAmt),0)," + " COALESCE(SUM(pl.CommittedAmt),0),COALESCE(SUM(pl.CommittedQty),0)," + " COALESCE(SUM(pl.InvoicedAmt),0), COALESCE(SUM(pl.InvoicedQty),0) " + "FROM C_ProjectLine pl " + "WHERE pl.C_Project_ID=p.C_Project_ID AND pl.IsActive='Y') " + "WHERE C_Project_ID=" + getC_Project_ID()); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); if (no != 1) { log.warn("updateHeader - #{}", no); } CacheMgt.get().reset(I_C_Project.Table_Name, getC_Project_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProjectLine.java
1
请完成以下Java代码
public void setPid(Long pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Integer getStatus() { return status;
} public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", pid=").append(pid); sb.append(", name=").append(name); sb.append(", value=").append(value); sb.append(", icon=").append(icon); sb.append(", type=").append(type); sb.append(", uri=").append(uri); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsPermission.java
1
请完成以下Java代码
public String getLineReference() { return entry.getNtryRef(); } @Override @NonNull protected String getUnstructuredRemittanceInfo(@NonNull final String delimiter) { return String.join(delimiter, getUnstructuredRemittanceInfoList()); } @Override @NonNull protected List<String> getUnstructuredRemittanceInfoList() { return getEntryTransaction() .stream() .findFirst() .map(EntryTransaction2::getRmtInf) .map(RemittanceInformation5::getUstrd) .orElse(ImmutableList.of()) .stream() .map(str -> Arrays.asList(str.split(" "))) .flatMap(List::stream) .filter(Check::isNotBlank) .collect(Collectors.toList()); } @Override @NonNull protected String getLineDescription(@NonNull final String delimiter) { return getLineDescriptionList().stream() .filter(Check::isNotBlank) .collect(Collectors.joining(delimiter)); } @Override @NonNull protected List<String> getLineDescriptionList() { final List<String> lineDesc = new ArrayList<>(); final String addtlNtryInfStr = entry.getAddtlNtryInf(); if (addtlNtryInfStr != null) { lineDesc.addAll( Arrays.stream(addtlNtryInfStr.split(" ")) .filter(Check::isNotBlank) .collect(Collectors.toList())); } final List<String> trxDetails = getEntryTransaction() .stream() .map(EntryTransaction2::getAddtlTxInf) .filter(Objects::nonNull) .map(str -> Arrays.asList(str.split(" "))) .flatMap(List::stream) .filter(Check::isNotBlank) .collect(Collectors.toList()); lineDesc.addAll(trxDetails);
return lineDesc; } @Override @Nullable protected String getCcy() { return entry.getAmt().getCcy(); } @Override @Nullable protected BigDecimal getAmtValue() { return entry.getAmt().getValue(); } public boolean isBatchTransaction() {return getEntryTransaction().size() > 1;} @Override public List<ITransactionDtlsWrapper> getTransactionDtlsWrapper() { return getEntryTransaction() .stream() .map(tr -> TransactionDtls2Wrapper.builder().entryDtls(tr).build()) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\BatchReportEntry2Wrapper.java
1
请完成以下Java代码
public boolean isMatching(@Nullable final HashableString other) { if (this == other) { return true; } if (other == null) { return false; } if (isPlain()) { if (other.isPlain()) { return valueEquals(other.value); } else { return hashWithSalt(other.salt).valueEquals(other.value); }
} else { if (other.isPlain()) { return other.hashWithSalt(salt).valueEquals(value); } else { return valueEquals(other.value); } } } private boolean valueEquals(final String otherValue) { return Objects.equals(this.value, otherValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\hash\HashableString.java
1
请完成以下Java代码
public static PPOrderRef ofPPOrderBOMLineId(final int ppOrderId, final int ppOrderBOMLineId) { return ofPPOrderBOMLineId(PPOrderId.ofRepoId(ppOrderId), PPOrderBOMLineId.ofRepoId(ppOrderBOMLineId)); } public static PPOrderRef ofPPOrderBOMLineId(@NonNull final PPOrderId ppOrderId, @NonNull final PPOrderBOMLineId ppOrderBOMLineId) { return builder().ppOrderId(ppOrderId).ppOrderBOMLineId(ppOrderBOMLineId).build(); } public static PPOrderRef ofPPOrderBOMLineId(@NonNull final PPOrderAndBOMLineId ppOrderAndBOMLineId) { return ofPPOrderBOMLineId(ppOrderAndBOMLineId.getPpOrderId(), ppOrderAndBOMLineId.getLineId()); } @Nullable public static PPOrderRef ofPPOrderAndLineIdOrNull(final int ppOrderRepoId, final int ppOrderBOMLineRepoId) { final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ppOrderRepoId); if (ppOrderId == null) { return null; } return builder().ppOrderId(ppOrderId).ppOrderBOMLineId(PPOrderBOMLineId.ofRepoIdOrNull(ppOrderBOMLineRepoId)).build(); } public boolean isFinishedGoods() { return !isBOMLine(); } public boolean isBOMLine() { return ppOrderBOMLineId != null; } public PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { final PPOrderId ppOrderIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getPpOrderId() : null; final PPOrderBOMLineId lineIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getLineId() : null; return PPOrderId.equals(this.ppOrderId, ppOrderIdNew) && PPOrderBOMLineId.equals(this.ppOrderBOMLineId, lineIdNew) ? this : toBuilder().ppOrderId(ppOrderIdNew).ppOrderBOMLineId(lineIdNew).build(); }
public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId) { if (PPOrderId.equals(this.ppOrderId, ppOrderId)) { return this; } return toBuilder().ppOrderId(ppOrderId).build(); } @Nullable public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderId(newPPOrderId); } else if (newPPOrderId != null) { return ofPPOrderId(newPPOrderId); } else { return null; } } @Nullable public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId); } else if (newPPOrderAndBOMLineId != null) { return ofPPOrderBOMLineId(newPPOrderAndBOMLineId); } else { return null; } } @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java
1
请在Spring Boot框架中完成以下Java代码
public void handleEvent(@NonNull final ShipmentScheduleCreatedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.forDocumentLine(event.getDocumentLineDescriptor()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final DemandDetail demandDetail = DemandDetail.forDocumentLine( event.getShipmentScheduleId(), event.getDocumentLineDescriptor(), event.getMaterialDescriptor().getQuantity()); final CandidateBuilder candidateBuilder = Candidate .builderForEventDescriptor(event.getEventDescriptor()) .materialDescriptor(event.getMaterialDescriptor())
.minMaxDescriptor(event.getMinMaxDescriptor()) .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .businessCaseDetail(demandDetail); final Candidate existingCandidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); if (existingCandidate != null) { candidateBuilder.id(existingCandidate.getId()); } final Candidate candidate = candidateBuilder.build(); candidateChangeHandler.onCandidateNewOrChange(candidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleCreatedHandler.java
2
请在Spring Boot框架中完成以下Java代码
public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getMchId() { return mchId; } public void setMchId(String mchId) { this.mchId = mchId; } public String getDeviceInfo() { return deviceInfo; } public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getNonceStr() { return nonceStr; } public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getOutTradeNo() { return outTradeNo; } public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getFeeType() { return feeType; } public void setFeeType(String feeType) { this.feeType = feeType; } public Integer getTotalFee() { return totalFee; } public void setTotalFee(Integer totalFee) {
this.totalFee = totalFee; } public String getSpbillCreateIp() { return spbillCreateIp; } public void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public WeiXinTradeTypeEnum getTradeType() { return tradeType; } public void setTradeType(WeiXinTradeTypeEnum tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } public void setLimitPay(String limitPay) { this.limitPay = limitPay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java
2
请完成以下Java代码
private static ImmutableMap<WindowId, ImmutableMap<ViewProfileId, SqlViewCustomizer>> makeViewCustomizersMap(final ImmutableList<SqlViewCustomizer> viewCustomizers) { final Map<WindowId, ImmutableMap<ViewProfileId, SqlViewCustomizer>> map = viewCustomizers .stream() .sorted(ORDERED_COMPARATOR) .collect(Collectors.groupingBy( SqlViewCustomizer::getWindowId, ImmutableMap.toImmutableMap(viewCustomizer -> viewCustomizer.getProfile().getProfileId(), viewCustomizer -> viewCustomizer))); return ImmutableMap.copyOf(map); } private static int getOrder(@NonNull final SqlViewCustomizer viewCustomizer) { if (viewCustomizer instanceof Ordered) { return ((Ordered)viewCustomizer).getOrder(); } else { return OrderUtils.getOrder(viewCustomizer.getClass(), Ordered.LOWEST_PRECEDENCE); } } public SqlViewCustomizer getOrNull( @NonNull final WindowId windowId, @Nullable final ViewProfileId profileId) { if (ViewProfileId.isNull(profileId)) { return null; } final ImmutableMap<ViewProfileId, SqlViewCustomizer> viewCustomizersByProfileId = map.get(windowId);
if (viewCustomizersByProfileId == null) { return null; } return viewCustomizersByProfileId.get(profileId); } public void forEachWindowIdAndProfileId(@NonNull final BiConsumer<WindowId, ViewProfileId> consumer) { viewCustomizers.forEach(viewCustomizer -> consumer.accept(viewCustomizer.getWindowId(), viewCustomizer.getProfile().getProfileId())); } public ImmutableListMultimap<WindowId, ViewProfile> getViewProfilesIndexedByWindowId() { return viewCustomizers .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(viewCustomizer -> viewCustomizer.getWindowId(), viewCustomizer -> viewCustomizer.getProfile())); } public List<ViewProfile> getViewProfilesByWindowId(WindowId windowId) { return viewProfilesByWindowId.get(windowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewCustomizerMap.java
1
请完成以下Java代码
public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_Customer_Retention_ID. @param C_Customer_Retention_ID C_Customer_Retention_ID */ @Override public void setC_Customer_Retention_ID (int C_Customer_Retention_ID) { if (C_Customer_Retention_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, Integer.valueOf(C_Customer_Retention_ID)); } /** Get C_Customer_Retention_ID. @return C_Customer_Retention_ID */ @Override public int getC_Customer_Retention_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Customer_Retention_ID); if (ii == null) return 0; return ii.intValue(); } /** * CustomerRetention AD_Reference_ID=540937 * Reference name: C_BPartner_TimeSpan_List */
public static final int CUSTOMERRETENTION_AD_Reference_ID=540937; /** Neukunde = N */ public static final String CUSTOMERRETENTION_Neukunde = "N"; /** Stammkunde = S */ public static final String CUSTOMERRETENTION_Stammkunde = "S"; /** Set Customer Retention. @param CustomerRetention Customer Retention */ @Override public void setCustomerRetention (java.lang.String CustomerRetention) { set_Value (COLUMNNAME_CustomerRetention, CustomerRetention); } /** Get Customer Retention. @return Customer Retention */ @Override public java.lang.String getCustomerRetention () { return (java.lang.String)get_Value(COLUMNNAME_CustomerRetention); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customer_Retention.java
1
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNErrorImpl that = (BPMNErrorImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(getActivityName(), that.getActivityName()) && Objects.equals(getActivityType(), that.getActivityType()) && Objects.equals(getErrorCode(), that.getErrorCode()) && Objects.equals(getErrorId(), that.getErrorId()) ); } @Override public String toString() { return ( "BPMNActivityImpl{" + "activityName='" + getActivityName() + '\'' +
", activityType='" + getActivityType() + '\'' + ", elementId='" + getElementId() + '\'' + ", errorId='" + getErrorId() + '\'' + ", errorCode='" + getErrorCode() + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNErrorImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class .getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME); String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie(CSRF_COOKIE_NAME, token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; } /**
* Angular sends the CSRF token in a custom header named "X-XSRF-TOKEN" * rather than the default "X-CSRF-TOKEN" that Spring security expects. * Hence we are now telling Spring security to expect the token in the * "X-XSRF-TOKEN" header.<br><br> * * This customization is added to the <code>csrf()</code> filter. * * @return */ private CsrfTokenRepository getCSRFTokenRepository() { HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName(CSRF_ANGULAR_HEADER_NAME); return repository; } }
repos\spring-boot-microservices-master\api-gateway\src\main\java\com\rohitghatol\microservice\gateway\config\OAuthConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void setWithoutSource(Boolean withoutSource) { this.withoutSource = withoutSource; } @CamundaQueryParam(value = "before", converter = DateConverter.class) public void setDeploymentBefore(Date deploymentBefore) { this.before = deploymentBefore; } @CamundaQueryParam(value = "after", converter = DateConverter.class) public void setDeploymentAfter(Date deploymentAfter) { this.after = deploymentAfter; } @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) public void setTenantIdIn(List<String> tenantIds) { this.tenantIds = tenantIds; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value = "includeDeploymentsWithoutTenantId", converter = BooleanConverter.class) public void setIncludeDeploymentsWithoutTenantId(Boolean includeDeploymentsWithoutTenantId) { this.includeDeploymentsWithoutTenantId = includeDeploymentsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected DeploymentQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createDeploymentQuery(); } @Override protected void applyFilters(DeploymentQuery query) { if (withoutSource != null && withoutSource && source != null) { throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination."); } if (id != null) { query.deploymentId(id); } if (name != null) { query.deploymentName(name); } if (nameLike != null) { query.deploymentNameLike(nameLike); } if (TRUE.equals(withoutSource)) { query.deploymentSource(null); } if (source != null) {
query.deploymentSource(source); } if (before != null) { query.deploymentBefore(before); } if (after != null) { query.deploymentAfter(after); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDeploymentsWithoutTenantId)) { query.includeDeploymentsWithoutTenantId(); } } @Override protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByDeploymentName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) { query.orderByDeploymentTime(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentQueryDto.java
2
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } @Override public Map<String, Object> getTransientVariables() { return transientVariables; } @Override public String getTenantId() { return tenantId; } @Override public String getOwner() { return ownerId; } @Override public String getAssignee() { return assigneeId; } @Override public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } @Override public String getOutcome() { return outcome; } @Override public Map<String, Object> getStartFormVariables() { return startFormVariables; }
@Override public String getCallbackId() { return this.callbackId; } @Override public String getCallbackType() { return this.callbackType; } @Override public String getReferenceId() { return referenceId; } @Override public String getReferenceType() { return referenceType; } @Override public String getParentId() { return this.parentId; } @Override public boolean isFallbackToDefaultTenant() { return this.fallbackToDefaultTenant; } @Override public boolean isStartWithForm() { return this.startWithForm; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java
1
请完成以下Java代码
private void sendEventObj(final Topic topic, final Object eventObj) { final Event event = toEvent(eventObj); Services.get(ITrxManager.class) .getCurrentTrxListenerManagerOrAutoCommit() .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> sendEventNow(topic, event)); } private void sendEventNow(final Topic topic, final Event event) { final IEventBus eventBus = Services.get(IEventBusFactory.class).getEventBus(topic); eventBus.enqueueEvent(event); } private static Event toEvent(final Object event) { final SimpleObjectSerializer objectSerializer = SimpleObjectSerializer.get(); return Event.builder() .putProperty(EVENT_PROPERTY_Content, objectSerializer.serialize(event)) .shallBeLogged() .build(); }
public static InOutChangedEvent extractInOutChangedEvent(@NonNull final Event event) { return extractEvent(event, InOutChangedEvent.class); } public static InvoiceChangedEvent extractInvoiceChangedEvent(@NonNull final Event event) { return extractEvent(event, InvoiceChangedEvent.class); } public static <T> T extractEvent(@NonNull final Event event, @NonNull final Class<T> eventType) { final String json = event.getPropertyAsString(EVENT_PROPERTY_Content); final SimpleObjectSerializer objectSerializer = SimpleObjectSerializer.get(); return objectSerializer.deserialize(json, eventType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStatsEventSender.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleQuery { private static final ShipmentScheduleQuery ANY = builder().build(); @Builder.Default @NonNull QueryLimit limit = QueryLimit.NO_LIMIT; @Nullable IQueryFilter<I_M_ShipmentSchedule> queryFilter; @NonNull @Singular ImmutableSet<ShipmentScheduleId> shipmentScheduleIds; @Nullable Instant canBeExportedFrom; @Nullable APIExportStatus exportStatus; @Nullable OrgId orgId; @Nullable AttributesKey attributesKey; @Nullable ProductId productId; @NonNull @Singular ImmutableSet<WarehouseId> warehouseIds; @Nullable ShipperId shipperId;
@Builder.Default boolean includeWithQtyToDeliverZero = true; @Builder.Default boolean includeInvalid = true; @Builder.Default boolean includeProcessed = true; boolean fromCompleteOrderOrNullOrder; boolean orderByOrderId; boolean onlyNonZeroReservedQty; @Nullable LocalDate preparationDate; /** * Only export a shipment schedule if its order does not have any schedule which is not yet ready to be exported. */ boolean onlyIfAllFromOrderExportable; public boolean isAny() {return this.equals(ANY);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ShipmentScheduleQuery.java
2
请在Spring Boot框架中完成以下Java代码
public void setResetExpiredJobEnabled(boolean isResetExpiredJobEnabled) { configuration.setResetExpiredJobEnabled(isResetExpiredJobEnabled); } public Thread getTimerJobAcquisitionThread() { return timerJobAcquisitionThread; } public void setTimerJobAcquisitionThread(Thread timerJobAcquisitionThread) { this.timerJobAcquisitionThread = timerJobAcquisitionThread; } public Thread getAsyncJobAcquisitionThread() { return asyncJobAcquisitionThread; } public void setAsyncJobAcquisitionThread(Thread asyncJobAcquisitionThread) { this.asyncJobAcquisitionThread = asyncJobAcquisitionThread; } public Thread getResetExpiredJobThread() { return resetExpiredJobThread; } public void setResetExpiredJobThread(Thread resetExpiredJobThread) { this.resetExpiredJobThread = resetExpiredJobThread; } public boolean isUnlockOwnedJobs() { return configuration.isUnlockOwnedJobs(); }
public void setUnlockOwnedJobs(boolean unlockOwnedJobs) { configuration.setUnlockOwnedJobs(unlockOwnedJobs); } @Override public AsyncTaskExecutor getTaskExecutor() { return taskExecutor; } @Override public void setTaskExecutor(AsyncTaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\DefaultAsyncJobExecutor.java
2
请完成以下Java代码
public Account verify(String id, Credential credential) { Account account = getAccount(id); if (account != null && verifyCredential(account, credential)) { return account; } return null; } private boolean verifyCredential(Account account, Credential credential) { if (credential instanceof PasswordCredential) { char[] password = ((PasswordCredential) credential).getPassword(); char[] expectedPassword = users.get(account.getPrincipal().getName()); return Arrays.equals(password, expectedPassword); } return false; } private Account getAccount(final String id) { if (users.containsKey(id)) { return new Account() { private static final long serialVersionUID = 1L; private final Principal principal = () -> id;
@Override public Principal getPrincipal() { return principal; } @Override public Set<String> getRoles() { return Collections.emptySet(); } }; } return null; } }
repos\tutorials-master\server-modules\undertow\src\main\java\com\baeldung\undertow\secure\CustomIdentityManager.java
1
请完成以下Java代码
abstract class AbstractPermissions<PermissionType extends Permission> implements Permissions<PermissionType> { /** {@link Permission}s indexed by {@link Permission#getResource()} */ private final ImmutableMap<Resource, PermissionType> permissions; public AbstractPermissions(final PermissionsBuilder<PermissionType, ? extends Permissions<PermissionType>> builder) { this.permissions = builder.getPermissions(); } @Override public String toString() { // NOTE: we are making it translateable friendly because it's displayed in Prefereces->Info->Rollen final String permissionsName = getClass().getSimpleName(); final Collection<PermissionType> permissionsList = permissions.values(); final StringBuilder sb = new StringBuilder(); sb.append(permissionsName).append(": "); if (permissionsList.isEmpty()) { sb.append("@NoRestrictions@"); } else { sb.append(Env.NL); } Joiner.on(Env.NL) .skipNulls() .appendTo(sb, permissionsList); return sb.toString(); } @Override public final int size() { return permissions.size(); } @Override public final Collection<PermissionType> getPermissionsList() { return permissions.values(); } protected final ImmutableMap<Resource, PermissionType> getPermissionsMap() { return permissions; } /** * Gets the "NO permission". * * It is an instance of PermissionType with all accesses revoked and with a generic {@link Resource}. * * <br/> * <b>NOTE to implementor: it is highly recommended that extended classes to not return <code>null</code> here.</b> * * @return no permission instance */
protected PermissionType noPermission() { return null; } @Override public final Optional<PermissionType> getPermissionIfExists(final Resource resource) { return Optional.fromNullable(permissions.get(resource)); } @Override public final PermissionType getPermissionOrDefault(final Resource resource) { // // Get the permission for given resource final Optional<PermissionType> permission = getPermissionIfExists(resource); if (permission.isPresent()) { return permission.get(); } // // Fallback: get the permission defined for the resource of "no permission", if any final PermissionType nonePermission = noPermission(); if (nonePermission == null) { return null; } final Resource defaultResource = nonePermission.getResource(); return getPermissionIfExists(defaultResource) // Fallback: return the "no permission" .or(nonePermission); } @Override public final boolean hasPermission(final Permission permission) { return permissions.values().contains(permission); } @Override public final boolean hasAccess(final Resource resource, final Access access) { return getPermissionOrDefault(resource).hasAccess(access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\AbstractPermissions.java
1
请完成以下Java代码
public class ExecutionVariableSnapshotObserver implements ExecutionObserver { /** * The variables which are observed during the execution. */ protected VariableMap variableSnapshot; protected ExecutionEntity execution; protected boolean localVariables = true; protected boolean deserializeValues = false; public ExecutionVariableSnapshotObserver(ExecutionEntity executionEntity) { this(executionEntity, true, false); } public ExecutionVariableSnapshotObserver(ExecutionEntity executionEntity, boolean localVariables, boolean deserializeValues) { this.execution = executionEntity; this.execution.addExecutionObserver(this); this.localVariables = localVariables; this.deserializeValues = deserializeValues; } @Override
public void onClear(ExecutionEntity execution) { if (variableSnapshot == null) { variableSnapshot = getVariables(this.localVariables); } } public VariableMap getVariables() { if (variableSnapshot == null) { return getVariables(this.localVariables); } else { return variableSnapshot; } } private VariableMap getVariables(final boolean localVariables) { return this.localVariables ? execution.getVariablesLocalTyped(deserializeValues) : execution.getVariablesTyped(deserializeValues); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExecutionVariableSnapshotObserver.java
1
请完成以下Java代码
public int getNbest_() { return nbest_; } public void setNbest_(int nbest_) { this.nbest_ = nbest_; } public int getVlevel_() { return vlevel_; }
public void setVlevel_(int vlevel_) { this.vlevel_ = vlevel_; } public DecoderFeatureIndex getFeatureIndex_() { return featureIndex_; } public void setFeatureIndex_(DecoderFeatureIndex featureIndex_) { this.featureIndex_ = featureIndex_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\ModelImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<Task> list() { cachedCandidateGroups = null; return super.list(); } @Override public List<Task> listPage(int firstResult, int maxResults) { cachedCandidateGroups = null; return super.listPage(firstResult, maxResults); } @Override public long count() { cachedCandidateGroups = null; return super.count(); } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; } public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups;
} public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java
2
请完成以下Java代码
public void setDIM_Dimension_Spec_ID (int DIM_Dimension_Spec_ID) { if (DIM_Dimension_Spec_ID < 1) set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, null); else set_ValueNoCheck (COLUMNNAME_DIM_Dimension_Spec_ID, Integer.valueOf(DIM_Dimension_Spec_ID)); } /** Get Dimensionsspezifikation. @return Dimensionsspezifikation */ @Override public int getDIM_Dimension_Spec_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DIM_Dimension_Spec_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Alle Attributwerte. @param IsIncludeAllAttributeValues Alle Attributwerte */ @Override public void setIsIncludeAllAttributeValues (boolean IsIncludeAllAttributeValues) { set_Value (COLUMNNAME_IsIncludeAllAttributeValues, Boolean.valueOf(IsIncludeAllAttributeValues)); } /** Get Alle Attributwerte. @return Alle Attributwerte */ @Override public boolean isIncludeAllAttributeValues () { Object oo = get_Value(COLUMNNAME_IsIncludeAllAttributeValues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Merkmalswert-Zusammenfassung. @param IsValueAggregate Merkmalswert-Zusammenfassung */ @Override public void setIsValueAggregate (boolean IsValueAggregate) { set_Value (COLUMNNAME_IsValueAggregate, Boolean.valueOf(IsValueAggregate)); } /** Get Merkmalswert-Zusammenfassung. @return Merkmalswert-Zusammenfassung */ @Override public boolean isValueAggregate () { Object oo = get_Value(COLUMNNAME_IsValueAggregate); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Merkmal. @param M_Attribute_ID Produkt-Merkmal */ @Override public void setM_Attribute_ID (int M_Attribute_ID) { if (M_Attribute_ID < 1) set_Value (COLUMNNAME_M_Attribute_ID, null); else set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID)); } /** Get Merkmal. @return Produkt-Merkmal */ @Override public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gruppenname. @param ValueAggregateName Gruppenname */ @Override public void setValueAggregateName (java.lang.String ValueAggregateName) { set_Value (COLUMNNAME_ValueAggregateName, ValueAggregateName); } /** Get Gruppenname. @return Gruppenname */ @Override public java.lang.String getValueAggregateName () { return (java.lang.String)get_Value(COLUMNNAME_ValueAggregateName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec_Attribute.java
1
请完成以下Java代码
public void deleteApiKey(TenantId tenantId, ApiKey apiKey, boolean force) { UUID apiKeyId = apiKey.getUuidId(); validateId(apiKeyId, id -> INCORRECT_API_KEY_ID + id); apiKeyDao.removeById(tenantId, apiKeyId); publishEvictEvent(new ApiKeyEvictEvent(apiKey.getValue())); } @Override public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteApiKeysByTenantId, tenantId [{}]", tenantId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); Set<String> values = apiKeyDao.deleteByTenantId(tenantId); values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value))); } @Override public void deleteByUserId(TenantId tenantId, UserId userId) { log.trace("Executing deleteApiKeysByUserId, tenantId [{}]", tenantId); validateId(userId, id -> INCORRECT_USER_ID + id); Set<String> values = apiKeyDao.deleteByUserId(tenantId, userId); values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value)));
} @Override public ApiKey findApiKeyByValue(String value) { log.trace("Executing findApiKeyByValue [{}]", value); var cacheKey = ApiKeyCacheKey.of(value); return cache.getAndPutInTransaction(cacheKey, () -> apiKeyDao.findByValue(value), true); } private String generateApiKeySecret() { return prefix + StringUtils.generateSafeToken(Math.min(valueBytesSize, MAX_API_KEY_VALUE_LENGTH)); } @Override public EntityType getEntityType() { return EntityType.API_KEY; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\pat\ApiKeyServiceImpl.java
1
请完成以下Java代码
public boolean isFollowUpNullAccepted() { return followUpNullAccepted; } @Override public TaskQuery taskNameNotEqual(String name) { this.nameNotEqual = name; return this; } @Override public TaskQuery taskNameNotLike(String nameNotLike) { ensureNotNull("Task nameNotLike", nameNotLike); this.nameNotLike = nameNotLike; return this; } /** * @return true if the query is not supposed to find CMMN or standalone tasks */ public boolean isQueryForProcessTasksOnly() { ProcessEngineConfigurationImpl engineConfiguration = Context.getProcessEngineConfiguration(); return !engineConfiguration.isCmmnEnabled() && !engineConfiguration.isStandaloneTasksEnabled(); } @Override public TaskQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } TaskQueryImpl orQuery = new TaskQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries;
queries.add(orQuery); return orQuery; } @Override public TaskQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } @Override public TaskQuery matchVariableNamesIgnoreCase() { this.variableNamesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableNameIgnoreCase(true); } return this; } @Override public TaskQuery matchVariableValuesIgnoreCase() { this.variableValuesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableValueIgnoreCase(true); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("app-a") .secret(passwordEncoder.encode("app-a-1234")) .authorizedGrantTypes("refresh_token","authorization_code") .accessTokenValiditySeconds(3600) .scopes("all") .autoApprove(true) .redirectUris("http://127.0.0.1:9090/app1/login") .and() .withClient("app-b") .secret(passwordEncoder.encode("app-b-1234")) .authorizedGrantTypes("refresh_token","authorization_code") .accessTokenValiditySeconds(7200) .scopes("all") .autoApprove(true)
.redirectUris("http://127.0.0.1:9091/app2/login"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints.tokenStore(jwtTokenStore()) .accessTokenConverter(jwtAccessTokenConverter()) .userDetailsService(userDetailService); } @Override public void configure(AuthorizationServerSecurityConfigurer security) { security.tokenKeyAccess("isAuthenticated()"); // 获取密钥需要身份认证 } }
repos\SpringAll-master\66.Spring-Security-OAuth2-SSO\sso-server\src\main\java\cc\mrbird\sso\server\config\SsoAuthorizationServerConfig.java
2
请完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override public BigDecimal getPrice()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty (final BigDecimal Qty) { set_Value (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_C_OrderLine_Detail.java
1
请完成以下Java代码
public void unclose(final I_PP_Order_BOMLine line) { changeQuantities(line, OrderBOMLineQuantities::unclose); orderBOMsRepo.save(line); } @Override public boolean isSomethingReported(@NonNull final I_PP_Order ppOrder) { if (getQuantities(ppOrder).isSomethingReported()) { return true; } final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID()); return orderBOMsRepo.retrieveOrderBOMLines(ppOrderId) .stream() .map(this::getQuantities) .anyMatch(OrderBOMLineQuantities::isSomethingReported); } @Override public Optional<DocSequenceId> getSerialNoSequenceId(@NonNull final PPOrderId ppOrderId) { final I_PP_Order_BOM orderBOM = orderBOMsRepo.getByOrderIdOrNull(ppOrderId); if (orderBOM == null) { throw new AdempiereException("@NotFound@ @PP_Order_BOM_ID@: " + ppOrderId); } return DocSequenceId.optionalOfRepoId(orderBOM.getSerialNo_Sequence_ID()); } @Override public QtyCalculationsBOM getQtyCalculationsBOM(@NonNull final I_PP_Order order) { final ImmutableList<QtyCalculationsBOMLine> lines = orderBOMsRepo.retrieveOrderBOMLines(order) .stream() .map(orderBOMLineRecord -> toQtyCalculationsBOMLine(order, orderBOMLineRecord)) .collect(ImmutableList.toImmutableList()); return QtyCalculationsBOM.builder() .lines(lines) .orderId(PPOrderId.ofRepoIdOrNull(order.getPP_Order_ID())) .build(); } @Override
public void save(final I_PP_Order_BOMLine orderBOMLine) { orderBOMsRepo.save(orderBOMLine); } @Override public Set<ProductId> getProductIdsToIssue(final PPOrderId ppOrderId) { return getOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class) .stream() .filter(bomLine -> BOMComponentType.ofNullableCodeOrComponent(bomLine.getComponentType()).isIssue()) .map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(@NonNull final I_PP_Order ppOrder) { final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrder.getM_Warehouse_ID()); return getIssueFromWarehouseIds(warehouseId); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(final WarehouseId ppOrderWarehouseId) { return warehouseDAO.getWarehouseIdsOfSameGroup(ppOrderWarehouseId, WarehouseGroupAssignmentType.MANUFACTURING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMBL.java
1
请完成以下Java代码
public void add (Timestamp DueDate, int daysDue, BigDecimal invoicedAmt, BigDecimal openAmt) { if (invoicedAmt == null) invoicedAmt = Env.ZERO; setInvoicedAmt(getInvoicedAmt().add(invoicedAmt)); if (openAmt == null) openAmt = Env.ZERO; setOpenAmt(getOpenAmt().add(openAmt)); // Days Due m_noItems++; m_daysDueSum += daysDue; setDaysDue(m_daysDueSum/m_noItems); // Due Date if (getDueDate().after(DueDate)) setDueDate(DueDate); // earliest // BigDecimal amt = openAmt; // Not due - negative if (daysDue <= 0) { setDueAmt (getDueAmt().add(amt)); if (daysDue == 0) setDue0 (getDue0().add(amt)); if (daysDue >= -7) setDue0_7 (getDue0_7().add(amt)); if (daysDue >= -30) setDue0_30 (getDue0_30().add(amt)); if (daysDue <= -1 && daysDue >= -7) setDue1_7 (getDue1_7().add(amt)); if (daysDue <= -8 && daysDue >= -30) setDue8_30 (getDue8_30().add(amt)); if (daysDue <= -31 && daysDue >= -60) setDue31_60 (getDue31_60().add(amt)); if (daysDue <= -31) setDue31_Plus (getDue31_Plus().add(amt)); if (daysDue <= -61 && daysDue >= -90) setDue61_90 (getDue61_90().add(amt)); if (daysDue <= -61) setDue61_Plus (getDue61_Plus().add(amt)); if (daysDue <= -91) setDue91_Plus (getDue91_Plus().add(amt)); }
else // Due = positive (> 1) { setPastDueAmt (getPastDueAmt().add(amt)); if (daysDue <= 7) setPastDue1_7 (getPastDue1_7().add(amt)); if (daysDue <= 30) setPastDue1_30 (getPastDue1_30().add(amt)); if (daysDue >= 8 && daysDue <= 30) setPastDue8_30 (getPastDue8_30().add(amt)); if (daysDue >= 31 && daysDue <= 60) setPastDue31_60 (getPastDue31_60().add(amt)); if (daysDue >= 31) setPastDue31_Plus (getPastDue31_Plus().add(amt)); if (daysDue >= 61 && daysDue <= 90) setPastDue61_90 (getPastDue61_90().add(amt)); if (daysDue >= 61) setPastDue61_Plus (getPastDue61_Plus().add(amt)); if (daysDue >= 91) setPastDue91_Plus (getPastDue91_Plus().add(amt)); } } // add /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer("MAging["); sb.append("AD_PInstance_ID=").append(getAD_PInstance_ID()) .append(",C_BPartner_ID=").append(getC_BPartner_ID()) .append(",C_Currency_ID=").append(getC_Currency_ID()) .append(",C_Invoice_ID=").append(getC_Invoice_ID()); sb.append("]"); return sb.toString(); } // toString } // MAging
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAging.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Number of Months. @param NoMonths Number of Months */ public void setNoMonths (int NoMonths) { set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths)); } /** Get Number of Months. @return Number of Months */ public int getNoMonths () { Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths); if (ii == null) return 0; return ii.intValue();
} /** RecognitionFrequency AD_Reference_ID=196 */ public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196; /** Month = M */ public static final String RECOGNITIONFREQUENCY_Month = "M"; /** Quarter = Q */ public static final String RECOGNITIONFREQUENCY_Quarter = "Q"; /** Year = Y */ public static final String RECOGNITIONFREQUENCY_Year = "Y"; /** Set Recognition frequency. @param RecognitionFrequency Recognition frequency */ public void setRecognitionFrequency (String RecognitionFrequency) { set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency); } /** Get Recognition frequency. @return Recognition frequency */ public String getRecognitionFrequency () { return (String)get_Value(COLUMNNAME_RecognitionFrequency); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionDetailsFilter extends OncePerRequestFilter { static final String UNKNOWN = "Unknown"; private DatabaseReader reader; @Autowired public SessionDetailsFilter(DatabaseReader reader) { this.reader = reader; } // tag::dofilterinternal[] @Override public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); HttpSession session = request.getSession(false); if (session != null) { String remoteAddr = getRemoteAddress(request); String geoLocation = getGeoLocation(remoteAddr); SessionDetails details = new SessionDetails(); details.setAccessType(request.getHeader("User-Agent")); details.setLocation(remoteAddr + " " + geoLocation); session.setAttribute("SESSION_DETAILS", details); } } // end::dofilterinternal[] String getGeoLocation(String remoteAddr) { try { CityResponse city = this.reader.city(InetAddress.getByName(remoteAddr)); String cityName = city.getCity().getName(); String countryName = city.getCountry().getName(); if (cityName == null && countryName == null) { return null;
} else if (cityName == null) { return countryName; } else if (countryName == null) { return cityName; } return cityName + ", " + countryName; } catch (Exception ex) { return UNKNOWN; } } private String getRemoteAddress(HttpServletRequest request) { String remoteAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteAddr == null) { remoteAddr = request.getRemoteAddr(); } else if (remoteAddr.contains(",")) { remoteAddr = remoteAddr.split(",")[0]; } return remoteAddr; } } // end::class[]
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-findbyusername\src\main\java\sample\session\SessionDetailsFilter.java
2
请完成以下Java代码
public class ResultItemWrapper<ValueType> implements ResultItem { private final ValueType value; public ResultItemWrapper(final ValueType value) { super(); Check.assumeNotNull(value, "value not null"); this.value = value; } public final ValueType getValue() { return value; } @Override public String getText() { return value.toString(); } @Override public String toString() { return getText(); } @Override public int hashCode() { return new HashcodeBuilder() .append(value)
.toHashcode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final ResultItemWrapper<ValueType> other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(this.value, other.value) .isEqual(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\swing\autocomplete\ResultItemWrapper.java
1
请完成以下Java代码
public ITrxItemExecutorBuilder<IT, RT> setContext(final ITrxItemProcessorContext processorCtx) { this._processorCtx = processorCtx; this._ctx = null; this._trxName = null; return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor) { this._processor = processor; return this; } private final ITrxItemProcessor<IT, RT> getProcessor() { Check.assumeNotNull(_processor, "processor is set"); return _processor; } @Override public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler) { this._exceptionHandler = exceptionHandler; return this; } private final ITrxItemExceptionHandler getExceptionHandler() { return _exceptionHandler; } @Override public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy) { this._onItemErrorPolicy = onItemErrorPolicy; return this; }
@Override public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch) { if (itemsPerBatch == Integer.MAX_VALUE) { this.itemsPerBatch = null; } else { this.itemsPerBatch = itemsPerBatch; } return this; } @Override public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints) { this._useTrxSavepoints = useTrxSavepoints; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java
1
请完成以下Java代码
public int compare(Map.Entry<K, Float> o1, Map.Entry<K, Float> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<K, Vector> entry : storage.entrySet()) { if (entry.getKey().equals(key)) { continue; } maxHeap.add(new AbstractMap.SimpleEntry<K, Float>(entry.getKey(), entry.getValue().cosineForUnitVector(vector))); } return maxHeap.toList(); } /** * 获取与向量最相似的词语 * * @param vector 向量 * @param size topN个 * @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 */ public List<Map.Entry<K, Float>> nearest(Vector vector, int size) { MaxHeap<Map.Entry<K, Float>> maxHeap = new MaxHeap<Map.Entry<K, Float>>(size, new Comparator<Map.Entry<K, Float>>() { @Override public int compare(Map.Entry<K, Float> o1, Map.Entry<K, Float> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<K, Vector> entry : storage.entrySet()) { maxHeap.add(new AbstractMap.SimpleEntry<K, Float>(entry.getKey(), entry.getValue().cosineForUnitVector(vector))); } return maxHeap.toList(); } /** * 获取与向量最相似的词语(默认10个) * * @param vector 向量 * @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 */ public List<Map.Entry<K, Float>> nearest(Vector vector) { return nearest(vector, 10); } /** * 查询与词语最相似的词语 * * @param key 词语 * @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列 */ public List<Map.Entry<K, Float>> nearest(K key) { return nearest(key, 10); } /** * 执行查询最相似的对象(子类通过query方法决定如何解析query,然后通过此方法执行查询) * * @param query 查询语句(或者说一个对象的内容) * @param size 需要返回前多少个对象 * @return */ final List<Map.Entry<K, Float>> queryNearest(String query, int size) { if (query == null || query.length() == 0) { return Collections.emptyList(); } try { return nearest(query(query), size); }
catch (Exception e) { return Collections.emptyList(); } } /** * 查询抽象文本对应的向量。此方法应当保证返回单位向量。 * * @param query * @return */ public abstract Vector query(String query); /** * 模型中的词向量总数(词表大小) * * @return */ public int size() { return storage.size(); } /** * 模型中的词向量维度 * * @return */ public int dimension() { if (storage == null || storage.isEmpty()) { return 0; } return storage.values().iterator().next().size(); } /** * 删除元素 * * @param key * @return */ public Vector remove(K key) { return storage.remove(key); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractVectorModel.java
1
请完成以下Java代码
public IView createView(@NonNull final CreateViewRequest request) { final StockDetailsRowsData stockDetailsRowData = createStockDetailsRowData(request); return new StockDetailsView( request.getViewId(), request.getParentViewId(), stockDetailsRowData, ImmutableDocumentFilterDescriptorsProvider.of(createEmptyFilterDescriptor())); } private DocumentFilterDescriptor createEmptyFilterDescriptor() { return ProductFilterUtil.createFilterDescriptor(); } private StockDetailsRowsData createStockDetailsRowData(@NonNull final CreateViewRequest request) { final DocumentFilterList filters = request.getStickyFilters(); final HUStockInfoQueryBuilder query = HUStockInfoQuery.builder(); for (final DocumentFilter filter : filters.toList()) { final HUStockInfoSingleQueryBuilder singleQuery = HUStockInfoSingleQuery.builder(); final int productRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Product_ID, -1); singleQuery.productId(ProductId.ofRepoIdOrNull(productRepoId)); final int attributeRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Attribute_ID, -1); singleQuery.attributeId(AttributeId.ofRepoIdOrNull(attributeRepoId)); final String attributeValue = filter.getParameterValueAsString(I_M_HU_Stock_Detail_V.COLUMNNAME_AttributeValue, null); if (MaterialCockpitUtil.DONT_FILTER.equals(attributeValue)) { singleQuery.attributeValue(AttributeValue.DONT_FILTER); } else { singleQuery.attributeValue(AttributeValue.NOT_EMPTY); } query.singleQuery(singleQuery.build());
} final Stream<HUStockInfo> huStockInfos = huStockInfoRepository.getByQuery(query.build()); return StockDetailsRowsData.of(huStockInfos); } @Override public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(windowId) // .caption(caption) .setFilters(ImmutableList.of(createEmptyFilterDescriptor())) .addElementsFromViewRowClass(StockDetailsRow.class, viewDataType) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsViewFactory.java
1
请完成以下Spring Boot application配置
server: port: 8088 spring: redis: database: 0 host: 127.0.0.1 port: 6379 password: 123456 lettuce: pool: min-idle: 0 max-active
: 8 max-idle: 8 max-wait: -1ms connect-timeout: 30000ms
repos\springboot-demo-master\redis\src\main\resources\application.yaml
2
请完成以下Java代码
public XMLGregorianCalendar getRequestDate() { return requestDate; } /** * Sets the value of the requestDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setRequestDate(XMLGregorianCalendar value) { this.requestDate = value; } /** * Gets the value of the requestId property. * * @return * possible object is * {@link String } * */ public String getRequestId() {
return requestId; } /** * Sets the value of the requestId property. * * @param value * allowed object is * {@link String } * */ public void setRequestId(String value) { this.requestId = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CreditType.java
1
请在Spring Boot框架中完成以下Java代码
public class TaskConfiguration extends ResourceServerConfigurerAdapter { /** * Provide security so that endpoints are only served if the request is * already authenticated. */ @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http.requestMatchers() .antMatchers("/**") .and() .authorizeRequests() .anyRequest() .authenticated() .antMatchers(HttpMethod.GET, "/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.OPTIONS, "/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.POST, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PUT, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PATCH, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.DELETE, "/**").access("#oauth2.hasScope('write')"); // @formatter:on }
/** * Id of the resource that you are letting the client have access to. * Supposing you have another api ("say api2"), then you can customize the * access within resource server to define what api is for what resource id. * <br> * <br> * * So suppose you have 2 APIs, then you can define 2 resource servers. * <ol> * <li>Client 1 has been configured for access to resourceid1, so he can * only access "api1" if the resource server configures the resourceid to * "api1".</li> * <li>Client 1 can't access resource server 2 since it has configured the * resource id to "api2" * </li> * </ol> * */ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("apis"); } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\config\TaskConfiguration.java
2
请完成以下Java代码
protected Class<DashboardEntity> getEntityClass() { return DashboardEntity.class; } @Override protected JpaRepository<DashboardEntity, UUID> getRepository() { return dashboardRepository; } @Override public Long countByTenantId(TenantId tenantId) { return dashboardRepository.countByTenantId(tenantId.getId()); } @Override public Dashboard findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(dashboardRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public PageData<Dashboard> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(dashboardRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override public DashboardId getExternalIdByInternal(DashboardId internalId) { return Optional.ofNullable(dashboardRepository.getExternalIdById(internalId.getId())) .map(DashboardId::new).orElse(null); } @Override public List<Dashboard> findByTenantIdAndTitle(UUID tenantId, String title) { return DaoUtil.convertDataList(dashboardRepository.findByTenantIdAndTitle(tenantId, title)); } @Override public PageData<DashboardId> findIdsByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.pageToPageData(dashboardRepository.findIdsByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)).map(DashboardId::new));
} @Override public PageData<DashboardId> findAllIds(PageLink pageLink) { return DaoUtil.pageToPageData(dashboardRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(DashboardId::new)); } @Override public PageData<Dashboard> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<DashboardFields> findNextBatch(UUID id, int batchSize) { return dashboardRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.DASHBOARD; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\dashboard\JpaDashboardDao.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String name; public User() { } public User(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id;
} public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-webapp-jsp\src\main\java\net\alanbinu\springboot2\springboot2webappjsp\domain\User.java
2
请完成以下Java代码
private DocumentFilterDescriptor createEmptyFilterDescriptor() { return ProductFilterUtil.createFilterDescriptor(); } private StockDetailsRowsData createStockDetailsRowData(@NonNull final CreateViewRequest request) { final DocumentFilterList filters = request.getStickyFilters(); final HUStockInfoQueryBuilder query = HUStockInfoQuery.builder(); for (final DocumentFilter filter : filters.toList()) { final HUStockInfoSingleQueryBuilder singleQuery = HUStockInfoSingleQuery.builder(); final int productRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Product_ID, -1); singleQuery.productId(ProductId.ofRepoIdOrNull(productRepoId)); final int attributeRepoId = filter.getParameterValueAsInt(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Attribute_ID, -1); singleQuery.attributeId(AttributeId.ofRepoIdOrNull(attributeRepoId)); final String attributeValue = filter.getParameterValueAsString(I_M_HU_Stock_Detail_V.COLUMNNAME_AttributeValue, null); if (MaterialCockpitUtil.DONT_FILTER.equals(attributeValue)) { singleQuery.attributeValue(AttributeValue.DONT_FILTER); } else {
singleQuery.attributeValue(AttributeValue.NOT_EMPTY); } query.singleQuery(singleQuery.build()); } final Stream<HUStockInfo> huStockInfos = huStockInfoRepository.getByQuery(query.build()); return StockDetailsRowsData.of(huStockInfos); } @Override public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, final ViewProfileId profileId) { return ViewLayout.builder() .setWindowId(windowId) // .caption(caption) .setFilters(ImmutableList.of(createEmptyFilterDescriptor())) .addElementsFromViewRowClass(StockDetailsRow.class, viewDataType) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsViewFactory.java
1
请完成以下Java代码
public boolean isEnableProcessDefinitionInfoCache() { return enableProcessDefinitionInfoCache; } public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) { this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache; return this; } public TaskPostProcessor getTaskPostProcessor() { return taskPostProcessor; } public void setTaskPostProcessor(TaskPostProcessor processor) { this.taskPostProcessor = processor; } public boolean isEnableHistoryCleaning() { return enableHistoryCleaning; } public ProcessEngineConfiguration setEnableHistoryCleaning(boolean enableHistoryCleaning) { this.enableHistoryCleaning = enableHistoryCleaning; return this; } public String getHistoryCleaningTimeCycleConfig() { return historyCleaningTimeCycleConfig; } public ProcessEngineConfiguration setHistoryCleaningTimeCycleConfig(String historyCleaningTimeCycleConfig) { this.historyCleaningTimeCycleConfig = historyCleaningTimeCycleConfig; return this; } /** * @deprecated use {@link #getCleanInstancesEndedAfter()} instead */ @Deprecated public int getCleanInstancesEndedAfterNumberOfDays() { return (int) cleanInstancesEndedAfter.toDays(); } /** * @deprecated use {@link #setCleanInstancesEndedAfter(Duration)} instead */ @Deprecated public ProcessEngineConfiguration setCleanInstancesEndedAfterNumberOfDays(int cleanInstancesEndedAfterNumberOfDays) { return setCleanInstancesEndedAfter(Duration.ofDays(cleanInstancesEndedAfterNumberOfDays)); } public Duration getCleanInstancesEndedAfter() { return cleanInstancesEndedAfter;
} public ProcessEngineConfiguration setCleanInstancesEndedAfter(Duration cleanInstancesEndedAfter) { this.cleanInstancesEndedAfter = cleanInstancesEndedAfter; return this; } public int getCleanInstancesBatchSize() { return cleanInstancesBatchSize; } public ProcessEngineConfiguration setCleanInstancesBatchSize(int cleanInstancesBatchSize) { this.cleanInstancesBatchSize = cleanInstancesBatchSize; return this; } public HistoryCleaningManager getHistoryCleaningManager() { return historyCleaningManager; } public ProcessEngineConfiguration setHistoryCleaningManager(HistoryCleaningManager historyCleaningManager) { this.historyCleaningManager = historyCleaningManager; return this; } public boolean isAlwaysUseArraysForDmnMultiHitPolicies() { return alwaysUseArraysForDmnMultiHitPolicies; } public ProcessEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) { this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies; return this; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\ProcessEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public StaxEventItemWriter<Transaction> itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); return itemWriter; } @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setMaxPoolSize(5); taskExecutor.setCorePoolSize(5); taskExecutor.setQueueCapacity(5); taskExecutor.afterPropertiesSet(); return taskExecutor; } @Bean(name = "jobRepository") public JobRepository getJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); // JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "dataSource") public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2) .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") .addScript("classpath:org/springframework/batch/core/schema-h2.sql") .build(); } @Bean(name = "transactionManager") public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Bean(name = "jobLauncher") public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // SimpleJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\partitioner\SpringBatchPartitionConfig.java
2
请完成以下Java代码
public class VariableUpdatedListenerDelegate implements ActivitiEventListener { private final List<VariableEventListener<VariableUpdatedEvent>> listeners; private final ToVariableUpdatedConverter converter; private final VariableEventFilter variableEventFilter; public VariableUpdatedListenerDelegate( List<VariableEventListener<VariableUpdatedEvent>> listeners, ToVariableUpdatedConverter converter, VariableEventFilter variableEventFilter ) { this.listeners = listeners; this.converter = converter; this.variableEventFilter = variableEventFilter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiVariableUpdatedEvent) { ActivitiVariableUpdatedEvent internalEvent = (ActivitiVariableUpdatedEvent) event; if (variableEventFilter.shouldEmmitEvent(internalEvent)) { converter
.from(internalEvent) .ifPresent(convertedEvent -> { if (listeners != null) { for (VariableEventListener<VariableUpdatedEvent> listener : listeners) { listener.onEvent(convertedEvent); } } }); } } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-runtime-shared-impl\src\main\java\org\activiti\runtime\api\event\internal\VariableUpdatedListenerDelegate.java
1
请完成以下Java代码
public void onIsCompanyFlagChanged(@NonNull final I_C_BPartner_QuickInput record) { bpartnerQuickInputService.updateNameAndGreetingNoSave(record); } @CalloutMethod(columnNames = I_C_BPartner_QuickInput.COLUMNNAME_C_Location_ID) public void onLocationChanged(@NonNull final I_C_BPartner_QuickInput record) { final OrgId orgInChangeId = getOrgInChangeViaLocationPostalCode(record); if (orgInChangeId == null) { return; } final boolean userHasOrgPermissions = Env.getUserRolePermissions().isOrgAccess(orgInChangeId, null, Access.WRITE); if (userHasOrgPermissions) { record.setAD_Org_ID(orgInChangeId.getRepoId()); } } @Nullable private OrgId getOrgInChangeViaLocationPostalCode(final @NonNull I_C_BPartner_QuickInput record)
{ final LocationId locationId = LocationId.ofRepoIdOrNull(record.getC_Location_ID()); if (locationId == null) { return null; } final I_C_Location locationRecord = locationDAO.getById(locationId); final PostalId postalId = PostalId.ofRepoIdOrNull(locationRecord.getC_Postal_ID()); if (postalId == null) { return null; } final I_C_Postal postalRecord = locationDAO.getPostalById(postalId); final OrgId orgInChargeId = OrgId.ofRepoId(postalRecord.getAD_Org_InCharge_ID()); return orgInChargeId.isRegular() ? orgInChargeId : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_QuickInput.java
1
请在Spring Boot框架中完成以下Java代码
public Void execute(CommandContext commandContext) { JobQueryImpl jobQuery = new JobQueryImpl(commandContext, jobServiceConfiguration); jobQuery.lockOwner(lockOwner); // The tenantId is only used if it has been explicitly set if (tenantId != null) { if (!tenantId.isEmpty()) { jobQuery.jobTenantId(tenantId); } else { jobQuery.jobWithoutTenantId(); } } List<Job> jobs = jobServiceConfiguration.getJobEntityManager().findJobsByQueryCriteria(jobQuery); for (Job job : jobs) { try { jobServiceConfiguration.getJobManager().unacquire(job); logJobUnlocking(job); } catch (Exception e) { /*
* Not logging the exception. The engine is shutting down, so not much can be done at this point. * * Furthermore: some exceptions can be expected here: if the job was picked up and put in the queue when * the shutdown was triggered, the job can still be executed as the threadpool doesn't shut down immediately. * * This would then throw an NPE for data related to the job queried here (e.g. the job itself or related executions). * That is also why the exception is catched here and not higher-up (e.g. at the flush, but the flush won't be reached for an NPE) */ } } return null; } protected void logJobUnlocking(Job job) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Unacquired job {} with owner {} and tenantId {}", job, lockOwner, tenantId); } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\UnacquireOwnedJobsCmd.java
2
请在Spring Boot框架中完成以下Java代码
public class DocTypePrintOptionsRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<Integer, DocTypePrintOptionsMap> cache = CCache.<Integer, DocTypePrintOptionsMap>builder() .tableName(I_C_DocType_PrintOptions.Table_Name) .build(); @NonNull public DocumentPrintOptions getByDocTypeAndFlavor( @NonNull final DocTypeId docTypeId, @NonNull final DocumentReportFlavor flavor) { return getDocTypePrintOptionsMap().getByDocTypeAndFlavor(docTypeId, flavor); } private DocTypePrintOptionsMap getDocTypePrintOptionsMap() { return cache.getOrLoad(0, this::retrieveDocTypePrintOptionsMap); } private DocTypePrintOptionsMap retrieveDocTypePrintOptionsMap() { final ImmutableMap<DocTypePrintOptionsKey, DocumentPrintOptions> map = queryBL .createQueryBuilderOutOfTrx(I_C_DocType_PrintOptions.class) .addOnlyActiveRecordsFilter() .create() .stream() .collect(ImmutableMap.toImmutableMap( DocTypePrintOptionsRepository::toDocTypePrintOptionsKey, DocTypePrintOptionsRepository::toDocumentPrintOptions)); return !map.isEmpty() ? new DocTypePrintOptionsMap(map) : DocTypePrintOptionsMap.EMPTY; } @NonNull private static DocTypePrintOptionsKey toDocTypePrintOptionsKey(@NonNull final I_C_DocType_PrintOptions record) { final DocTypeId docTypeId = DocTypeId.ofRepoId(record.getC_DocType_ID()); final DocumentReportFlavor flavor = DocumentReportFlavor.ofNullableCode(record.getDocumentFlavor()); return DocTypePrintOptionsKey.of(docTypeId, flavor); } @NonNull private static DocumentPrintOptions toDocumentPrintOptions(@NonNull final I_C_DocType_PrintOptions record) { return DocumentPrintOptions.builder() .sourceName("DocType options: C_DocType_ID=" + record.getC_DocType_ID() + ", flavor=" + DocumentReportFlavor.ofNullableCode(record.getDocumentFlavor())) .option(DocumentPrintOptions.OPTION_IsPrintLogo, record.isPRINTER_OPTS_IsPrintLogo()) .option(DocumentPrintOptions.OPTION_IsPrintTotals, record.isPRINTER_OPTS_IsPrintTotals()) .build(); }
@Value(staticConstructor = "of") private static class DocTypePrintOptionsKey { @NonNull DocTypeId docTypeId; @Nullable DocumentReportFlavor flavor; } private static class DocTypePrintOptionsMap { public static final DocTypePrintOptionsMap EMPTY = new DocTypePrintOptionsMap(ImmutableMap.of()); private final ImmutableMap<DocTypePrintOptionsKey, DocumentPrintOptions> map; DocTypePrintOptionsMap(final Map<DocTypePrintOptionsKey, DocumentPrintOptions> map) { this.map = ImmutableMap.copyOf(map); } public DocumentPrintOptions getByDocTypeAndFlavor( @NonNull final DocTypeId docTypeId, @NonNull final DocumentReportFlavor flavor) { return CoalesceUtil.coalesceSuppliers( () -> map.get(DocTypePrintOptionsKey.of(docTypeId, flavor)), () -> map.get(DocTypePrintOptionsKey.of(docTypeId, null)), () -> DocumentPrintOptions.NONE); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocTypePrintOptionsRepository.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("size", tableInfoByTableName.size()) .toString(); } @Nullable public TableInfo getTableInfoOrNull(final String tableName) { final TableNameKey tableNameKey = TableNameKey.of(tableName); return tableInfoByTableName.get(tableNameKey); } @Nullable public TableInfo getTableInfoOrNull(final AdTableId adTableId) { return tableInfoByTableId.get(adTableId); } } private static class JUnitGeneratedTableInfoMap { private final AtomicInteger nextTableId2 = new AtomicInteger(1); private final HashMap<TableNameKey, TableInfo> tableInfoByTableName = new HashMap<>(); private final HashMap<AdTableId, TableInfo> tableInfoByTableId = new HashMap<>(); public AdTableId getOrCreateTableId(@NonNull final String tableName) { final TableNameKey tableNameKey = TableNameKey.of(tableName); TableInfo tableInfo = tableInfoByTableName.get(tableNameKey); if (tableInfo == null) { tableInfo = TableInfo.builder() .adTableId(AdTableId.ofRepoId(nextTableId2.getAndIncrement())) .tableName(tableName) .entityType("D") .tooltipType(TooltipType.DEFAULT) .build(); tableInfoByTableName.put(tableNameKey, tableInfo); tableInfoByTableId.put(tableInfo.getAdTableId(), tableInfo); } return tableInfo.getAdTableId(); } public String getTableName(@NonNull final AdTableId adTableId) { final TableInfo tableInfo = tableInfoByTableId.get(adTableId); if (tableInfo != null)
{ return tableInfo.getTableName(); } //noinspection ConstantConditions final I_AD_Table adTable = POJOLookupMap.get().lookup("AD_Table", adTableId.getRepoId()); if (adTable != null) { final String tableName = adTable.getTableName(); if (Check.isBlank(tableName)) { throw new AdempiereException("No TableName set for " + adTable); } return tableName; } // throw new AdempiereException("No TableName found for AD_Table_ID=" + adTableId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\TableIdsCache.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSessionServerSecurityContextRepository implements ServerSecurityContextRepository { private static final Log logger = LogFactory.getLog(WebSessionServerSecurityContextRepository.class); /** * The default session attribute name to save and load the {@link SecurityContext} */ public static final String DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME = "SPRING_SECURITY_CONTEXT"; private String springSecurityContextAttrName = DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME; private boolean cacheSecurityContext; /** * Sets the session attribute name used to save and load the {@link SecurityContext} * @param springSecurityContextAttrName the session attribute name to use to save and * load the {@link SecurityContext} */ public void setSpringSecurityContextAttrName(String springSecurityContextAttrName) { Assert.hasText(springSecurityContextAttrName, "springSecurityContextAttrName cannot be null or empty"); this.springSecurityContextAttrName = springSecurityContextAttrName; } /** * If set to true the result of {@link #load(ServerWebExchange)} will use * {@link Mono#cache()} to prevent multiple lookups. * @param cacheSecurityContext true if {@link Mono#cache()} should be used, else * false. */ public void setCacheSecurityContext(boolean cacheSecurityContext) {
this.cacheSecurityContext = cacheSecurityContext; } @Override public Mono<Void> save(ServerWebExchange exchange, @Nullable SecurityContext context) { return exchange.getSession().doOnNext((session) -> { if (context == null) { session.getAttributes().remove(this.springSecurityContextAttrName); logger.debug(LogMessage.format("Removed SecurityContext stored in WebSession: '%s'", session)); } else { session.getAttributes().put(this.springSecurityContextAttrName, context); logger.debug(LogMessage.format("Saved SecurityContext '%s' in WebSession: '%s'", context, session)); } }).flatMap(WebSession::changeSessionId); } @Override public Mono<SecurityContext> load(ServerWebExchange exchange) { Mono<SecurityContext> result = exchange.getSession().flatMap((session) -> { SecurityContext context = (SecurityContext) session.getAttribute(this.springSecurityContextAttrName); logger.debug((context != null) ? LogMessage.format("Found SecurityContext '%s' in WebSession: '%s'", context, session) : LogMessage.format("No SecurityContext found in WebSession: '%s'", session)); return Mono.justOrEmpty(context); }); return (this.cacheSecurityContext) ? result.cache() : result; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\context\WebSessionServerSecurityContextRepository.java
2
请完成以下Java代码
public class BooleanFormType extends SimpleFormFieldType { public final static String TYPE_NAME = "boolean"; public String getName() { return TYPE_NAME; } public TypedValue convertValue(TypedValue propertyValue) { if(propertyValue instanceof BooleanValue) { return propertyValue; } else { Object value = propertyValue.getValue(); if(value == null) { return Variables.booleanValue(null, propertyValue.isTransient()); } else if((value instanceof Boolean) || (value instanceof String)) { return Variables.booleanValue(Boolean.valueOf(value.toString()), propertyValue.isTransient()); } else { throw new ProcessEngineException("Value '"+value+"' is not of type Boolean."); } } } // deprecated ///////////////////////////////////////////////// public Object convertFormValueToModelValue(Object propertyValue) { if (propertyValue==null || "".equals(propertyValue)) { return null; } return Boolean.valueOf(propertyValue.toString());
} public String convertModelValueToFormValue(Object modelValue) { if (modelValue==null) { return null; } if(Boolean.class.isAssignableFrom(modelValue.getClass()) || boolean.class.isAssignableFrom(modelValue.getClass())) { return modelValue.toString(); } throw new ProcessEngineException("Model value is not of type boolean, but of type " + modelValue.getClass().getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\BooleanFormType.java
1
请完成以下Java代码
/* package */final class SwingProcessExecutionListener implements IProcessExecutionListener { public static final IProcessExecutionListener of(final IProcessExecutionListener delegate) { if (delegate instanceof SwingProcessExecutionListener) { return delegate; } return new SwingProcessExecutionListener(delegate); } private final IProcessExecutionListener delegate; private SwingProcessExecutionListener(final IProcessExecutionListener delegate) { super(); this.delegate = delegate; } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(delegate).toString(); } @Override public void lockUI(final ProcessInfo pi) {
invokeInEDT(() -> delegate.lockUI(pi)); } @Override public void unlockUI(final ProcessInfo pi) { invokeInEDT(() -> delegate.unlockUI(pi)); } private final void invokeInEDT(final Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\SwingProcessExecutionListener.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentSalesRepDescriptorFactory { public DocumentSalesRepDescriptor forDocumentRecord(@NonNull final I_C_Invoice invoiceRecord) { final Customer customer = Customer.ofOrNull(BPartnerId.ofRepoIdOrNull(invoiceRecord.getC_BPartner_ID())); final Beneficiary salesRep = Beneficiary.ofOrNull(BPartnerId.ofRepoIdOrNull(invoiceRecord.getC_BPartner_SalesRep_ID())); return new InvoiceRecordSalesRepDescriptor( invoiceRecord, OrgId.ofRepoId(invoiceRecord.getAD_Org_ID()), SOTrx.ofBoolean(invoiceRecord.isSOTrx()), customer, salesRep, invoiceRecord.getSalesPartnerCode(), invoiceRecord.isSalesPartnerRequired()); } public DocumentSalesRepDescriptor forDocumentRecord(@NonNull final I_C_Order orderRecord) { final Customer customer = extractEffectiveBillPartnerId(orderRecord); final Beneficiary salesRep = Beneficiary.ofOrNull(BPartnerId.ofRepoIdOrNull(orderRecord.getC_BPartner_SalesRep_ID()));
return new OrderRecordSalesRepDescriptor( orderRecord, OrgId.ofRepoId(orderRecord.getAD_Org_ID()), SOTrx.ofBoolean(orderRecord.isSOTrx()), customer, salesRep, orderRecord.getSalesPartnerCode(), orderRecord.isSalesPartnerRequired()); } private Customer extractEffectiveBillPartnerId(@NonNull final I_C_Order orderRecord) { return Customer.ofOrNull(BPartnerId.ofRepoIdOrNull(firstGreaterThanZero( orderRecord.getBill_BPartner_ID(), orderRecord.getC_BPartner_ID()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\salesrep\DocumentSalesRepDescriptorFactory.java
2
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
LowCodeUrlsEnum(String url, String title) { this.url = url; this.title = title; } /** * 根据code获取可用的数量 * * @return */ public static List<String> getLowCodeInterceptUrls() { return Arrays.stream(LowCodeUrlsEnum.values()).map(LowCodeUrlsEnum::getUrl).collect(Collectors.toList()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\firewall\interceptor\enums\LowCodeUrlsEnum.java
2
请完成以下Java代码
public String getColumnName() { return m_columnName; } // getColumnName /** * Get Display Type * @return display type */ public int getDisplayType() { return m_displayType; } // getDisplayType /** * Get Alias Name * @return alias column name */ public String getAlias() { return m_alias; } // getAlias /** * Column has Alias. * (i.e. has a key) * @return true if Alias */ public boolean hasAlias() { return !m_columnName.equals(m_alias); } // hasAlias /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_pageBreak; } // isPageBreak /** * String Representation * @return info */ public String toString()
{ StringBuffer sb = new StringBuffer("PrintDataColumn["); sb.append("ID=").append(m_AD_Column_ID) .append("-").append(m_columnName); if (hasAlias()) sb.append("(").append(m_alias).append(")"); sb.append(",DisplayType=").append(m_displayType) .append(",Size=").append(m_columnSize) .append("]"); return sb.toString(); } // toString public void setFormatPattern(String formatPattern) { m_FormatPattern = formatPattern; } public String getFormatPattern() { return m_FormatPattern; } } // PrintDataColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataColumn.java
1
请完成以下Java代码
public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } @JsonIgnore public Collection<EventPayload> getHeaders() { return payload.values() .stream() .filter(EventPayload::isHeader) .collect(Collectors.toList()); } @JsonIgnore public Collection<EventPayload> getCorrelationParameters() { return payload.values() .stream() .filter(EventPayload::isCorrelationParameter) .collect(Collectors.toList()); } public EventPayload getPayload(String name) { return payload.get(name); } @JsonGetter public Collection<EventPayload> getPayload() { return payload.values(); } @JsonSetter public void setPayload(Collection<EventPayload> payload) { for (EventPayload eventPayload : payload) { this.payload.put(eventPayload.getName(), eventPayload); } } public void addHeader(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setHeader(true); } else { payload.put(name, EventPayload.header(name, type));
} } public void addPayload(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setType(type); } else { payload.put(name, new EventPayload(name, type)); } } public void addPayload(EventPayload payload) { this.payload.put(payload.getName(), payload); } public void addCorrelation(String name, String type) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setCorrelationParameter(true); } else { payload.put(name, EventPayload.correlation(name, type)); } } public void addFullPayload(String name) { EventPayload eventPayload = payload.get(name); if (eventPayload != null) { eventPayload.setFullPayload(true); eventPayload.setCorrelationParameter(false); eventPayload.setHeader(false); } else { payload.put(name, EventPayload.fullPayload(name)); } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventModel.java
1
请完成以下Java代码
private void onRecordCopied(@NonNull final PO to, @NonNull final PO from, @NonNull final CopyTemplate template) { if (InterfaceWrapperHelper.isInstanceOf(to, I_C_OrderLine.class) && InterfaceWrapperHelper.isInstanceOf(from, I_C_OrderLine.class)) { final I_C_OrderLine newOrderLine = InterfaceWrapperHelper.create(to, I_C_OrderLine.class); final I_C_OrderLine fromProposalLine = InterfaceWrapperHelper.create(from, I_C_OrderLine.class); newOrderLine.setRef_ProposalLine_ID(fromProposalLine.getC_OrderLine_ID()); orderDAO.save(newOrderLine); createPurchaseOrderAllocRecord(newOrderLine, fromProposalLine); } } private void createPurchaseOrderAllocRecord(final I_C_OrderLine newOrderLine, final I_C_OrderLine fromOrderLine) { final I_C_PurchaseCandidate_Alloc alloc = queryBL.createQueryBuilder(I_C_PurchaseCandidate_Alloc.class) .addEqualsFilter(I_C_PurchaseCandidate_Alloc.COLUMN_C_OrderLinePO_ID, fromOrderLine.getC_OrderLine_ID()) .create().first(); if(alloc == null) { return; } final I_C_PurchaseCandidate_Alloc purchaseCandidateAlloc = InterfaceWrapperHelper.copy() .setFrom(alloc) .copyToNew(I_C_PurchaseCandidate_Alloc.class); purchaseCandidateAlloc.setC_OrderPO_ID(newOrderLine.getC_Order_ID()); purchaseCandidateAlloc.setC_OrderLinePO_ID(newOrderLine.getC_OrderLine_ID()); InterfaceWrapperHelper.save(purchaseCandidateAlloc); markProcessed(PurchaseCandidateId.ofRepoId(purchaseCandidateAlloc.getC_PurchaseCandidate_ID())); } private void markProcessed(final PurchaseCandidateId cPurchaseCandidateId) { final I_C_PurchaseCandidate candidate = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class) .addEqualsFilter(I_C_PurchaseCandidate.COLUMN_C_PurchaseCandidate_ID, cPurchaseCandidateId) .create()
.first(); Check.assumeNotNull(candidate, "Could not find a Purchase candidate for line C_PurchaseCandidate_ID {}", cPurchaseCandidateId); candidate.setProcessed(true); InterfaceWrapperHelper.save(candidate); } private void completePurchaseOrderIfNeeded(final I_C_Order newOrder) { if (completeIt) { documentBL.processEx(newOrder, IDocument.ACTION_Complete, IDocument.STATUS_Completed); } else { newOrder.setDocAction(IDocument.ACTION_Prepare); orderDAO.save(newOrder); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\command\CreatePurchaseOrderFromRequisitionCommand.java
1
请完成以下Java代码
public class SimplifiedToTaiwanChineseDictionary extends BaseChineseDictionary { static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>(); static { long start = System.currentTimeMillis(); String datPath = HanLP.Config.tcDictionaryRoot + "s2tw"; if (!loadDat(datPath, trie)) { TreeMap<String, String> s2t = new TreeMap<String, String>(); TreeMap<String, String> t2tw = new TreeMap<String, String>(); if (!load(s2t, false, HanLP.Config.tcDictionaryRoot + "s2t.txt") || !load(t2tw, false, HanLP.Config.tcDictionaryRoot + "t2tw.txt")) { throw new IllegalArgumentException("简体转台湾繁体词典加载失败"); } combineChain(s2t, t2tw);
trie.build(s2t); saveDat(datPath, trie, s2t.entrySet()); } logger.info("简体转台湾繁体词典加载成功,耗时" + (System.currentTimeMillis() - start) + "ms"); } public static String convertToTraditionalTaiwanChinese(String simplifiedChineseString) { return segLongest(simplifiedChineseString.toCharArray(), trie); } public static String convertToTraditionalTaiwanChinese(char[] simplifiedChinese) { return segLongest(simplifiedChinese, trie); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\SimplifiedToTaiwanChineseDictionary.java
1
请在Spring Boot框架中完成以下Java代码
protected void cleanupForComparison(Device e) { super.cleanupForComparison(e); if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) { e.setCustomerId(null); } } @Override protected Device saveOrUpdate(EntitiesImportCtx ctx, Device device, DeviceExportData exportData, IdProvider idProvider, CompareResult compareResult) { Device savedDevice; if (exportData.getCredentials() != null && ctx.isSaveCredentials()) { exportData.getCredentials().setId(null); exportData.getCredentials().setDeviceId(null); savedDevice = deviceService.saveDeviceWithCredentials(device, exportData.getCredentials()); } else { savedDevice = deviceService.saveDevice(device); } if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) { importCalculatedFields(ctx, savedDevice, exportData, idProvider); } return savedDevice; } @Override protected boolean updateRelatedEntitiesIfUnmodified(EntitiesImportCtx ctx, Device prepared, DeviceExportData exportData, IdProvider idProvider) { boolean updated = super.updateRelatedEntitiesIfUnmodified(ctx, prepared, exportData, idProvider); var credentials = exportData.getCredentials();
if (credentials != null && ctx.isSaveCredentials()) { var existing = credentialsService.findDeviceCredentialsByDeviceId(ctx.getTenantId(), prepared.getId()); credentials.setId(existing.getId()); credentials.setDeviceId(prepared.getId()); if (!existing.equals(credentials)) { credentialsService.updateDeviceCredentials(ctx.getTenantId(), credentials); updated = true; } } return updated; } @Override public EntityType getEntityType() { return EntityType.DEVICE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\DeviceImportService.java
2
请完成以下Java代码
protected void beforeSessionRepositoryFilter(ServletContext servletContext) { } /** * Invoked after the springSessionRepositoryFilter is added. * @param servletContext the {@link ServletContext} */ protected void afterSessionRepositoryFilter(ServletContext servletContext) { } /** * Get the {@link DispatcherType} for the springSessionRepositoryFilter. * @return the {@link DispatcherType} for the filter
*/ protected EnumSet<DispatcherType> getSessionDispatcherTypes() { return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC); } /** * Determine if the springSessionRepositoryFilter should be marked as supporting * asynch. Default is true. * @return true if springSessionRepositoryFilter should be marked as supporting asynch */ protected boolean isAsyncSessionSupported() { return true; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\context\AbstractHttpSessionApplicationInitializer.java
1
请在Spring Boot框架中完成以下Java代码
public Binder getBinder() { Binder binder = this.binder; if (binder == null) { binder = this.contributors.getBinder(this.activationContext); this.binder = binder; } return binder; } @Override public @Nullable ConfigDataResource getParent() { return this.contributor.getResource(); } @Override public ConfigurableBootstrapContext getBootstrapContext() { return this.contributors.getBootstrapContext(); } } private class InactiveSourceChecker implements BindHandler { private final @Nullable ConfigDataActivationContext activationContext; InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) { this.activationContext = activationContext; } @Override public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) { for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) { if (!contributor.isActive(this.activationContext)) { InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name); } } return result; }
} /** * Binder options that can be used with * {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}. */ enum BinderOption { /** * Throw an exception if an inactive contributor contains a bound value. */ FAIL_ON_BIND_TO_INACTIVE_SOURCE } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult create(@RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.create(productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody PmsProductAttributeParam productAttributeParam) { int count = productAttributeService.update(id, productAttributeParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询单个商品属性") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttribute> getItem(@PathVariable Long id) { PmsProductAttribute productAttribute = productAttributeService.getItem(id); return CommonResult.success(productAttribute); }
@ApiOperation("批量删除商品属性") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = productAttributeService.delete(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据商品分类的id获取商品属性及属性分类") @RequestMapping(value = "/attrInfo/{productCategoryId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<ProductAttrInfo>> getAttrInfo(@PathVariable Long productCategoryId) { List<ProductAttrInfo> productAttrInfoList = productAttributeService.getProductAttrInfo(productCategoryId); return CommonResult.success(productAttrInfoList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductAttributeController.java
2
请完成以下Java代码
public class DgsClientUsage { public void sendSingleQuery() { // tag::sendSingleQuery[] HttpGraphQlClient client = HttpGraphQlClient.create(WebClient.create("https://example.org/graphql")); DgsGraphQlClient dgsClient = DgsGraphQlClient.create(client); // <1> List<Book> books = dgsClient.request(BookByIdGraphQLQuery.newRequest().id("42").build()) // <2> .projection(new BooksProjectionRoot<>().id().name()) // <3> .retrieveSync("books") .toEntityList(Book.class); // end::sendSingleQuery[] } public void sendManyQueries() { // tag::sendManyQueries[] HttpGraphQlClient client = HttpGraphQlClient.create(WebClient.create("https://example.org/graphql")); DgsGraphQlClient dgsClient = DgsGraphQlClient.create(client); // <1> ClientGraphQlResponse response = dgsClient
.request(BookByIdGraphQLQuery.newRequest().id("42").build()) // <2> .queryAlias("firstBook") // <3> .projection(new BooksProjectionRoot<>().id().name()) .request(BookByIdGraphQLQuery.newRequest().id("53").build()) // <4> .queryAlias("secondBook") .projection(new BooksProjectionRoot<>().id().name()) .executeSync(); // <5> Book firstBook = response.field("firstBook").toEntity(Book.class); // <6> Book secondBook = response.field("secondBook").toEntity(Book.class); // end::sendManyQueries[] } record Book(Long id, String name) { } }
repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\dgsgraphqlclient\DgsClientUsage.java
1
请完成以下Java代码
public void setM_Product_Category_Parent(org.compiere.model.I_M_Product_Category M_Product_Category_Parent) { set_ValueFromPO(COLUMNNAME_M_Product_Category_Parent_ID, org.compiere.model.I_M_Product_Category.class, M_Product_Category_Parent); } /** Set Parent Product Category. @param M_Product_Category_Parent_ID Parent Product Category */ @Override public void setM_Product_Category_Parent_ID (int M_Product_Category_Parent_ID) { if (M_Product_Category_Parent_ID < 1) set_Value (COLUMNNAME_M_Product_Category_Parent_ID, null); else set_Value (COLUMNNAME_M_Product_Category_Parent_ID, Integer.valueOf(M_Product_Category_Parent_ID)); } /** Get Parent Product Category. @return Parent Product Category */ @Override public int getM_Product_Category_Parent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** * MRP_Exclude AD_Reference_ID=319 * Reference name: _YesNo */ public static final int MRP_EXCLUDE_AD_Reference_ID=319; /** Yes = Y */ public static final String MRP_EXCLUDE_Yes = "Y"; /** No = N */ public static final String MRP_EXCLUDE_No = "N"; /** Set MRP ausschliessen. @param MRP_Exclude MRP ausschliessen */ @Override public void setMRP_Exclude (java.lang.String MRP_Exclude) { set_Value (COLUMNNAME_MRP_Exclude, MRP_Exclude); } /** Get MRP ausschliessen. @return MRP ausschliessen */ @Override public java.lang.String getMRP_Exclude () { return (java.lang.String)get_Value(COLUMNNAME_MRP_Exclude); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set DB1 %. @param PlannedMargin Project's planned margin as a percentage */
@Override public void setPlannedMargin (java.math.BigDecimal PlannedMargin) { set_Value (COLUMNNAME_PlannedMargin, PlannedMargin); } /** Get DB1 %. @return Project's planned margin as a percentage */ @Override public java.math.BigDecimal getPlannedMargin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PlannedMargin); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category.java
1
请完成以下Java代码
public BigDecimal getApprovalAmt() { return getGrandTotal(); } public void setRMA(final MRMA rma) { final MInvoice originalInvoice = rma.getOriginalInvoice(); if (originalInvoice == null) { throw new AdempiereException("Not invoiced - RMA: " + rma.getDocumentNo()); } setM_RMA_ID(rma.getM_RMA_ID()); setAD_Org_ID(rma.getAD_Org_ID()); setDescription(rma.getDescription()); InvoiceDocumentLocationAdapterFactory .locationAdapter(this) .setFrom(originalInvoice); setSalesRep_ID(rma.getSalesRep_ID()); setGrandTotal(rma.getAmt()); setOpenAmt(rma.getAmt()); setIsSOTrx(rma.isSOTrx()); setTotalLines(rma.getAmt()); setC_Currency_ID(originalInvoice.getC_Currency_ID()); setIsTaxIncluded(originalInvoice.isTaxIncluded()); setM_PriceList_ID(originalInvoice.getM_PriceList_ID()); setC_Project_ID(originalInvoice.getC_Project_ID()); setC_Activity_ID(originalInvoice.getC_Activity_ID()); setC_Campaign_ID(originalInvoice.getC_Campaign_ID()); setUser1_ID(originalInvoice.getUser1_ID());
setUser2_ID(originalInvoice.getUser2_ID()); } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE * @deprecated Please use {@link IInvoiceBL#isComplete(I_C_Invoice)} */ @Deprecated public boolean isComplete() { return Services.get(IInvoiceBL.class).isComplete(this); } // isComplete } // MInvoice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInvoice.java
1
请在Spring Boot框架中完成以下Java代码
public class ResourceServerConfig extends ResourceServerConfigurerAdapter { private final ResourceServerProperties sso; @Autowired public ResourceServerConfig(ResourceServerProperties sso) { this.sso = sso; } @Bean @ConfigurationProperties(prefix = "security.oauth2.client") public ClientCredentialsResourceDetails clientCredentialsResourceDetails() { return new ClientCredentialsResourceDetails(); } @Bean public RequestInterceptor oauth2FeignRequestInterceptor(){ return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails()); }
@Bean public OAuth2RestTemplate clientCredentialsRestTemplate() { return new OAuth2RestTemplate(clientCredentialsResourceDetails()); } @Bean public ResourceServerTokenServices tokenServices() { return new CustomUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId()); } @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/" , "/demo").permitAll() .anyRequest().authenticated(); } }
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\config\ResourceServerConfig.java
2
请完成以下Java代码
public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours) { set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours); } @Override public String getKeepAliveTimeHours() { return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours); } /** * NotificationType AD_Reference_ID=540643 * Reference name: _NotificationType */ public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643; /** Async Batch Processed = ABP */ public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP"; /** Workpackage Processed = WPP */ public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP"; @Override public void setNotificationType (final @Nullable String NotificationType) {
set_Value (COLUMNNAME_NotificationType, NotificationType); } @Override public String getNotificationType() { return get_ValueAsString(COLUMNNAME_NotificationType); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java
1
请完成以下Java代码
public void executeHandler(ModificationBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { ModificationBuilderImpl executionBuilder = (ModificationBuilderImpl) commandContext.getProcessEngineConfiguration() .getRuntimeService() .createModification(batchConfiguration.getProcessDefinitionId()) .processInstanceIds(batchConfiguration.getIds()); executionBuilder.setInstructions(batchConfiguration.getInstructions()); if (batchConfiguration.isSkipCustomListeners()) { executionBuilder.skipCustomListeners(); } if (batchConfiguration.isSkipIoMappings()) { executionBuilder.skipIoMappings(); } executionBuilder.execute(false); } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected ModificationBatchConfiguration createJobConfiguration(ModificationBatchConfiguration configuration, List<String> processIdsForJob) { return new ModificationBatchConfiguration( processIdsForJob, configuration.getProcessDefinitionId(), configuration.getInstructions(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings()
); } @Override protected ModificationBatchConfigurationJsonConverter getJsonConverterInstance() { return ModificationBatchConfigurationJsonConverter.INSTANCE; } protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) { return commandContext.getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBatchJobHandler.java
1
请完成以下Java代码
public List<Customer> findAll() { return em.createQuery("select c from Customer c", Customer.class).getResultList(); } /* * (non-Javadoc) * @see example.springdata.jpa.showcase.before.CustomerService#findAll(int, int) */ @Override public List<Customer> findAll(int page, int pageSize) { var query = em.createQuery("select c from Customer c", Customer.class); query.setFirstResult(page * pageSize); query.setMaxResults(pageSize); return query.getResultList(); } /* * (non-Javadoc) * @see example.springdata.jpa.showcase.before.CustomerService#save(example.springdata.jpa.showcase.core.Customer) */ @Override @Transactional public Customer save(Customer customer) { // Is new? if (customer.getId() == null) { em.persist(customer); return customer; } else { return em.merge(customer); }
} /* * (non-Javadoc) * @see example.springdata.jpa.showcase.before.CustomerService#findByLastname(java.lang.String, int, int) */ @Override public List<Customer> findByLastname(String lastname, int page, int pageSize) { var query = em.createQuery("select c from Customer c where c.lastname = ?1", Customer.class); query.setParameter(1, lastname); query.setFirstResult(page * pageSize); query.setMaxResults(pageSize); return query.getResultList(); } }
repos\spring-data-examples-main\jpa\showcase\src\main\java\example\springdata\jpa\showcase\before\CustomerServiceImpl.java
1
请完成以下Java代码
public List<LoggerConfiguration> getLoggerConfigurations() { throw new UnsupportedOperationException("Unable to get logger configurations"); } /** * Returns the current configuration for a {@link LoggingSystem}'s logger. * @param loggerName the name of the logger * @return the current configuration * @since 1.5.0 */ public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) { throw new UnsupportedOperationException("Unable to get logger configuration"); } /** * Detect and return the logging system in use. Supports Logback and Java Logging. * @param classLoader the classloader * @return the logging system */ public static LoggingSystem get(ClassLoader classLoader) { String loggingSystemClassName = System.getProperty(SYSTEM_PROPERTY); if (StringUtils.hasLength(loggingSystemClassName)) { if (NONE.equals(loggingSystemClassName)) { return new NoOpLoggingSystem(); } return get(classLoader, loggingSystemClassName); } LoggingSystem loggingSystem = SYSTEM_FACTORY.getLoggingSystem(classLoader); Assert.state(loggingSystem != null, "No suitable logging system located"); return loggingSystem; } private static LoggingSystem get(ClassLoader classLoader, String loggingSystemClassName) { try { Class<?> systemClass = ClassUtils.forName(loggingSystemClassName, classLoader); Constructor<?> constructor = systemClass.getDeclaredConstructor(ClassLoader.class); constructor.setAccessible(true); return (LoggingSystem) constructor.newInstance(classLoader); } catch (Exception ex) { throw new IllegalStateException(ex); } } /** * {@link LoggingSystem} that does nothing.
*/ static class NoOpLoggingSystem extends LoggingSystem { @Override public void beforeInitialize() { } @Override public void setLogLevel(@Nullable String loggerName, @Nullable LogLevel level) { } @Override public List<LoggerConfiguration> getLoggerConfigurations() { return Collections.emptyList(); } @Override public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) { return null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggingSystem.java
1
请完成以下Java代码
protected boolean isAggregatedHU(final I_M_HU hu) { return handlingUnitsBL.isAggregateHU(hu); } @Override protected int getAggregatedHUsCount(final I_M_HU hu) { final I_M_HU_Item parentHUItem = hu.getM_HU_Item_Parent(); if (parentHUItem == null) { // shall not happen return 0; } return parentHUItem.getQty().intValueExact(); } @Override protected boolean isVirtualPI(final I_M_HU huObj) {
return handlingUnitsBL.isVirtual(huObj); } IHUIteratorListener toHUIteratorListener() { return new HUIteratorListenerAdapter() { @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(IncludedHUsCounter.this).toString(); } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return IncludedHUsCounter.this.accept(hu.getValue()); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\IncludedHUsCounter.java
1
请完成以下Java代码
public boolean executeMultipleStatements() throws SQLException { String sql = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');" + "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');"; try (Statement statement = connection.createStatement()) { statement.execute(sql); return true; } } public int[] executeBatchProcessing() throws SQLException { try (Statement statement = connection.createStatement()) { connection.setAutoCommit(false); statement.addBatch("INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com')"); statement.addBatch("INSERT INTO users (name, email) VALUES ('Diana', 'diana@example.com')"); int[] updateCounts = statement.executeBatch(); connection.commit(); return updateCounts; } } public boolean callStoredProcedure() throws SQLException { try (CallableStatement callableStatement = connection.prepareCall("{CALL InsertMultipleUsers()}")) { callableStatement.execute(); return true; } } public List<User> executeMultipleSelectStatements() throws SQLException { String sql = "SELECT * FROM users WHERE email = 'alice@example.com';" + "SELECT * FROM users WHERE email = 'bob@example.com';"; List<User> users = new ArrayList<>(); try (Statement statement = connection.createStatement()) {
statement.execute(sql); // Here we execute the multiple queries do { try (ResultSet resultSet = statement.getResultSet()) { while (resultSet != null && resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String email = resultSet.getString("email"); users.add(new User(id, name, email)); } } } while (statement.getMoreResults()); } return users; } }
repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\sql\MultipleSQLExecution.java
1
请完成以下Java代码
public int getTimes() { return times; } public boolean isRepeat() { return isRepeat; } private Date getDateAfterRepeat(Date date) { // use date without the current offset for due date calculation to get the // next due date as it would be without any modifications, later add offset Date dateWithoutOffset = new Date(date.getTime() - repeatOffset); if (start != null) { Date cur = start; for (int i = 0; i < times && !cur.after(dateWithoutOffset); i++) { cur = add(cur, period); } if (cur.before(dateWithoutOffset)) { return null; } // add offset to calculated due date return repeatOffset == 0L ? cur : new Date(cur.getTime() + repeatOffset); } Date cur = add(end, period.negate()); Date next = end; for (int i=0;i<times && cur.after(date);i++) { next = cur; cur = add(cur, period.negate()); } return next.before(date) ? null : next; } private Date add(Date date, Duration duration) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); duration.addTo(calendar);
return calendar.getTime(); } private Duration parsePeriod(String period) { if (period.matches(PnW_PATTERN)) { return parsePnWDuration(period); } return datatypeFactory.newDuration(period); } private Duration parsePnWDuration(String period) { String weeks = period.replaceAll("\\D", ""); long duration = Long.parseLong(weeks) * MS_PER_WEEK; return datatypeFactory.newDuration(duration); } private boolean isDuration(String time) { return time.startsWith("P"); } public void setRepeatOffset(long repeatOffset) { this.repeatOffset = repeatOffset; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\DurationHelper.java
1
请完成以下Java代码
public void setC_Flatrate_DataEntry_IncludedT (final @Nullable java.lang.String C_Flatrate_DataEntry_IncludedT) { set_Value (COLUMNNAME_C_Flatrate_DataEntry_IncludedT, C_Flatrate_DataEntry_IncludedT); } @Override public java.lang.String getC_Flatrate_DataEntry_IncludedT() { return get_ValueAsString(COLUMNNAME_C_Flatrate_DataEntry_IncludedT); } @Override public void setC_Flatrate_Data_ID (final int C_Flatrate_Data_ID) { if (C_Flatrate_Data_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, C_Flatrate_Data_ID); } @Override public int getC_Flatrate_Data_ID() {
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Data_ID); } @Override public void setHasContracts (final boolean HasContracts) { set_Value (COLUMNNAME_HasContracts, HasContracts); } @Override public boolean isHasContracts() { return get_ValueAsBoolean(COLUMNNAME_HasContracts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Data.java
1
请完成以下Java代码
public class VertragsdatenAbfragenResponse { @XmlElement(name = "return", namespace = "", required = true) protected VertragsdatenAntwort _return; /** * Gets the value of the return property. * * @return * possible object is * {@link VertragsdatenAntwort } * */ public VertragsdatenAntwort getReturn() { return _return;
} /** * Sets the value of the return property. * * @param value * allowed object is * {@link VertragsdatenAntwort } * */ public void setReturn(VertragsdatenAntwort value) { this._return = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenAbfragenResponse.java
1
请完成以下Java代码
public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { byteArrayField.deleteByteArrayValue(); Context .getCommandContext() .getDbEntityManager() .delete(this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java
1
请完成以下Java代码
public void setQty(final BigDecimal qty) { forecastLine.setQty(qty); final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID()); final BigDecimal qtyCalculated = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty); forecastLine.setQtyCalculated(qtyCalculated); } @Override public BigDecimal getQty() { return forecastLine.getQty(); } @Override public int getM_HU_PI_Item_Product_ID() { final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID(); if (forecastLine_PIItemProductId > 0) { return forecastLine_PIItemProductId; } return -1; } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public BigDecimal getQtyTU() { return forecastLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { forecastLine.setQtyEnteredTU(qtyPacks); }
@Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java
1
请在Spring Boot框架中完成以下Java代码
public class RoleMenuReq extends AbsReq { /** 角色ID */ private String roleId; /**菜单ID列表*/ private List<String> menuIdList; public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; }
public List<String> getMenuIdList() { return menuIdList; } public void setMenuIdList(List<String> menuIdList) { this.menuIdList = menuIdList; } @Override public String toString() { return "RoleMenuReq{" + "roleId='" + roleId + '\'' + ", menuIdList=" + menuIdList + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\RoleMenuReq.java
2
请完成以下Java代码
public void setBackground (Color bg) { if (bg.equals(getBackground())) return; super.setBackground(bg); } // setBackground /** * Set Editor to value * @param value value of the editor */ @Override public void setValue (Object value) { if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value
* @return current value */ @Override public Object getValue() { return new String(super.getPassword()); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return new String(super.getPassword()); } // getDisplay }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPassword.java
1
请完成以下Java代码
public int getCarrier_Goods_Type_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_Goods_Type_ID); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); }
@Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Goods_Type.java
1
请完成以下Java代码
public List<de.metas.inoutcandidate.model.I_M_ReceiptSchedule> createOrUpdateReceiptSchedules(final Object model_NOTUSED, final List<de.metas.inoutcandidate.model.I_M_ReceiptSchedule> previousSchedules) { // Check if we really have something to customize if (previousSchedules == null || previousSchedules.isEmpty()) { return Collections.emptyList(); } for (final de.metas.inoutcandidate.model.I_M_ReceiptSchedule receiptSchedule : previousSchedules) { final I_M_ReceiptSchedule receiptScheduleHU = InterfaceWrapperHelper.create(receiptSchedule, I_M_ReceiptSchedule.class); updateFromOrderline(receiptScheduleHU); } return Collections.emptyList(); } @Override public void updateReceiptSchedules(Object model) { // Does nothing because "updateFromOrderline" updates only if the receipt schedule was newly created anyways. // This method is supposed to update existing receipt schedules, so there is nothing to do for this case. } /** * Copy HU relevant informations from Order Line to given <code>receiptSchedule</code>. * * This method it is also creating standard planning HUs (see {@link #generatePlanningHUs(de.metas.handlingunits.model.I_M_ReceiptSchedule)}). * * @param receiptSchedule */ private void updateFromOrderline(final I_M_ReceiptSchedule receiptSchedule) { // Don't touch processed receipt schedules if (receiptSchedule.isProcessed()) { return; } // Update receipt schedules only if they were just created. // We do this because we want to perform this update only ONCE and not each time an receipt schedule or an order line gets updated (08168) if (!InterfaceWrapperHelper.isJustCreated(receiptSchedule))
{ return; } final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(receiptSchedule.getC_OrderLine(), I_C_OrderLine.class); final int itemProductID; final String packDescription; final BigDecimal qtyItemCapacity; if (orderLine == null) { itemProductID = -1; packDescription = null; qtyItemCapacity = null; } else { itemProductID = orderLine.getM_HU_PI_Item_Product_ID(); packDescription = orderLine.getPackDescription(); qtyItemCapacity = orderLine.getQtyItemCapacity(); } receiptSchedule.setM_HU_PI_Item_Product_ID(itemProductID); receiptSchedule.setPackDescription(packDescription); receiptSchedule.setQtyItemCapacity(qtyItemCapacity); // i.e. Qty CUs/TU // receiptSchedule.setIsPackingMaterial(isPackingMaterial); // virtual column InterfaceWrapperHelper.save(receiptSchedule); } @Override public void inactivateReceiptSchedules(final Object model) { // NOTE: this producer is not creating any receipt schedules, it's just customizing the existing one. // So the responsibility of deactivating receipt schedules is going to it's creator. } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptScheduleProducer.java
1