instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static PlainAttributeSetInstanceAware forProductIdAndAttributeSetInstanceId( @NonNull final ProductId productId, @Nullable final AttributeSetInstanceId attributeSetInstanceId) { return new PlainAttributeSetInstanceAware(productId, AttributeSetInstanceId.nullToNone(attributeSetInstanceId)); } private PlainAttributeSetInstanceAware( @Nullable final ProductId productId, @NonNull final AttributeSetInstanceId attributeSetInstanceId) { this.productId = productId; this.attributeSetInstanceId = attributeSetInstanceId; } @Override public I_M_Product getM_Product() { return Services.get(IProductDAO.class).getById(productId); } @Override public int getM_Product_ID() { return ProductId.toRepoId(productId); } @Override public I_M_AttributeSetInstance getM_AttributeSetInstance() {
return Services.get(IAttributeSetInstanceBL.class).getById(attributeSetInstanceId); } @Override public int getM_AttributeSetInstance_ID() { return attributeSetInstanceId.getRepoId(); } @Override public void setM_AttributeSetInstance(I_M_AttributeSetInstance asi) { throw new UnsupportedOperationException("Changing the M_AttributeSetInstance is not supported for " + PlainAttributeSetInstanceAware.class.getName()); } @Override public void setM_AttributeSetInstance_ID(int M_AttributeSetInstance_ID) { throw new UnsupportedOperationException("Changing the M_AttributeSetInstance_ID is not supported for " + PlainAttributeSetInstanceAware.class.getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\PlainAttributeSetInstanceAware.java
1
请在Spring Boot框架中完成以下Java代码
public Object getTown() { return town; } /** * Sets the value of the town property. * * @param value * allowed object is * {@link Object } * */ public void setTown(Object value) { this.town = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link Object } * */ public Object getCountry() { return country;
} /** * Sets the value of the country property. * * @param value * allowed object is * {@link Object } * */ public void setCountry(Object value) { this.country = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ShipFromType.java
2
请在Spring Boot框架中完成以下Java代码
public class InvoiceToAllocate { // invoiceId or preparyOrderId shall non null @Nullable InvoiceId invoiceId; @Nullable OrderId prepayOrderId; @NonNull ClientAndOrgId clientAndOrgId; @NonNull String documentNo; @NonNull BPartnerId bpartnerId; @NonNull String bpartnerName; @NonNull LocalDate dateInvoiced; @NonNull LocalDate dateAcct; @NonNull CurrencyCode documentCurrencyCode; /** * Date used to calculate the currency conversion and discount */ @NonNull ZonedDateTime evaluationDate; @NonNull InvoiceAmtMultiplier multiplier; @NonNull
Amount grandTotal; @NonNull Amount openAmountConverted; @NonNull Amount discountAmountConverted; @NonNull DocTypeId docTypeId; @NonNull InvoiceDocBaseType docBaseType; @Nullable String poReference; @Nullable CurrencyConversionTypeId currencyConversionTypeId; public boolean grantDiscount(@NonNull final Amount amountToAllocate) { return openAmountConverted.subtract(discountAmountConverted).equals(amountToAllocate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\InvoiceToAllocate.java
2
请完成以下Java代码
public void setPriceStdFixed (java.math.BigDecimal PriceStdFixed) { set_Value (COLUMNNAME_PriceStdFixed, PriceStdFixed); } /** Get Festpreis. @return Festpreis, ohne ggf. zusätzliche Rabatte */ @Override public java.math.BigDecimal getPriceStdFixed () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStdFixed); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Preisaufschlag. @param PricingSystemSurchargeAmt Aufschlag auf den Preis, der aus dem Preissystem resultieren würde */ @Override public void setPricingSystemSurchargeAmt (java.math.BigDecimal PricingSystemSurchargeAmt) { set_Value (COLUMNNAME_PricingSystemSurchargeAmt, PricingSystemSurchargeAmt); } /** Get Preisaufschlag. @return Aufschlag auf den Preis, der aus dem Preissystem resultieren würde */ @Override public java.math.BigDecimal getPricingSystemSurchargeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricingSystemSurchargeAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) {
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Produktschlüssel. @param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_DiscountSchema.java
1
请完成以下Java代码
public void setM_Product_SupplierApproval_Norm_ID (final int M_Product_SupplierApproval_Norm_ID) { if (M_Product_SupplierApproval_Norm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, M_Product_SupplierApproval_Norm_ID); } @Override public int getM_Product_SupplierApproval_Norm_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_SupplierApproval_Norm_ID); } /** * SupplierApproval_Norm AD_Reference_ID=541363 * Reference name: SupplierApproval_Norm */ public static final int SUPPLIERAPPROVAL_NORM_AD_Reference_ID=541363; /** ISO 9100 Luftfahrt = ISO9100 */
public static final String SUPPLIERAPPROVAL_NORM_ISO9100Luftfahrt = "ISO9100"; /** TS 16949 = TS16949 */ public static final String SUPPLIERAPPROVAL_NORM_TS16949 = "TS16949"; @Override public void setSupplierApproval_Norm (final java.lang.String SupplierApproval_Norm) { set_Value (COLUMNNAME_SupplierApproval_Norm, SupplierApproval_Norm); } @Override public java.lang.String getSupplierApproval_Norm() { return get_ValueAsString(COLUMNNAME_SupplierApproval_Norm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_SupplierApproval_Norm.java
1
请完成以下Java代码
public BigDecimal getQtyTUsTotal() { if (qtyTUsTotal == null) { return Quantity.QTY_INFINITE; } return qtyTUsTotal; } public Builder setStandardQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { this.qtyCUsPerTU = qtyCUsPerTU; return this; } public BigDecimal getStandardQtyCUsPerTU() { return qtyCUsPerTU; } public Builder setStandardQtyTUsPerLU(final BigDecimal qtyTUsPerLU) { this.qtyTUsPerLU = qtyTUsPerLU; return this; } public Builder setStandardQtyTUsPerLU(final int qtyTUsPerLU)
{ return setStandardQtyTUsPerLU(BigDecimal.valueOf(qtyTUsPerLU)); } public BigDecimal getStandardQtyTUsPerLU() { return qtyTUsPerLU; } public Builder setStandardQtysAsInfinite() { setStandardQtyCUsPerTU(BigDecimal.ZERO); setStandardQtyTUsPerLU(BigDecimal.ZERO); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TotalQtyCUBreakdownCalculator.java
1
请完成以下Java代码
protected void addItemToGroup(final I_C_OrderLine purchaseOrderLine, final I_C_OrderLine salesOrderLine) { final BigDecimal oldQtyEntered = purchaseOrderLine.getQtyEntered(); // the purchase order line's UOM is the internal stocking UOM, so we don't need to convert from qtyOrdered/qtyReserved to qtyEntered. final BigDecimal purchaseQty; if (I_C_OrderLine.COLUMNNAME_QtyOrdered.equals(purchaseQtySource)) { purchaseQty = PurchaseTypeEnum.MEDIATED.equals(purchaseType) ? salesOrderLine.getQtyOrdered().subtract(salesOrderLine.getQtyDelivered()) : salesOrderLine.getQtyOrdered(); } else if (I_C_OrderLine.COLUMNNAME_QtyReserved.equals(purchaseQtySource)) { purchaseQty = salesOrderLine.getQtyReserved(); } else { Check.errorIf(true, "Unsupported purchaseQtySource={}", purchaseQtySource); purchaseQty = null; // won't be reached } final BigDecimal newQtyEntered = oldQtyEntered.add(purchaseQty); // setting QtyEntered, because qtyOrdered will be set from qtyEntered by a model interceptor purchaseOrderLine.setQtyEntered(newQtyEntered); purchaseOrderLine2saleOrderLines.get(purchaseOrderLine).add(salesOrderLine); // no NPE, because the list for this key was added in createGroup() } I_C_Order getPurchaseOrder() { return purchaseOrder; }
@Override public String toString() { return ObjectUtils.toString(this); } @Nullable private static OrderId extractSingleOrderIdOrNull(final List<I_C_OrderLine> orderLines) { return CollectionUtils.extractSingleElementOrDefault( orderLines, orderLine -> OrderId.ofRepoId(orderLine.getC_Order_ID()), null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\po_from_so\impl\CreatePOLineFromSOLinesAggregator.java
1
请完成以下Java代码
public boolean remove(Object o) { return map.remove(o) == PRESENT; } @Override public void clear() { map.clear(); } @SuppressWarnings("unchecked") @Override public Object clone() { try { final IdentityHashSet<E> newSet = (IdentityHashSet<E>)super.clone(); newSet.map = (IdentityHashMap<E, Object>)map.clone(); return newSet; } catch (CloneNotSupportedException e) { throw new InternalError(); } } // -- Serializable --// private synchronized void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out size s.writeInt(map.size()); // Write out all elements in the proper order. for (Iterator<E> i = map.keySet().iterator(); i.hasNext();) s.writeObject(i.next()); } private synchronized void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic s.defaultReadObject(); // Read in size (number of Mappings) int size = s.readInt(); // Read in IdentityHashMap capacity and load factor and create backing IdentityHashMap map = new IdentityHashMap<E, Object>((size * 4) / 3); // Allow for 33% growth (i.e., capacity is >= 2* size()). // Read in all elements in the proper order. for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") final E e = (E)s.readObject(); map.put(e, PRESENT); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IdentityHashSet.java
1
请在Spring Boot框架中完成以下Java代码
public String getCustomerUid() { return customerUid; } /** * Sets the value of the customerUid property. * * @param value * allowed object is * {@link String } * */ public void setCustomerUid(String value) { this.customerUid = value; } /** * Gets the value of the authToken property. * * @return * possible object is * {@link String } * */ public String getAuthToken() { return authToken; } /** * Sets the value of the authToken property. * * @param value * allowed object is * {@link String } * */ public void setAuthToken(String value) { this.authToken = value; } /**
* Gets the value of the depot property. * * @return * possible object is * {@link String } * */ public String getDepot() { return depot; } /** * Sets the value of the depot property. * * @param value * allowed object is * {@link String } * */ public void setDepot(String value) { this.depot = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\Login.java
2
请完成以下Java代码
public int deleteAllCalculatedFieldsByEntityId(TenantId tenantId, EntityId entityId) { log.trace("Executing deleteAllCalculatedFieldsByEntityId, tenantId [{}], entityId [{}]", tenantId, entityId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); validateId(entityId.getId(), id -> INCORRECT_ENTITY_ID + id); List<CalculatedField> calculatedFields = calculatedFieldDao.removeAllByEntityId(tenantId, entityId); return calculatedFields.size(); } @Override public boolean referencedInAnyCalculatedField(TenantId tenantId, EntityId referencedEntityId) { return calculatedFieldDao.findAllByTenantId(tenantId).stream() .filter(calculatedField -> !referencedEntityId.equals(calculatedField.getEntityId())) .map(CalculatedField::getConfiguration) .map(CalculatedFieldConfiguration::getReferencedEntities) .anyMatch(referencedEntities -> referencedEntities.contains(referencedEntityId)); } @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findById(tenantId, new CalculatedFieldId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(calculatedFieldDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.CALCULATED_FIELD; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\cf\BaseCalculatedFieldService.java
1
请完成以下Java代码
class InnerClass implements HelloWorld { @Override public String greet(String name) { return "Inner class within an interface"; } } // Nested interface within an interfaces interface HelloSomeone { public String greet(String name); } // Enum within an interface enum Directon { NORTH, SOUTH, EAST, WEST; } } enum Level {
LOW, MEDIUM, HIGH; } enum Foods { DRINKS, EATS; // Enum within Enum enum DRINKS { APPLE_JUICE, COLA; } enum EATS { POTATO, RICE; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\classfile\Outer.java
1
请在Spring Boot框架中完成以下Java代码
public StatusUpdateTrigger statusUpdateTrigger(StatusUpdater statusUpdater, Publisher<InstanceEvent> events) { AdminServerProperties.MonitorProperties monitorProperties = this.adminServerProperties.getMonitor(); Duration defaultTimeout = monitorProperties.getDefaultTimeout(); Duration statusInterval = monitorProperties.getStatusInterval(); if (defaultTimeout.compareTo(statusInterval) > 0) { log.warn( "Default timeout ({}) is larger than status interval ({}), hence status interval will be used as timeout.", defaultTimeout, statusInterval); } return new StatusUpdateTrigger(statusUpdater, events, monitorProperties.getStatusInterval(), monitorProperties.getStatusLifetime(), monitorProperties.getStatusMaxBackoff()); } @Bean @ConditionalOnMissingBean public EndpointDetector endpointDetector(InstanceRepository instanceRepository, InstanceWebClient.Builder instanceWebClientBuilder) { InstanceWebClient instanceWebClient = instanceWebClientBuilder.build(); ChainingStrategy strategy = new ChainingStrategy( new QueryIndexEndpointStrategy(instanceWebClient, new ApiMediaTypeHandler()), new ProbeEndpointsStrategy(instanceWebClient, this.adminServerProperties.getProbedEndpoints())); return new EndpointDetector(instanceRepository, strategy); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public EndpointDetectionTrigger endpointDetectionTrigger(EndpointDetector endpointDetector, Publisher<InstanceEvent> events) { return new EndpointDetectionTrigger(endpointDetector, events); } @Bean
@ConditionalOnMissingBean public InfoUpdater infoUpdater(InstanceRepository instanceRepository, InstanceWebClient.Builder instanceWebClientBuilder) { return new InfoUpdater(instanceRepository, instanceWebClientBuilder.build(), new ApiMediaTypeHandler()); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public InfoUpdateTrigger infoUpdateTrigger(InfoUpdater infoUpdater, Publisher<InstanceEvent> events) { return new InfoUpdateTrigger(infoUpdater, events, this.adminServerProperties.getMonitor().getInfoInterval(), this.adminServerProperties.getMonitor().getInfoLifetime(), this.adminServerProperties.getMonitor().getInfoMaxBackoff()); } @Bean @ConditionalOnMissingBean(InstanceEventStore.class) public InMemoryEventStore eventStore() { return new InMemoryEventStore(); } @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean(InstanceRepository.class) public SnapshottingInstanceRepository instanceRepository(InstanceEventStore eventStore) { return new SnapshottingInstanceRepository(eventStore); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerAutoConfiguration.java
2
请完成以下Java代码
public static boolean checkIntersect(Geometry rectangle1, Geometry rectangle2) { boolean intersect = rectangle1.intersects(rectangle2); Geometry overlap = rectangle1.intersection(rectangle2); log.info("Do both rectangle intersect? {}", intersect); log.info("Overlapping Area: {}", overlap); return intersect; } public static Geometry getBuffer(Geometry point, int intBuffer) { Geometry buffer = point.buffer(intBuffer); log.info("Buffer Geometry: {}", buffer); return buffer; } public static double getDistance(Geometry point1, Geometry point2) { double distance = point1.distance(point2); log.info("Distance: {}",distance); return distance; }
public static Geometry getUnion(Geometry geometry1, Geometry geometry2) { Geometry union = geometry1.union(geometry2); log.info("Union Result: {}", union); return union; } public static Geometry getDifference(Geometry base, Geometry cut) { Geometry result = base.difference(cut); log.info("Resulting Geometry: {}", result); return result; } public static Geometry validateAndRepair(Geometry invalidGeo) throws Exception { boolean valid = invalidGeo.isValid(); log.info("Is valid Geometry value? {}", valid); Geometry repaired = invalidGeo.buffer(0); log.info("Repaired Geometry: {}", repaired); return repaired; } }
repos\tutorials-master\jts\src\main\java\com\baeldung\jts\operations\JTSOperationUtils.java
1
请完成以下Java代码
public static IvParameterSpec getIV() { SecureRandom secureRandom = new SecureRandom(); byte[] iv = new byte[128 / 8]; byte[] nonce = new byte[96 / 8]; secureRandom.nextBytes(nonce); System.arraycopy(nonce, 0, iv, 0, nonce.length); return new IvParameterSpec(nonce); } public static IvParameterSpec getIVSecureRandom(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException { SecureRandom random = SecureRandom.getInstanceStrong(); byte[] iv = new byte[Cipher.getInstance(algorithm).getBlockSize()]; random.nextBytes(iv); return new IvParameterSpec(iv); } public static IvParameterSpec getIVInternal(Cipher cipher) throws InvalidParameterSpecException { AlgorithmParameters params = cipher.getParameters(); byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); return new IvParameterSpec(iv); } public static byte[] getRandomIVWithSize(int size) { byte[] nonce = new byte[size]; new SecureRandom().nextBytes(nonce); return nonce;
} public static byte[] encryptWithPadding(SecretKey key, byte[] bytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cipherTextBytes = cipher.doFinal(bytes); return cipherTextBytes; } public static byte[] decryptWithPadding(SecretKey key, byte[] cipherTextBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(cipherTextBytes); } }
repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\utils\CryptoUtils.java
1
请完成以下Java代码
public class CaseTaskItemHandler extends ProcessOrCaseTaskItemHandler { protected CmmnActivityBehavior getActivityBehavior() { return new CaseTaskActivityBehavior(); } protected CaseTask getDefinition(CmmnElement element) { return (CaseTask) super.getDefinition(element); } protected String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { CaseTask definition = getDefinition(element); return definition.getCase(); } protected String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) {
CaseTask definition = getDefinition(element); return definition.getCamundaCaseBinding(); } protected String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { CaseTask definition = getDefinition(element); return definition.getCamundaCaseVersion(); } protected String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context) { CaseTask definition = getDefinition(element); return definition.getCamundaCaseTenantId(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CaseTaskItemHandler.java
1
请完成以下Java代码
public final void initialize(final ModelValidationEngine engine, final MClient client) { if (client != null) { ad_Client_ID = client.getAD_Client_ID(); } engine.addModelChange(I_C_Payment.Table_Name, this); } @Override public String modelChange(final PO po, final int type) throws Exception { if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE) { final MPayment payment = (MPayment)po; if (po.is_ValueChanged(I_C_Payment.COLUMNNAME_CreditCardNumber) || po.is_ValueChanged(I_C_Payment.COLUMNNAME_CreditCardVV)) { final OrgId orgId = OrgId.ofRepoId(payment.getAD_Org_ID()); final OrgInfo orgInfo = Services.get(IOrgDAO.class).getOrgInfoById(orgId); final StoreCreditCardNumberMode ccStoreMode = orgInfo.getStoreCreditCardNumberMode(); if (StoreCreditCardNumberMode.DONT_STORE.equals(ccStoreMode)) { payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardNumber, payment.getCreditCardNumber().replaceAll(" ", "").replaceAll(".", "*")); payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardVV, payment.getCreditCardVV().replaceAll(" ", "").replaceAll(".", "*")); } else if (StoreCreditCardNumberMode.LAST_4_DIGITS.equals(ccStoreMode)) { final String creditCardNumer = payment.getCreditCardNumber(); final Obscure obscure = new Obscure(creditCardNumer, X_AD_Field.OBSCURETYPE_ObscureAlphaNumericButLast4);
payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardNumber, obscure.getObscuredValue()); payment.set_ValueOfColumn(I_C_Payment.COLUMNNAME_CreditCardVV, "***"); } else { // nothing to do } } } return null; } @Override public String docValidate(final PO po, final int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\Payment.java
1
请完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFileName (final java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setTags (final @Nullable java.lang.String Tags) { set_Value (COLUMNNAME_Tags, Tags); } @Override public java.lang.String getTags() { return get_ValueAsString(COLUMNNAME_Tags); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U";
/** Local File-URL = LU */ public static final String TYPE_LocalFile_URL = "LU"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry.java
1
请完成以下Java代码
public class Quote { private String currency; private BigDecimal ask; private BigDecimal bid; private LocalDate date; public Quote(String currency, BigDecimal ask, BigDecimal bid) { this.currency = currency; this.ask = ask; this.bid = bid; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public BigDecimal getAsk() { return ask;
} public void setAsk(BigDecimal ask) { this.ask = ask; } public BigDecimal getBid() { return bid; } public void setBid(BigDecimal bid) { this.bid = bid; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
repos\tutorials-master\core-java-modules\java-spi\exchange-rate-api\src\main\java\com\baeldung\rate\api\Quote.java
1
请完成以下Java代码
public void destroy() { } protected class SameSiteResponseProxy extends HttpServletResponseWrapper { protected HttpServletResponse response; public SameSiteResponseProxy(HttpServletResponse resp) { super(resp); response = resp; } @Override public void sendError(int sc) throws IOException { appendSameSiteIfMissing(); super.sendError(sc); } @Override public void sendError(int sc, String msg) throws IOException { appendSameSiteIfMissing(); super.sendError(sc, msg); } @Override public void sendRedirect(String location) throws IOException { appendSameSiteIfMissing(); super.sendRedirect(location); }
@Override public PrintWriter getWriter() throws IOException { appendSameSiteIfMissing(); return super.getWriter(); } @Override public ServletOutputStream getOutputStream() throws IOException { appendSameSiteIfMissing(); return super.getOutputStream(); } protected void appendSameSiteIfMissing() { Collection<String> cookieHeaders = response.getHeaders(CookieConstants.SET_COOKIE_HEADER_NAME); boolean firstHeader = true; String cookieHeaderStart = cookieConfigurator.getCookieName("JSESSIONID") + "="; for (String cookieHeader : cookieHeaders) { if (cookieHeader.startsWith(cookieHeaderStart)) { cookieHeader = cookieConfigurator.getConfig(cookieHeader); } if (firstHeader) { response.setHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader); firstHeader = false; } else { response.addHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader); } } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SessionCookieFilter.java
1
请完成以下Java代码
private I_R_Request createRequestFromShipment(final I_M_InOut shipment) { final I_C_BPartner bPartner = bPartnerDAO.getById(shipment.getC_BPartner_ID()); final I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bPartner, I_AD_User.class); final I_R_Request request = createEmptyRequest(); request.setSalesRep_ID(getAD_User_ID()); request.setC_BPartner_ID(shipment.getC_BPartner_ID()); request.setM_InOut_ID(shipment.getM_InOut_ID()); request.setDateDelivered(shipment.getMovementDate()); if (defaultContact != null) { request.setAD_User_ID(defaultContact.getAD_User_ID()); }
return request; } private I_R_Request createRequestFromUser(final I_AD_User user) { final I_R_Request request = createEmptyRequest(); request.setAD_User_ID(user.getAD_User_ID()); request.setC_BPartner_ID(user.getC_BPartner_ID()); return request; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\request\process\WEBUI_CreateRequest.java
1
请完成以下Java代码
protected IExternalSystemChildConfigId getExternalChildConfigId() { if (this.childConfigId <= 0) { throw new AdempiereException("Child Config ID is mandatory for this process!"); } return ExternalSystemScriptedExportConversionConfigId.ofRepoId(this.childConfigId); } @Override protected Map<String, String> extractExternalSystemParameters(final ExternalSystemParentConfig externalSystemParentConfig) { if (Check.isBlank(outboundDataProcessRecordId)) { throw new AdempiereException("Outbound data process record id is missing."); } final ExternalSystemScriptedExportConversionConfig externalSystemScriptedExportConversionConfig = ExternalSystemScriptedExportConversionConfig .cast(externalSystemParentConfig.getChildConfig()); return externalSystemScriptedExportConversionService.getParameters(externalSystemScriptedExportConversionConfig, getProcessInfo().getCtx(), outboundDataProcessRecordId); } @Override
protected String getTabName() { return ExternalSystemType.ScriptedExportConversion.getValue(); } @Override protected ExternalSystemType getExternalSystemType() { return ExternalSystemType.ScriptedExportConversion; } @Override protected long getSelectedRecordCount(final IProcessPreconditionsContext context) { // called when a document is completed, not from the External System window return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeScriptedExportConversionAction.java
1
请完成以下Java代码
private void retrieveOrCreateMediaTrayRecord( @NonNull final I_AD_PrinterHW printerRecord, @NonNull final PrinterHWMediaTray printerTrayPojo) { final Integer trayNumber = Integer.valueOf(printerTrayPojo.getTrayNumber()); I_AD_PrinterHW_MediaTray printerTrayRecord = Services.get(IQueryBL.class).createQueryBuilder(I_AD_PrinterHW_MediaTray.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMN_TrayNumber, trayNumber) .addEqualsFilter(I_AD_PrinterHW_MediaTray.COLUMN_AD_PrinterHW_ID, printerRecord.getAD_PrinterHW_ID()) .create() .firstOnly(I_AD_PrinterHW_MediaTray.class); if (printerTrayRecord == null) { printerTrayRecord = newInstance(I_AD_PrinterHW_MediaTray.class); printerTrayRecord.setTrayNumber(trayNumber); printerTrayRecord.setAD_PrinterHW(printerRecord); printerTrayRecord.setName(printerTrayPojo.getName()); save(printerTrayRecord); Services.get(IPrinterBL.class).createDefaultTrayMatching(printerTrayRecord); } printerTrayRecord.setName(printerTrayPojo.getName()); save(printerTrayRecord); }
private I_AD_PrinterHW retrieveOrCreatePrinterRecord( @NonNull final String hostKey, @NonNull final PrinterHW hwPrinter) { I_AD_PrinterHW printerRecord = Services.get(IQueryBL.class).createQueryBuilder(I_AD_PrinterHW.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_PrinterHW.COLUMNNAME_HostKey, hostKey) .addEqualsFilter(I_AD_PrinterHW.COLUMN_Name, hwPrinter.getName()) .create() .firstOnly(I_AD_PrinterHW.class); if (printerRecord == null) { printerRecord = newInstance(I_AD_PrinterHW.class); printerRecord.setName(hwPrinter.getName()); printerRecord.setHostKey(hostKey); printerRecord.setOutputType(OutputType.Queue.getCode()); save(printerRecord); Services.get(IPrinterBL.class).createConfigAndDefaultPrinterMatching(printerRecord); } return printerRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.rest-api-impl\src\main\java\de\metas\printing\rest\PrinterHWRepo.java
1
请完成以下Java代码
public Store where(Condition... conditions) { return where(DSL.and(conditions)); } /** * Create an inline derived table from this table */ @Override public Store where(Field<Boolean> condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Store where(SQL condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Store where(@Stringly.SQL String condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Store where(@Stringly.SQL String condition, Object... binds) { return where(DSL.condition(condition, binds)); } /** * Create an inline derived table from this table */
@Override @PlainSQL public Store where(@Stringly.SQL String condition, QueryPart... parts) { return where(DSL.condition(condition, parts)); } /** * Create an inline derived table from this table */ @Override public Store whereExists(Select<?> select) { return where(DSL.exists(select)); } /** * Create an inline derived table from this table */ @Override public Store whereNotExists(Select<?> select) { return where(DSL.notExists(select)); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Store.java
1
请完成以下Java代码
public Comparator<Object> getComparator() { if (comparator != null) { return comparator; } if (items != null && !items.isEmpty()) { final ComparatorChain<Object> cmpChain = new ComparatorChain<>(); for (final QueryOrderByItem item : items) { @SuppressWarnings("rawtypes") final ModelAccessor<Comparable> accessor = new ModelAccessor<>(item.getColumnName()); final boolean reverse = item.getDirection() == Direction.Descending; final Comparator<Object> cmpDirection = new AccessorComparator<>( ComparableComparatorNullsEqual.getInstance(), accessor); cmpChain.addComparator(cmpDirection, reverse);
final boolean nullsFirst = item.getNulls() == Nulls.First; final Comparator<Object> cmpNulls = new AccessorComparator<>( ComparableComparator.getInstance(nullsFirst), accessor); cmpChain.addComparator(cmpNulls); } comparator = cmpChain; } else { comparator = NullComparator.getInstance(); } return comparator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderBy.java
1
请完成以下Java代码
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID() { return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_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); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_HazardSymbol.java
1
请完成以下Java代码
private HULabelConfigMap retrieveMap() { ImmutableList<HULabelConfigRoute> list = queryBL.createQueryBuilder(I_M_HU_Label_Config.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(HULabelConfigRepository::fromRecord) .collect(ImmutableList.toImmutableList()); return new HULabelConfigMap(list); } public static HULabelConfigRoute fromRecord(final I_M_HU_Label_Config record) { return HULabelConfigRoute.builder() .seqNo(SeqNo.ofInt(record.getSeqNo())) .sourceDocType(HULabelSourceDocType.ofNullableCode(record.getHU_SourceDocType())) .acceptHUUnitTypes(extractAcceptedHuUnitTypes(record)) .bpartnerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_ID())) .config(HULabelConfig.builder() .printFormatProcessId(AdProcessId.ofRepoId(record.getLabelReport_Process_ID())) .autoPrint(record.isAutoPrint()) .autoPrintCopies(PrintCopies.ofIntOrOne(record.getAutoPrintCopies())) .build()) .build(); } public static ImmutableSet<HuUnitType> extractAcceptedHuUnitTypes(final I_M_HU_Label_Config record) { final ImmutableSet.Builder<HuUnitType> builder = ImmutableSet.builder(); if (record.isApplyToLUs()) { builder.add(HuUnitType.LU); } if (record.isApplyToTUs()) { builder.add(HuUnitType.TU); } if (record.isApplyToCUs()) { builder.add(HuUnitType.VHU); } return builder.build();
} // // // // // private static class HULabelConfigMap { private final ImmutableList<HULabelConfigRoute> orderedList; public HULabelConfigMap(final ImmutableList<HULabelConfigRoute> list) { this.orderedList = list.stream() .sorted(Comparator.comparing(HULabelConfigRoute::getSeqNo)) .collect(ImmutableList.toImmutableList()); } public ExplainedOptional<HULabelConfig> getFirstMatching(@NonNull final HULabelConfigQuery query) { return orderedList.stream() .filter(route -> route.isMatching(query)) .map(HULabelConfigRoute::getConfig) .findFirst() .map(ExplainedOptional::of) .orElseGet(() -> ExplainedOptional.emptyBecause("No HU Label Config found for " + query)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelConfigRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService { @Autowired private UserDao userDao; public List<User> getByMap(Map<String,Object> map){ DynamicDataSourceContextHolder.setDatabaseType(DatabaseTypeEnum.USER); return userDao.getByMap(map); } public User getById(Integer id){ DynamicDataSourceContextHolder.setDatabaseType(DatabaseTypeEnum.USER); return userDao.getById(id); } public User create(User user){ DynamicDataSourceContextHolder.setDatabaseType(DatabaseTypeEnum.USER);
userDao.create(user); return user; } public User update(User user){ DynamicDataSourceContextHolder.setDatabaseType(DatabaseTypeEnum.USER); userDao.update(user); return user; } public int delete(Integer id){ DynamicDataSourceContextHolder.setDatabaseType(DatabaseTypeEnum.USER); return userDao.delete(id); } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\service\UserService.java
2
请完成以下Java代码
public int getM_ProductPrice_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_ProductPrice getM_ProductPrice() { return get_ValueAsPO(COLUMNNAME_M_ProductPrice_ID, org.compiere.model.I_M_ProductPrice.class); } @Override public void setM_ProductPrice(org.compiere.model.I_M_ProductPrice M_ProductPrice) { set_ValueFromPO(COLUMNNAME_M_ProductPrice_ID, org.compiere.model.I_M_ProductPrice.class, M_ProductPrice); } /** Set Produkt-Preis. @param M_ProductPrice_ID Produkt-Preis */ @Override public void setM_ProductPrice_ID (int M_ProductPrice_ID) { if (M_ProductPrice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductPrice_ID, Integer.valueOf(M_ProductPrice_ID)); } /** Get Produkt-Preis. @return Produkt-Preis */ @Override public int getM_ProductPrice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Mindestpreis. @param PriceLimit Unterster Preis für Kostendeckung */ @Override public void setPriceLimit (java.math.BigDecimal PriceLimit) { set_Value (COLUMNNAME_PriceLimit, PriceLimit); } /** Get Mindestpreis. @return Unterster Preis für Kostendeckung */ @Override public java.math.BigDecimal getPriceLimit () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceLimit); if (bd == null) return BigDecimal.ZERO; return bd; }
/** Set Auszeichnungspreis. @param PriceList Auszeichnungspreis */ @Override public void setPriceList (java.math.BigDecimal PriceList) { set_Value (COLUMNNAME_PriceList, PriceList); } /** Get Auszeichnungspreis. @return Auszeichnungspreis */ @Override public java.math.BigDecimal getPriceList () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Standardpreis. @param PriceStd Standardpreis */ @Override public void setPriceStd (java.math.BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } /** Get Standardpreis. @return Standardpreis */ @Override public java.math.BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String genre; private int age; @OneToMany(cascade = CascadeType.ALL, mappedBy = "author", orphanRemoval = true) private List<Book> books = new ArrayList<>(); @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "publisher_id") @Fetch(FetchMode.JOIN) // this is not needed for entity graph and JOIN FETCH usage private Publisher publisher; public void addBook(Book book) { this.books.add(book); book.setAuthor(this); } public void removeBook(Book book) { book.setAuthor(null); this.books.remove(book); } public void removeBooks() { Iterator<Book> iterator = this.books.iterator(); while (iterator.hasNext()) { Book book = iterator.next(); book.setAuthor(null); iterator.remove(); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception { return pojoWrapper.getReferencedObject(propertyName, interfaceMethod); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) { final String propertyName; if (idPropertyName.endsWith("_ID")) { propertyName = idPropertyName.substring(0, idPropertyName.length() - 3); } else { throw new AdempiereException("Invalid idPropertyName: " + idPropertyName); } pojoWrapper.setReferencedObject(propertyName, value); } @Override public boolean invokeEquals(final Object[] methodArgs) { return pojoWrapper.invokeEquals(methodArgs); }
@Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { throw new IllegalStateException("Invoking parent method is not supported"); } @Override public boolean isKeyColumnName(final String columnName) { return pojoWrapper.isKeyColumnName(columnName); } @Override public boolean isCalculated(final String columnName) { return pojoWrapper.isCalculated(columnName); } @Override public boolean hasColumnName(String columnName) { return pojoWrapper.hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOModelInternalAccessor.java
1
请在Spring Boot框架中完成以下Java代码
protected final DataRedisProperties getProperties() { return this.properties; } protected @Nullable SslBundle getSslBundle() { return this.connectionDetails.getSslBundle(); } protected final boolean isSslEnabled() { return getProperties().getSsl().isEnabled(); } protected final boolean urlUsesSsl(String url) { return DataRedisUrl.of(url).useSsl(); } protected boolean isPoolEnabled(Pool pool) { Boolean enabled = pool.getEnabled(); return (enabled != null) ? enabled : COMMONS_POOL2_AVAILABLE; } private List<RedisNode> createSentinels(Sentinel sentinel) { List<RedisNode> nodes = new ArrayList<>(); for (Node node : sentinel.getNodes()) { nodes.add(asRedisNode(node)); } return nodes; } protected final DataRedisConnectionDetails getConnectionDetails() { return this.connectionDetails; } private Mode determineMode() {
if (getSentinelConfig() != null) { return Mode.SENTINEL; } if (getClusterConfiguration() != null) { return Mode.CLUSTER; } if (getMasterReplicaConfiguration() != null) { return Mode.MASTER_REPLICA; } return Mode.STANDALONE; } enum Mode { STANDALONE, CLUSTER, MASTER_REPLICA, SENTINEL } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionConfiguration.java
2
请完成以下Java代码
private BufferedImage makeCircleImage(int finalSize, int scale) { int hi = finalSize * scale; BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2.setComposite(AlphaComposite.Src); float stroke = 6f * scale / 3f; double diameter = hi - stroke - (4 * scale); double x = (hi - diameter) / 2.0; double y = (hi - diameter) / 2.0;
Shape circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.setPaint(new Color(0xBBDEFB)); g2.fill(circle); g2.setPaint(new Color(0x0D47A1)); g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g2.draw(circle); } finally { g2.dispose(); } return img; } } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\drawcircle\DrawBufferedCircle.java
1
请完成以下Java代码
public PermissionCheckBuilder disjunctive() { this.disjunctive = true; return this; } public PermissionCheckBuilder conjunctive() { this.disjunctive = false; return this; } public PermissionCheckBuilder atomicCheck(Resource resource, String queryParam, Permission permission) { if (!isPermissionDisabled(permission)) { PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceIdQueryParam(queryParam); permCheck.setPermission(permission); this.atomicChecks.add(permCheck); } return this; } public PermissionCheckBuilder atomicCheckForResourceId(Resource resource, String resourceId, Permission permission) { if (!isPermissionDisabled(permission)) { PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceId(resourceId); permCheck.setPermission(permission); this.atomicChecks.add(permCheck); } return this; } public PermissionCheckBuilder composite() { return new PermissionCheckBuilder(this); } public PermissionCheckBuilder done() { parent.compositeChecks.add(this.build()); return parent; } public CompositePermissionCheck build() { validate();
CompositePermissionCheck permissionCheck = new CompositePermissionCheck(disjunctive); permissionCheck.setAtomicChecks(atomicChecks); permissionCheck.setCompositeChecks(compositeChecks); return permissionCheck; } public List<PermissionCheck> getAtomicChecks() { return atomicChecks; } protected void validate() { if (!atomicChecks.isEmpty() && !compositeChecks.isEmpty()) { throw new ProcessEngineException("Mixed authorization checks of atomic and composite permissions are not supported"); } } public boolean isPermissionDisabled(Permission permission) { AuthorizationManager authorizationManager = Context.getCommandContext().getAuthorizationManager(); return authorizationManager.isPermissionDisabled(permission); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheckBuilder.java
1
请完成以下Java代码
public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceId() { orderBy(HistoricCaseActivityInstanceQueryProperty.HISTORIC_CASE_ACTIVITY_INSTANCE_ID); return this; } public HistoricCaseActivityInstanceQuery orderByCaseInstanceId() { orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_INSTANCE_ID); return this; } public HistoricCaseActivityInstanceQuery orderByCaseExecutionId() { orderBy(HistoricCaseActivityInstanceQueryProperty.HISTORIC_CASE_ACTIVITY_INSTANCE_ID); return this; } public HistoricCaseActivityInstanceQuery orderByCaseActivityId() { orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_ACTIVITY_ID); return this; } public HistoricCaseActivityInstanceQuery orderByCaseActivityName() { orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_ACTIVITY_NAME); return this; } public HistoricCaseActivityInstanceQuery orderByCaseActivityType() { orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_ACTIVITY_TYPE); return this; } public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceCreateTime() { orderBy(HistoricCaseActivityInstanceQueryProperty.CREATE); return this; } public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceEndTime() { orderBy(HistoricCaseActivityInstanceQueryProperty.END); return this; } public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceDuration() { orderBy(HistoricCaseActivityInstanceQueryProperty.DURATION); return this; } public HistoricCaseActivityInstanceQuery orderByCaseDefinitionId() { orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_DEFINITION_ID); return this; } public HistoricCaseActivityInstanceQuery orderByTenantId() { return orderBy(HistoricCaseActivityInstanceQueryProperty.TENANT_ID); } // getter public String[] getCaseActivityInstanceIds() { return caseActivityInstanceIds; } public String getCaseInstanceId() {
return caseInstanceId; } public String getCaseDefinitionId() { return caseDefinitionId; } public String[] getCaseActivityIds() { return caseActivityIds; } public String getCaseActivityName() { return caseActivityName; } public String getCaseActivityType() { return caseActivityType; } public Date getCreatedBefore() { return createdBefore; } public Date getCreatedAfter() { return createdAfter; } public Date getEndedBefore() { return endedBefore; } public Date getEndedAfter() { return endedAfter; } public Boolean getEnded() { return ended; } public Integer getCaseActivityInstanceState() { return caseActivityInstanceState; } public Boolean isRequired() { return required; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseActivityInstanceQueryImpl.java
1
请完成以下Java代码
public AttributesKey getStorageAttributesKey() {return getProductDescriptor().getStorageAttributesKey();} public void assertMaterialDispoGroupIdIsSet() { if (materialDispoGroupId == null) { throw new AdempiereException("Expected materialDispoGroupId to be set: " + this); } } public DDOrderCandidateData withPPOrderId(@Nullable final PPOrderId forwardPPOrderIdNew) { final PPOrderRef forwardPPOrderRefNew = PPOrderRef.withPPOrderId(forwardPPOrderRef, forwardPPOrderIdNew); if (Objects.equals(this.forwardPPOrderRef, forwardPPOrderRefNew)) { return this;
} return toBuilder().forwardPPOrderRef(forwardPPOrderRefNew).build(); } public int getOrderLineIdAsRepoId() { return IdConstants.toRepoId(salesOrderLineId); } public int getOrderIdAsRepoId() { return IdConstants.toRepoId(salesOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\DDOrderCandidateData.java
1
请完成以下Java代码
private String prepareJSONPath(@NonNull final String rawJSONPath) { return StringUtils.prependIfNotStartingWith( rawJSONPath .replace("\n", "") .replace("\r", ""), "/"); } private Evaluatee getEvalContext() { final List<Evaluatee> contexts = new ArrayList<>(); contexts.add(Evaluatees.ofRangeAwareParams(getProcessInfo().getParameterAsIParams())); contexts.add(Evaluatees.ofCtx(Env.getCtx())); return Evaluatees.compose(contexts); } protected final boolean isCalledViaAPI() {
return ProcessCalledFrom.API.equals(getProcessInfo().getProcessCalledFrom()); } @Value @Builder protected static class CustomPostgRESTParameters { boolean storeJsonFile; /** * Expect one object from postgREST, not an array. Fail if there are zero or more than one objects. */ @Builder.Default boolean expectSingleResult = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\process\PostgRESTProcessExecutor.java
1
请完成以下Java代码
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public boolean isActive() { return isActive; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) { this.involvedUser = involvedUser; } public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name;
} public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
private String computeChecksum(JsonNode node) { String canonicalString = JacksonUtil.toCanonicalString(node); if (canonicalString == null) { return null; } return Hashing.sha256().hashBytes(canonicalString.getBytes()).toString(); } private boolean acquireAdvisoryLock() { try { Boolean acquired = jdbcTemplate.queryForObject( "SELECT pg_try_advisory_lock(?)", Boolean.class, ADVISORY_LOCK_ID ); if (Boolean.TRUE.equals(acquired)) { log.trace("Acquired advisory lock"); return true; } return false; } catch (Exception e) { log.error("Failed to acquire advisory lock", e); return false; } } private void releaseAdvisoryLock() { try { jdbcTemplate.queryForObject( "SELECT pg_advisory_unlock(?)", Boolean.class, ADVISORY_LOCK_ID ); log.debug("Released advisory lock"); } catch (Exception e) { log.error("Failed to release advisory lock", e);
} } private VersionInfo parseVersion(String version) { try { String[] parts = version.split("\\."); int major = Integer.parseInt(parts[0]); int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; int maintenance = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; int patch = parts.length > 3 ? Integer.parseInt(parts[3]) : 0; return new VersionInfo(major, minor, maintenance, patch); } catch (Exception e) { log.error("Failed to parse version: {}", version, e); return null; } } private Stream<Path> listDir(Path dir) { try { return Files.list(dir); } catch (NoSuchFileException e) { return Stream.empty(); } catch (IOException e) { throw new UncheckedIOException(e); } } public record VersionInfo(int major, int minor, int maintenance, int patch) {} }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\system\SystemPatchApplier.java
2
请完成以下Java代码
public boolean isEnableEagerExecutionTreeFetching() { return enableEagerExecutionTreeFetching; } public void setEnableEagerExecutionTreeFetching(boolean enableEagerExecutionTreeFetching) { this.enableEagerExecutionTreeFetching = enableEagerExecutionTreeFetching; } public boolean isEnableExecutionRelationshipCounts() { return enableExecutionRelationshipCounts; } public void setEnableExecutionRelationshipCounts(boolean enableExecutionRelationshipCounts) { this.enableExecutionRelationshipCounts = enableExecutionRelationshipCounts; } public boolean isValidateExecutionRelationshipCountConfigOnBoot() {
return validateExecutionRelationshipCountConfigOnBoot; } public void setValidateExecutionRelationshipCountConfigOnBoot( boolean validateExecutionRelationshipCountConfigOnBoot ) { this.validateExecutionRelationshipCountConfigOnBoot = validateExecutionRelationshipCountConfigOnBoot; } public boolean isEnableLocalization() { return enableLocalization; } public void setEnableLocalization(boolean enableLocalization) { this.enableLocalization = enableLocalization; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\PerformanceSettings.java
1
请完成以下Java代码
public static String rewriteWhereClauseWithLowercaseKeyWords(final String whereClause) { return whereClause.replaceAll("\\s", " ") .replaceAll(WHERE, WHERE_LOWERCASE) .replaceAll(FROM, FROM_LOWERCASE) .replaceAll(ON, ON_LOWERCASE); } @Value public static class TableNameAndAlias { public static TableNameAndAlias ofTableNameAndAlias(final String tableName, final String alias) { return new TableNameAndAlias(tableName, alias); } public static TableNameAndAlias ofTableName(final String tableName) { final String synonym = ""; return new TableNameAndAlias(tableName, synonym); } private final String tableName; private final String alias; private TableNameAndAlias(@NonNull final String tableName, final String alias) { this.tableName = tableName; this.alias = alias != null ? alias : ""; } public String getAliasOrTableName() { return !alias.isEmpty() ? alias : tableName; } public boolean isTrlTable() { return tableName.toUpperCase().endsWith("_TRL"); } } @Value public static final class SqlSelect { private final String sql; private final ImmutableList<TableNameAndAlias> tableNameAndAliases; @Builder private SqlSelect( @NonNull final String sql, @NonNull @Singular final ImmutableList<TableNameAndAlias> tableNameAndAliases) { this.sql = sql; this.tableNameAndAliases = tableNameAndAliases; }
public boolean hasWhereClause() { return sql.indexOf(" WHERE ") >= 0; } public String getFirstTableAliasOrTableName() { if (tableNameAndAliases.isEmpty()) // TODO check if we still need this check! { return ""; } return tableNameAndAliases.get(0).getAliasOrTableName(); } public String getFirstTableNameOrEmpty() { if (tableNameAndAliases.isEmpty()) { return ""; } return tableNameAndAliases.get(0).getTableName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\ParsedSql.java
1
请完成以下Java代码
public Bindings createBindings() { return new SimpleBindings(); } public ScriptEngineFactory getFactory() { if (scriptEngineFactory == null) { synchronized (this) { if (scriptEngineFactory == null) { scriptEngineFactory = new FreeMarkerScriptEngineFactory(); } } } return scriptEngineFactory; } public void initConfiguration() { if (configuration == null) { synchronized (this) { if (configuration == null) { configuration = new Configuration(Configuration.VERSION_2_3_29); } } } }
protected String getFilename(ScriptContext context) { String filename = (String) context.getAttribute(ScriptEngine.FILENAME); if (filename != null) { return filename; } else { return "unknown"; } } public CompiledScript compile(String script) throws ScriptException { return compile(new StringReader(script)); } public CompiledScript compile(Reader script) throws ScriptException { initConfiguration(); return new FreeMarkerCompiledScript(this, script, configuration); } }
repos\camunda-bpm-platform-master\freemarker-template-engine\src\main\java\org\camunda\templateengines\FreeMarkerScriptEngine.java
1
请完成以下Java代码
public void setDocAction (String DocAction) { set_Value (COLUMNNAME_DocAction, DocAction); } /** Get Document Action. @return The targeted status of the document */ public String getDocAction () { return (String)get_Value(COLUMNNAME_DocAction); } /** Set Create Counter Document. @param IsCreateCounter Create Counter Document */ public void setIsCreateCounter (boolean IsCreateCounter) { set_Value (COLUMNNAME_IsCreateCounter, Boolean.valueOf(IsCreateCounter)); } /** Get Create Counter Document. @return Create Counter Document */ public boolean isCreateCounter () { Object oo = get_Value(COLUMNNAME_IsCreateCounter); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Valid. @param IsValid Element is valid */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Valid. @return Element is valid */ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocTypeCounter.java
1
请完成以下Java代码
public String toString() { return "Pointcut [type=" + type + ", tableName=" + tableName + ", modelClass=" + modelClass + ", method=" + method + ", timings=" + timings + ", afterCommit=" + afterCommit + ", columnNamesToCheckForChanges=" + columnNamesToCheckForChanges + ", methodTimingParameterType=" + methodTimingParameterType + ", onlyIfUIAction=" + onlyIfUIAction + "]"; } public boolean isMethodRequiresTiming() { return methodTimingParameterType != null; } public Object convertToMethodTimingParameterType(final int timing) { if (methodTimingParameterType == null) { // shall not happen throw new AdempiereException("Method does not required timing parameter: " + getMethod()); } else if (int.class.isAssignableFrom(methodTimingParameterType)) { return timing; } else if (ModelChangeType.class.isAssignableFrom(methodTimingParameterType)) { return ModelChangeType.valueOf(timing); } else if (DocTimingType.class.isAssignableFrom(methodTimingParameterType)) { return DocTimingType.valueOf(timing); } else { // shall not happen because we already validated the parameter type when we set it throw new AdempiereException("Not supported timing parameter type '" + methodTimingParameterType + "' for method " + getMethod()); } } /** * Returns <code>true</code> if the other instance is also a PointCut and if {@link #compareTo(Pointcut)} returns 0.<br> * Just added this method because the javadoc of {@link java.util.SortedSet} states that {@link #equals(Object)} and {@link #compareTo(Pointcut)} need to be consistent. * * @task https://metasfresh.atlassian.net/browse/FRESH-318 */ @Override public boolean equals(final Object obj)
{ if (this == obj) { return true; } final Pointcut other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } // we use PointCut in a sorted set, so equals has to be consistent with compareTo() if (compareTo(other) == 0) { return true; } return false; }; /** * Compares this instance with the given {@link Pointcut} by comparing their. * <ul> * <li>TableName</li> * <li>Method's name</li> * <li>Method's declaring class name</li> * </ul> * * @task https://metasfresh.atlassian.net/browse/FRESH-318 */ @Override public int compareTo(final Pointcut o) { return ComparisonChain.start() .compare(getTableName(), o.getTableName()) .compare(getMethod() == null ? null : getMethod().getDeclaringClass().getName(), o.getMethod() == null ? null : o.getMethod().getDeclaringClass().getName()) .compare(getMethod() == null ? null : getMethod().getName(), o.getMethod() == null ? null : o.getMethod().getName()) .compare(getMethod() == null ? null : getMethod().getName(), o.getMethod() == null ? null : o.getMethod().getName()) .result(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\Pointcut.java
1
请完成以下Java代码
public class MachineEntity { private Long id; private Date gmtCreate; private Date gmtModified; private String app; private String ip; private String hostname; private Date timestamp; private Integer port; public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; }
public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public MachineInfo toMachineInfo() { MachineInfo machineInfo = new MachineInfo(); machineInfo.setApp(app); machineInfo.setHostname(hostname); machineInfo.setIp(ip); machineInfo.setPort(port); machineInfo.setLastHeartbeat(timestamp.getTime()); machineInfo.setHeartbeatVersion(timestamp.getTime()); return machineInfo; } @Override public String toString() { return "MachineEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", hostname='" + hostname + '\'' + ", timestamp=" + timestamp + ", port=" + port + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MachineEntity.java
1
请完成以下Java代码
public boolean getIsPurchaseOr(final boolean defaultValue) { return purchase.orElse(defaultValue); } public void setDefaultContact(final boolean defaultContact) { this.defaultContact = Optional.of(defaultContact); } public void setBillToDefault(final boolean billToDefault) { this.billToDefault = Optional.of(billToDefault); }
public void setShipToDefault(final boolean shipToDefault) { this.shipToDefault = Optional.of(shipToDefault); } public void setPurchaseDefault(final boolean purchaseDefault) { this.purchaseDefault = Optional.of(purchaseDefault); } public void setSalesDefault(final boolean salesDefault) { this.salesDefault = Optional.of(salesDefault); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerContactType.java
1
请完成以下Java代码
ConfigurableEnvironment convertEnvironmentIfNecessary(ConfigurableEnvironment environment, Class<? extends ConfigurableEnvironment> type) { if (type.equals(environment.getClass())) { return environment; } return convertEnvironment(environment, type); } private ConfigurableEnvironment convertEnvironment(ConfigurableEnvironment environment, Class<? extends ConfigurableEnvironment> type) { ConfigurableEnvironment result = createEnvironment(type); result.setActiveProfiles(environment.getActiveProfiles()); result.setConversionService(environment.getConversionService()); copyPropertySources(environment, result); return result; } private ConfigurableEnvironment createEnvironment(Class<? extends ConfigurableEnvironment> type) { try { Constructor<? extends ConfigurableEnvironment> constructor = type.getDeclaredConstructor(); ReflectionUtils.makeAccessible(constructor); return constructor.newInstance(); } catch (Exception ex) { return new ApplicationEnvironment(); } } private void copyPropertySources(ConfigurableEnvironment source, ConfigurableEnvironment target) { removePropertySources(target.getPropertySources(), isServletEnvironment(target.getClass(), this.classLoader)); for (PropertySource<?> propertySource : source.getPropertySources()) { if (!SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(propertySource.getName())) { target.getPropertySources().addLast(propertySource); } } } private boolean isServletEnvironment(Class<?> conversionType, ClassLoader classLoader) {
try { Class<?> webEnvironmentClass = ClassUtils.forName(CONFIGURABLE_WEB_ENVIRONMENT_CLASS, classLoader); return webEnvironmentClass.isAssignableFrom(conversionType); } catch (Throwable ex) { return false; } } private void removePropertySources(MutablePropertySources propertySources, boolean isServletEnvironment) { Set<String> names = new HashSet<>(); for (PropertySource<?> propertySource : propertySources) { names.add(propertySource.getName()); } for (String name : names) { if (!isServletEnvironment || !SERVLET_ENVIRONMENT_SOURCE_NAMES.contains(name)) { propertySources.remove(name); } } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\EnvironmentConverter.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("candidate", candidate) .toString(); } @Override public Properties getCtx() { return InterfaceWrapperHelper.getCtx(candidate); } @Override public I_C_BPartner getC_BPartner() { return candidate.getC_BPartner(); } @Override public boolean isContractedProduct() { final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry(); if (flatrateDataEntry == null) { return false; } // Consider that we have a contracted product only if the data entry has the Price or the QtyPlanned set (FRESH-568) return Services.get(IPMMContractsBL.class).hasPriceOrQty(flatrateDataEntry); } @Override public I_M_Product getM_Product() { return candidate.getM_Product(); } @Override public int getProductId() { return candidate.getM_Product_ID(); } @Override public I_C_UOM getC_UOM() { return candidate.getC_UOM(); } @Override public I_C_Flatrate_Term getC_Flatrate_Term() { final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry(); if(flatrateDataEntry == null) { return null; } return flatrateDataEntry.getC_Flatrate_Term(); }
@Override public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry() { return InterfaceWrapperHelper.create(candidate.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class); } @Override public Object getWrappedModel() { return candidate; } @Override public Timestamp getDate() { return candidate.getDatePromised(); } @Override public BigDecimal getQty() { // TODO: shall we use QtyToOrder instead... but that could affect our price (if we have some prices defined on breaks) return candidate.getQtyPromised(); } @Override public void setM_PricingSystem_ID(int M_PricingSystem_ID) { candidate.setM_PricingSystem_ID(M_PricingSystem_ID); } @Override public void setM_PriceList_ID(int M_PriceList_ID) { candidate.setM_PriceList_ID(M_PriceList_ID); } @Override public void setCurrencyId(final CurrencyId currencyId) { candidate.setC_Currency_ID(CurrencyId.toRepoId(currencyId)); } @Override public void setPrice(BigDecimal priceStd) { candidate.setPrice(priceStd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_PurchaseCandidate.java
1
请完成以下Java代码
public void addFirst(Pipe<M, M> pipe) { pipeList.addFirst(pipe); } /** * 以最低优先级加入管道 * * @param pipe */ public void addLast(Pipe<M, M> pipe) { pipeList.addLast(pipe); } @Override public Pipe<M, M> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) {
return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<M, M>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<M, M>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<M, M>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java
1
请完成以下Java代码
public boolean isEmpty() { return customerIds.isEmpty() && deliveryDays.isEmpty() && handoverLocationIds.isEmpty(); } public boolean isMatching(final PickingJobReference pickingJobReference) { return isCustomerMatching(pickingJobReference) && isDeliveryDateMatching(pickingJobReference) && isHandoverLocationMatching(pickingJobReference); } public boolean isMatching(final PickingJobFacet facet) { return PickingJobFacetHandlers.isMatching(facet, this); } private boolean isCustomerMatching(final PickingJobReference pickingJobReference) {return isCustomerMatching(pickingJobReference.getCustomerId());} private boolean isCustomerMatching(final BPartnerId customerId) {return customerIds.isEmpty() || customerIds.contains(customerId);} private boolean isDeliveryDateMatching(final PickingJobReference pickingJobReference) { final ZonedDateTime deliveryDate = pickingJobReference.getDeliveryDate(); return deliveryDate != null && isDeliveryDateMatching(deliveryDate.toLocalDate()); } private boolean isDeliveryDateMatching(final LocalDate deliveryDay) {return deliveryDays.isEmpty() || deliveryDays.contains(deliveryDay);} private boolean isHandoverLocationMatching(final PickingJobReference pickingJobReference) {return isHandoverLocationMatching(Optional.ofNullable(pickingJobReference.getHandoverLocationId()).orElse(pickingJobReference.getDeliveryBPLocationId()));} private boolean isHandoverLocationMatching(final BPartnerLocationId handoverLocationId) {return handoverLocationIds.isEmpty() || handoverLocationIds.contains(handoverLocationId);}
public Facets retainFacetsOfGroup(@NonNull final PickingJobFacetGroup group) {return PickingJobFacetHandlers.retainFacetsOfGroups(this, ImmutableSet.of(group));} public Set<Facets> toSingleElementFacets() { if (isEmpty()) { return ImmutableSet.of(); } return Streams.concat( customerIds.stream().map(customerId -> Facets.builder().customerId(customerId).build()), deliveryDays.stream().map(deliveryDay -> Facets.builder().deliveryDay(deliveryDay).build()), handoverLocationIds.stream().map(handoverLocationId -> Facets.builder().handoverLocationId(handoverLocationId).build()) ) .collect(ImmutableSet.toImmutableSet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobQuery.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getMemberId() { return memberId; } public void setMemberId(Integer memberId) { this.memberId = memberId; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getMemberPhone() { return memberPhone; } public void setMemberPhone(String memberPhone) { this.memberPhone = memberPhone; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Date getSubscribeTime() {
return subscribeTime; } public void setSubscribeTime(Date subscribeTime) { this.subscribeTime = subscribeTime; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } @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(", memberId=").append(memberId); sb.append(", productId=").append(productId); sb.append(", memberPhone=").append(memberPhone); sb.append(", productName=").append(productName); sb.append(", subscribeTime=").append(subscribeTime); sb.append(", sendTime=").append(sendTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionLog.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getElementId() { return elementId; } public String getElementName() { return elementName; } public String getScopeId() { return scopeId; } public boolean isWithoutScopeId() { return withoutScopeId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() { return scopeType; } public boolean isWithoutScopeType() { return withoutScopeType; } public String getScopeDefinitionId() { return scopeDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCorrelationId() { return correlationId; } public boolean isOnlyTimers() {
return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public boolean isExecutable() { return executable; } public boolean isOnlyExternalWorkers() { return onlyExternalWorkers; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\DeadLetterJobQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public List<Survey> retrieveAllSurveys() { return surveys; } public Survey retrieveSurvey(String surveyId) { for (Survey survey : surveys) { if (survey.getId().equals(surveyId)) { return survey; } } return null; } public List<Question> retrieveQuestions(String surveyId) { Survey survey = retrieveSurvey(surveyId); if (survey == null) { return null; } return survey.getQuestions(); } public Question retrieveQuestion(String surveyId, String questionId) { Survey survey = retrieveSurvey(surveyId); if (survey == null) { return null; } for (Question question : survey.getQuestions()) { if (question.getId().equals(questionId)) { return question;
} } return null; } private SecureRandom random = new SecureRandom(); public Question addQuestion(String surveyId, Question question) { Survey survey = retrieveSurvey(surveyId); if (survey == null) { return null; } String randomId = new BigInteger(130, random).toString(32); question.setId(randomId); survey.getQuestions().add(question); return question; } }
repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\service\SurveyService.java
2
请完成以下Java代码
public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getActive() { return active; } public void setActive(int active) { this.active = active; } public List<String> getRoleList() { if(this.roles.length() > 0) { return Arrays.asList(this.roles.split(",")); } return new ArrayList<>(); }
public void setRoles(String roles) { this.roles = roles; } public List<String> getPermissionList() { if(this.permissions.length() > 0) { return Arrays.asList(this.permissions.split(",")); } return new ArrayList<>(); } public void setPermissions(String permissions) { this.permissions = permissions; } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\model\User.java
1
请完成以下Java代码
public int getR_InterestArea_ID() { return get_ValueAsInt(COLUMNNAME_R_InterestArea_ID); } @Override public void setSalesgroup (final @Nullable java.lang.String Salesgroup) { set_Value (COLUMNNAME_Salesgroup, Salesgroup); } @Override public java.lang.String getSalesgroup() { return get_ValueAsString(COLUMNNAME_Salesgroup); } @Override public void setShelfLifeMinDays (final int ShelfLifeMinDays) { set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays); } @Override public int getShelfLifeMinDays() { return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays); } @Override public void setShipperName (final @Nullable java.lang.String ShipperName) { set_Value (COLUMNNAME_ShipperName, ShipperName); } @Override public java.lang.String getShipperName() { return get_ValueAsString(COLUMNNAME_ShipperName); } @Override public void setShipperRouteCodeName (final @Nullable java.lang.String ShipperRouteCodeName) { set_Value (COLUMNNAME_ShipperRouteCodeName, ShipperRouteCodeName); } @Override public java.lang.String getShipperRouteCodeName() { return get_ValueAsString(COLUMNNAME_ShipperRouteCodeName); } @Override public void setShortDescription (final @Nullable java.lang.String ShortDescription) { set_Value (COLUMNNAME_ShortDescription, ShortDescription); } @Override public java.lang.String getShortDescription() { return get_ValueAsString(COLUMNNAME_ShortDescription); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } @Override public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID);
} @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } @Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请完成以下Java代码
public class X_MD_Stock extends org.compiere.model.PO implements I_MD_Stock, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1875304086L; /** Standard Constructor */ public X_MD_Stock (final Properties ctx, final int MD_Stock_ID, @Nullable final String trxName) { super (ctx, MD_Stock_ID, trxName); } /** Load Constructor */ public X_MD_Stock (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAttributesKey (final java.lang.String AttributesKey) { set_Value (COLUMNNAME_AttributesKey, AttributesKey); } @Override public java.lang.String getAttributesKey() { return get_ValueAsString(COLUMNNAME_AttributesKey); } @Override public void setMD_Stock_ID (final int MD_Stock_ID) { if (MD_Stock_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Stock_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Stock_ID, MD_Stock_ID); } @Override
public int getMD_Stock_ID() { return get_ValueAsInt(COLUMNNAME_MD_Stock_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock.java
1
请完成以下Java代码
public void setPwd(String pwd) { this.pwd = pwd; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated;
} public Set<String> getRoles() { return roles; } public void setRoles(Set<String> roles) { this.roles = roles; } public Set<String> getPerms() { return perms; } public void setPerms(Set<String> perms) { this.perms = perms; } }
repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\User.java
1
请完成以下Java代码
protected Timestamp extractEffectiveSinceTimestamp() { return CoalesceUtil.coalesceSuppliersNotNull(() -> since, this::retrieveSinceValue, () -> Timestamp.from(Instant.ofEpochSecond(0))); } private Timestamp retrieveSinceValue() { final ProcessInfo processInfo = getProcessInfo(); return pInstanceDAO.getLastRunDate(processInfo.getAdProcessId(), processInfo.getPinstanceId()); } private Map<String, String> extractParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { final Map<String, String> parameters = new HashMap<>(); final Map<String, String> childSpecificParams = extractExternalSystemParameters(externalSystemParentConfig); if (childSpecificParams != null && !childSpecificParams.isEmpty()) { parameters.putAll(childSpecificParams); } runtimeParametersRepository.getByConfigIdAndRequest(externalSystemParentConfig.getId(), externalRequest) .forEach(runtimeParameter -> parameters.put(runtimeParameter.getName(), runtimeParameter.getValue()));
return parameters; } protected String getOrgCode(@NonNull final ExternalSystemParentConfig externalSystemParentConfig) { return orgDAO.getById(getOrgId()).getValue(); } @Nullable protected Timestamp getSinceParameterValue() { return since; } protected abstract IExternalSystemChildConfigId getExternalChildConfigId(); protected abstract Map<String, String> extractExternalSystemParameters(ExternalSystemParentConfig externalSystemParentConfig); protected abstract String getTabName(); protected abstract ExternalSystemType getExternalSystemType(); protected abstract long getSelectedRecordCount(final IProcessPreconditionsContext context); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeExternalSystemProcess.java
1
请在Spring Boot框架中完成以下Java代码
public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public void setC_Project_Repair_Consumption_Summary_ID (final int C_Project_Repair_Consumption_Summary_ID) { if (C_Project_Repair_Consumption_Summary_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, C_Project_Repair_Consumption_Summary_ID); } @Override public int getC_Project_Repair_Consumption_Summary_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Repair_Consumption_Summary_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
} @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请完成以下Java代码
private GenericZoomIntoTableInfo getTableInfo() { if (_tableInfo == null) { _tableInfo = tableInfoByTableName.getOrLoad( TableInfoCacheKey.builder().tableName(getTableName()).ignoreExcludeFromZoomTargetsFlag(ignoreExcludeFromZoomTargetsFlag).build(), this::retrieveTableInfo); } return _tableInfo; } private GenericZoomIntoTableInfo retrieveTableInfo(@NonNull final TableInfoCacheKey key) { return tableInfoRepository.retrieveTableInfo(key.getTableName(), key.isIgnoreExcludeFromZoomTargetsFlag()) .withCustomizedWindowIds(customizedWindowInfoMapRepository.get()); } private SOTrx getRecordSOTrxEffective() { if (_recordSOTrx_Effective == null) { _recordSOTrx_Effective = computeRecordSOTrxEffective(); } return _recordSOTrx_Effective; } private SOTrx computeRecordSOTrxEffective() { final String tableName = getTableInfo().getTableName(); final String sqlWhereClause = getRecordWhereClause(); // might be null if (sqlWhereClause == null || Check.isBlank(sqlWhereClause)) { return SOTrx.SALES; } return DB.retrieveRecordSOTrx(tableName, sqlWhereClause).orElse(SOTrx.SALES); } private Optional<TableRecordReference> retrieveParentRecordRef() { final GenericZoomIntoTableInfo tableInfo = getTableInfo(); if (tableInfo.getParentTableName() == null || tableInfo.getParentLinkColumnName() == null) { return Optional.empty(); } final String sqlWhereClause = getRecordWhereClause(); // might be null if (sqlWhereClause == null || Check.isBlank(sqlWhereClause)) { return Optional.empty(); } final String sql = "SELECT " + tableInfo.getParentLinkColumnName() + " FROM " + tableInfo.getTableName() + " WHERE " + sqlWhereClause; try { final int parentRecordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql); if (parentRecordId < InterfaceWrapperHelper.getFirstValidIdByColumnName(tableInfo.getParentTableName() + "_ID"))
{ return Optional.empty(); } final TableRecordReference parentRecordRef = TableRecordReference.of(tableInfo.getParentTableName(), parentRecordId); return Optional.of(parentRecordRef); } catch (final Exception ex) { logger.warn("Failed retrieving parent record ID from current record. Returning empty. \n\tthis={} \n\tSQL: {}", this, sql, ex); return Optional.empty(); } } @NonNull private static CustomizedWindowInfoMapRepository getCustomizedWindowInfoMapRepository() { return !Adempiere.isUnitTestMode() ? SpringContextHolder.instance.getBean(CustomizedWindowInfoMapRepository.class) : NullCustomizedWindowInfoMapRepository.instance; } @Value @Builder private static class TableInfoCacheKey { @NonNull String tableName; boolean ignoreExcludeFromZoomTargetsFlag; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\RecordWindowFinder.java
1
请完成以下Java代码
protected TbDeleteRelationNodeConfiguration loadEntityNodeActionConfig(TbNodeConfiguration configuration) throws TbNodeException { var deleteRelationNodeConfiguration = TbNodeUtils.convert(configuration, TbDeleteRelationNodeConfiguration.class); if (!deleteRelationNodeConfiguration.isDeleteForSingleEntity()) { return deleteRelationNodeConfiguration; } checkIfConfigEntityTypeIsSupported(deleteRelationNodeConfiguration.getEntityType()); return deleteRelationNodeConfiguration; } @Override protected boolean createEntityIfNotExists() { return false; } @Override public void onMsg(TbContext ctx, TbMsg msg) { ListenableFuture<Boolean> deleteResultFuture = config.isDeleteForSingleEntity() ? Futures.transformAsync(getTargetEntityId(ctx, msg), targetEntityId -> deleteRelationToSpecificEntity(ctx, msg, targetEntityId), MoreExecutors.directExecutor()) : deleteRelationsByTypeAndDirection(ctx, msg, ctx.getDbCallbackExecutor()); withCallback(deleteResultFuture, deleted -> { if (deleted) { ctx.tellSuccess(msg); return; } ctx.tellFailure(msg, new RuntimeException("Failed to delete relation(s) with originator!")); }, t -> ctx.tellFailure(msg, t), MoreExecutors.directExecutor()); } private ListenableFuture<Boolean> deleteRelationToSpecificEntity(TbContext ctx, TbMsg msg, EntityId targetEntityId) { EntityId fromId; EntityId toId; if (EntitySearchDirection.FROM.equals(config.getDirection())) { fromId = msg.getOriginator();
toId = targetEntityId; } else { toId = msg.getOriginator(); fromId = targetEntityId; } var relationType = processPattern(msg, config.getRelationType()); var tenantId = ctx.getTenantId(); var relationService = ctx.getRelationService(); return Futures.transformAsync(relationService.checkRelationAsync(tenantId, fromId, toId, relationType, RelationTypeGroup.COMMON), relationExists -> { if (relationExists) { return relationService.deleteRelationAsync(tenantId, fromId, toId, relationType, RelationTypeGroup.COMMON); } return Futures.immediateFuture(true); }, MoreExecutors.directExecutor()); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbDeleteRelationNode.java
1
请完成以下Java代码
public int getDoc_User_ID() { return getPlanner_ID(); } @Override public BigDecimal getApprovalAmt() { return BigDecimal.ZERO; } @Override public int getC_Currency_ID() { return 0; } @Override public String getProcessMsg() { return null; } @Override public String getSummary() { return getDocumentNo() + "/" + getDatePromised(); } @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateOrdered()); } @Override public File createPDF() { final DocumentReportService documentReportService = SpringContextHolder.instance.getBean(DocumentReportService.class); final ReportResultData report = documentReportService.createStandardDocumentReportData(getCtx(), StandardDocumentReportType.MANUFACTURING_ORDER, getPP_Order_ID()); return report.writeToTemporaryFile(get_TableName() + get_ID()); } @Override public String getDocumentInfo() { final IDocTypeBL docTypeBL = Services.get(IDocTypeBL.class); final DocTypeId docTypeId = DocTypeId.ofRepoId(getC_DocType_ID()); final ITranslatableString docTypeName = docTypeBL.getNameById(docTypeId); return docTypeName.translate(Env.getADLanguageOrBaseLanguage()) + " " + getDocumentNo(); } private PPOrderRouting getOrderRouting() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return Services.get(IPPOrderRoutingRepository.class).getByOrderId(orderId); } @Override public String toString() { return "MPPOrder[ID=" + get_ID() + "-DocumentNo=" + getDocumentNo() + ",IsSOTrx=" + isSOTrx() + ",C_DocType_ID=" + getC_DocType_ID() + "]"; } /** * Auto report the first Activity and Sub contracting if are Milestone Activity */ private void autoReportActivities() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { if (activity.isMilestone() && (activity.isSubcontracting() || orderRouting.isFirstActivity(activity))) { ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder() .order(this) .orderActivity(activity) .qtyMoved(activity.getQtyToDeliver()) .durationSetup(Duration.ZERO) .duration(Duration.ZERO) .build()); } } } private void createVariances() { final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); // for (final I_PP_Order_BOMLine bomLine : getLines()) { ppCostCollectorBL.createMaterialUsageVariance(this, bomLine); } // final PPOrderRouting orderRouting = getOrderRouting(); for (final PPOrderRoutingActivity activity : orderRouting.getActivities()) { ppCostCollectorBL.createResourceUsageVariance(this, activity); } } } // MPPOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java
1
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Zusammenfassungseintrag. @param IsSummary This is a summary entity */ @Override public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Zusammenfassungseintrag. @return This is a summary entity */ @Override public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override
public org.compiere.model.I_C_Activity getParent_Activity() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class); } @Override public void setParent_Activity(org.compiere.model.I_C_Activity Parent_Activity) { set_ValueFromPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class, Parent_Activity); } /** Set Hauptkostenstelle. @param Parent_Activity_ID Hauptkostenstelle */ @Override public void setParent_Activity_ID (int Parent_Activity_ID) { if (Parent_Activity_ID < 1) set_Value (COLUMNNAME_Parent_Activity_ID, null); else set_Value (COLUMNNAME_Parent_Activity_ID, Integer.valueOf(Parent_Activity_ID)); } /** Get Hauptkostenstelle. @return Hauptkostenstelle */ @Override public int getParent_Activity_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_Activity_ID); if (ii == null) return 0; return ii.intValue(); } /** 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_C_Activity.java
1
请完成以下Java代码
public int getC_Invoice_Verification_Run_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Run_ID); } @Override public org.compiere.model.I_C_Invoice_Verification_Set getC_Invoice_Verification_Set() { return get_ValueAsPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class); } @Override public void setC_Invoice_Verification_Set(final org.compiere.model.I_C_Invoice_Verification_Set C_Invoice_Verification_Set) { set_ValueFromPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class, C_Invoice_Verification_Set); } @Override public void setC_Invoice_Verification_Set_ID (final int C_Invoice_Verification_Set_ID) { if (C_Invoice_Verification_Set_ID < 1) set_Value (COLUMNNAME_C_Invoice_Verification_Set_ID, null); else set_Value (COLUMNNAME_C_Invoice_Verification_Set_ID, C_Invoice_Verification_Set_ID); } @Override public int getC_Invoice_Verification_Set_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Set_ID); } @Override public void setDateEnd (final @Nullable java.sql.Timestamp DateEnd) { set_ValueNoCheck (COLUMNNAME_DateEnd, DateEnd); } @Override public java.sql.Timestamp getDateEnd() { return get_ValueAsTimestamp(COLUMNNAME_DateEnd); } @Override public void setDateStart (final @Nullable java.sql.Timestamp DateStart) { set_ValueNoCheck (COLUMNNAME_DateStart, DateStart); } @Override public java.sql.Timestamp getDateStart() { return get_ValueAsTimestamp(COLUMNNAME_DateStart); } @Override public void setMovementDate_Override (final @Nullable java.sql.Timestamp MovementDate_Override) { set_Value (COLUMNNAME_MovementDate_Override, MovementDate_Override); } @Override public java.sql.Timestamp getMovementDate_Override()
{ return get_ValueAsTimestamp(COLUMNNAME_MovementDate_Override); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } /** * Status AD_Reference_ID=541324 * Reference name: Invoice Verification Run Status */ public static final int STATUS_AD_Reference_ID=541324; /** Planned = P */ public static final String STATUS_Planned = "P"; /** Running = R */ public static final String STATUS_Running = "R"; /** Finished = F */ public static final String STATUS_Finished = "F"; @Override public void setStatus (final java.lang.String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_Run.java
1
请在Spring Boot框架中完成以下Java代码
public String getText() { return text; } /** * Sets the value of the text property. * * @param value * allowed object is * {@link String } * */ public void setText(String value) { this.text = value; } /** * Gets the value of the agencyCode property. * * @return * possible object is * {@link String } * */ public String getAgencyCode() { return agencyCode; } /** * Sets the value of the agencyCode property. * * @param value * allowed object is * {@link String } * */
public void setAgencyCode(String value) { this.agencyCode = value; } /** * Gets the value of the language property. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\FreeTextType.java
2
请在Spring Boot框架中完成以下Java代码
public void setCOUNTRY(String value) { this.country = value; } /** * Gets the value of the locationcode property. * * @return * possible object is * {@link String } * */ public String getLOCATIONCODE() { return locationcode; } /** * Sets the value of the locationcode property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the drfad1 property. * * @return * possible object is * {@link DRFAD1 } * */
public DRFAD1 getDRFAD1() { return drfad1; } /** * Sets the value of the drfad1 property. * * @param value * allowed object is * {@link DRFAD1 } * */ public void setDRFAD1(DRFAD1 value) { this.drfad1 = value; } /** * Gets the value of the dctad1 property. * * @return * possible object is * {@link DCTAD1 } * */ public DCTAD1 getDCTAD1() { return dctad1; } /** * Sets the value of the dctad1 property. * * @param value * allowed object is * {@link DCTAD1 } * */ public void setDCTAD1(DCTAD1 value) { this.dctad1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DADRE1.java
2
请完成以下Java代码
public class CompositeScriptScanner extends AbstractRecursiveScriptScanner { private final List<IScriptScanner> children = new ArrayList<IScriptScanner>(); private int currentIndex = -1; public CompositeScriptScanner(final IScriptScanner parentScanner) { super(parentScanner); } public CompositeScriptScanner() { this(null); } @Override public String toString() { return getClass().getSimpleName() + "[" + children + "]"; } public CompositeScriptScanner addScriptScanner(final IScriptScanner scriptScanner) { if (scriptScanner == null) { throw new IllegalArgumentException("scriptScanner is null"); } if (children.contains(scriptScanner)) { return this; }
children.add(scriptScanner); return this; } @Override protected IScriptScanner retrieveNextChildScriptScanner() { final int nextIndex = currentIndex + 1; if (nextIndex >= children.size()) { return null; } final IScriptScanner nextScanner = children.get(nextIndex); currentIndex = nextIndex; return nextScanner; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\CompositeScriptScanner.java
1
请在Spring Boot框架中完成以下Java代码
public TokenStore jwtTokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter(); accessTokenConverter.setSigningKey("test_key"); return accessTokenConverter; } @Override 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
请在Spring Boot框架中完成以下Java代码
public class RoutingKeyDLQAmqpConfiguration { public static final String DLX_EXCHANGE_MESSAGES = QUEUE_MESSAGES + ".dlx"; @Bean Queue messagesQueue() { return QueueBuilder.durable(QUEUE_MESSAGES) .withArgument("x-dead-letter-exchange", DLX_EXCHANGE_MESSAGES) .build(); } @Bean FanoutExchange deadLetterExchange() { return new FanoutExchange(DLX_EXCHANGE_MESSAGES); } @Bean Queue deadLetterQueue() { return QueueBuilder.durable(QUEUE_MESSAGES_DLQ).build(); }
@Bean Binding deadLetterBinding() { return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()); } @Bean DirectExchange messagesExchange() { return new DirectExchange(EXCHANGE_MESSAGES); } @Bean Binding bindingMessages() { return BindingBuilder.bind(messagesQueue()).to(messagesExchange()).with(QUEUE_MESSAGES); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\errorhandling\configuration\RoutingKeyDLQAmqpConfiguration.java
2
请完成以下Java代码
public IQualityInspectionOrder getQualityInspectionOrderOrNull() { final List<IQualityInspectionOrder> qualityInspectionOrders = getQualityInspectionOrders(); if (qualityInspectionOrders.isEmpty()) { return null; } // as of now, return the last one // TODO: consider returning an aggregated/averaged one return qualityInspectionOrders.get(qualityInspectionOrders.size() - 1); } @Override public void linkModelToMaterialTracking(final Object model) {
final I_M_Material_Tracking materialTracking = getM_Material_Tracking(); materialTrackingBL.linkModelToMaterialTracking( MTLinkRequest.builder() .model(model) .materialTrackingRecord(materialTracking) .build()); } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocuments.java
1
请完成以下Java代码
private boolean isCompleteOrderDeliveryRule(final ShipmentScheduleWithHU candidate) { final DeliveryRule deliveryRule = shipmentScheduleEffectiveValuesBL.getDeliveryRule(candidate.getM_ShipmentSchedule()); return deliveryRule.isCompleteOrder(); } private boolean isCompletelyDelivered(final ShipmentScheduleWithHU candidate) { final I_M_ShipmentSchedule shipmentSchedule = candidate.getM_ShipmentSchedule(); final BigDecimal qtyOrdered = shipmentScheduleEffectiveValuesBL.computeQtyOrdered(shipmentSchedule); final BigDecimal qtyToDeliver = shipmentScheduleEffectiveValuesBL.getQtyToDeliverBD(shipmentSchedule); final BigDecimal qtyDelivered = shipmentSchedule.getQtyDelivered(); final BigDecimal qtyDeliveredProjected = qtyDelivered.add(qtyToDeliver); return qtyOrdered.compareTo(qtyDeliveredProjected) <= 0; } @ToString private static class Order { @Getter private final OrderId orderId;
private final Set<ShipmentScheduleId> shipmentScheduleIds = new HashSet<>(); @Getter @Setter private boolean completeOrderDeliveryRequired; public Order(@NonNull final OrderId orderId) { this.orderId = orderId; } public void addShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId) { shipmentScheduleIds.add(shipmentScheduleId); } public Set<ShipmentScheduleId> getMissingShipmentScheduleIds(final Set<ShipmentScheduleId> allShipmentScheduleIds) { return Sets.difference(allShipmentScheduleIds, shipmentScheduleIds); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\CompleteOrderDeliveryRuleChecker.java
1
请完成以下Java代码
public abstract class AbstractAuthenticationProvider implements AuthenticationProvider { private final CustomerService customerService; private final UserAuthDetailsCache userAuthDetailsCache; protected SecurityUser authenticateByPublicId(String publicId, String authContextName, UserPrincipal userPrincipal) { TenantId systemId = TenantId.SYS_TENANT_ID; CustomerId customerId; try { customerId = new CustomerId(UUID.fromString(publicId)); } catch (Exception e) { throw new BadCredentialsException(authContextName + " is not valid"); } Customer publicCustomer = customerService.findCustomerById(systemId, customerId); if (publicCustomer == null) { throw new UsernameNotFoundException("Public entity not found"); } if (!publicCustomer.isPublic()) { throw new BadCredentialsException(authContextName + " is not valid"); } User user = new User(new UserId(EntityId.NULL_UUID)); user.setTenantId(publicCustomer.getTenantId()); user.setCustomerId(publicCustomer.getId()); user.setEmail(publicId); user.setAuthority(Authority.CUSTOMER_USER);
user.setFirstName("Public"); user.setLastName("Public"); UserPrincipal principal = userPrincipal == null ? new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, publicId) : userPrincipal; return new SecurityUser(user, true, principal); } protected SecurityUser authenticateByUserId(TenantId tenantId, UserId userId) { UserAuthDetails userAuthDetails = userAuthDetailsCache.getUserAuthDetails(tenantId, userId); if (userAuthDetails == null) { throw new UsernameNotFoundException("User with credentials not found"); } if (!userAuthDetails.credentialsEnabled()) { throw new DisabledException("User is not active"); } User user = userAuthDetails.user(); if (user.getAuthority() == null) { throw new InsufficientAuthenticationException("User has no authority assigned"); } UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); return new SecurityUser(user, true, userPrincipal); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\AbstractAuthenticationProvider.java
1
请完成以下Java代码
public class HistoricDetailEventEntity extends HistoryEvent { private static final long serialVersionUID = 1L; protected String activityInstanceId; protected String taskId; protected Date timestamp; protected String tenantId; protected String userOperationId; // getters and setters ////////////////////////////////////////////////////// public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public String getUserOperationId() { return userOperationId; } public void setUserOperationId(String userOperationId) { this.userOperationId = userOperationId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); } @Override public String toString() { return this.getClass().getSimpleName() + "[activityInstanceId=" + activityInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", id=" + id + ", tenantId=" + tenantId + ", userOperationId=" + userOperationId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDetailEventEntity.java
1
请完成以下Java代码
public CostAmount divide( @NonNull final BigDecimal divisor, @NonNull final CurrencyPrecision precision) { if (divisor.signum() == 0) { throw new AdempiereException("Diving " + this + " by ZERO is not allowed"); } final Money valueNew = value.divide(divisor, precision); final Money sourceValueNew = sourceValue != null ? sourceValue.divide(divisor, precision) : null; return new CostAmount(valueNew, sourceValueNew); } public CostAmount divide( @NonNull final Quantity divisor, @NonNull final CurrencyPrecision precision) { return divide(divisor.toBigDecimal(), precision); } public Optional<CostAmount> divideIfNotZero( @NonNull final Quantity divisor, @NonNull final CurrencyPrecision precision) { return divisor.isZero() ? Optional.empty() : Optional.of(divide(divisor, precision)); } public CostAmount round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider) { final Money valueNew = value.round(precisionProvider); final Money sourceValueNew = sourceValue != null ? sourceValue.round(precisionProvider) : null; if (Money.equals(value, valueNew) && Money.equals(sourceValue, sourceValueNew)) { return this; } else { return new CostAmount(valueNew, sourceValueNew); } } public CostAmount roundToPrecisionIfNeeded(final CurrencyPrecision precision) { final Money valueRounded = value.roundIfNeeded(precision); if (Money.equals(value, valueRounded)) { return this; } else { return new CostAmount(valueRounded, sourceValue); } } public CostAmount roundToCostingPrecisionIfNeeded(final AcctSchema acctSchema) { final AcctSchemaCosting acctSchemaCosting = acctSchema.getCosting(); final CurrencyPrecision precision = acctSchemaCosting.getCostingPrecision(); return roundToPrecisionIfNeeded(precision); } @NonNull public CostAmount subtract(@NonNull final CostAmount amtToSubtract) { assertCurrencyMatching(amtToSubtract); if (amtToSubtract.isZero())
{ return this; } return add(amtToSubtract.negate()); } public CostAmount toZero() { if (isZero()) { return this; } else { return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null); } } public Money toMoney() { return value; } @Nullable public Money toSourceMoney() { return sourceValue; } public BigDecimal toBigDecimal() {return value.toBigDecimal();} public boolean compareToEquals(@NonNull final CostAmount other) { return this.value.compareTo(other.value) == 0; } public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts) { return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
public Set<Author> getAuthors() { return authors; } public void removeAuthor(Author author) { this.authors.remove(author); author.getBooks().remove(this); } public void addAuthor(Author author) { authors.add(author); author.getBooks().add(this); } }
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\manytomanyremoval\Book.java
1
请完成以下Java代码
public void setM_BOMAlternative_ID (int M_BOMAlternative_ID) { if (M_BOMAlternative_ID < 1) set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, null); else set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, Integer.valueOf(M_BOMAlternative_ID)); } /** Get Alternative Group. @return Product BOM Alternative Group */ public int getM_BOMAlternative_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMAlternative.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { CommandContext commandContext = Context.getCommandContext(); MessageEventSubscriptionEntity subscription = messageExecutionContext.createMessageEventSubscription( commandContext, execution ); if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createMessageWaitingEvent( execution, subscription.getEventName(), subscription.getConfiguration() ) ); } } @Override public void trigger(DelegateExecution execution, String triggerName, Object triggerData) { ExecutionEntity executionEntity = deleteMessageEventSubScription(execution); leaveIntermediateCatchEvent(executionEntity); } @Override public void eventCancelledByEventGateway(DelegateExecution execution) { deleteMessageEventSubScription(execution); Context.getCommandContext() .getExecutionEntityManager() .deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL); } protected ExecutionEntity deleteMessageEventSubScription(DelegateExecution execution) { ExecutionEntity executionEntity = (ExecutionEntity) execution; // Should we use triggerName and triggerData, because message name expression can change? String messageName = messageExecutionContext.getMessageName(execution); EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager();
List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageName) ) { eventSubscriptionEntityManager.delete(eventSubscription); } } return executionEntity; } public MessageEventDefinition getMessageEventDefinition() { return messageEventDefinition; } public MessageExecutionContext getMessageExecutionContext() { return messageExecutionContext; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateCatchMessageEventActivityBehavior.java
1
请完成以下Java代码
private void fetchSelectedContacts(InfoSimple info, List<BPartnerContact> list) { final int rows = info.getRowCount(); for (int row = 0; row < rows; row++) { if (!info.isDataRow(row)) continue; if (info.isSelected(row)) { int bpartnerId = info.getValueAsInt(row, I_C_BPartner.COLUMNNAME_C_BPartner_ID); int userId = info.getValueAsInt(row, I_AD_User.COLUMNNAME_AD_User_ID); list.add(new BPartnerContact(bpartnerId, userId)); } } } /** * Refresh all included tabs * * @param mTab * parent tab */ private void refreshIncludedTabs(GridTab mTab) { for (GridTab detailTab : mTab.getIncludedTabs()) { detailTab.dataRefreshAll(); } } public static class BPartnerContact { private final int C_BPartner_ID; private final int AD_User_ID; public BPartnerContact(int cBPartnerID, int aDUserID) { super(); C_BPartner_ID = cBPartnerID; AD_User_ID = aDUserID; }
public int getC_BPartner_ID() { return C_BPartner_ID; } public int getAD_User_ID() { return AD_User_ID; } @Override public String toString() { return "BPartnerContact [C_BPartner_ID=" + C_BPartner_ID + ", AD_User_ID=" + AD_User_ID + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CalloutR_Group.java
1
请在Spring Boot框架中完成以下Java代码
protected String getMybatisCfgPath() { return EventRegistryEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE; } @Override public void configure(AbstractEngineConfiguration engineConfiguration) { if (eventEngineConfiguration == null) { eventEngineConfiguration = new StandaloneEventRegistryEngineConfiguration(); } initialiseEventRegistryEngineConfiguration(eventEngineConfiguration); initialiseCommonProperties(engineConfiguration, eventEngineConfiguration); initEngine(); initServiceConfigurations(engineConfiguration, eventEngineConfiguration); } protected void initialiseEventRegistryEngineConfiguration(EventRegistryEngineConfiguration eventRegistryEngineConfiguration) { // meant to be overridden } @Override protected List<Class<? extends Entity>> getEntityInsertionOrder() { return EntityDependencyOrder.INSERT_ORDER; } @Override protected List<Class<? extends Entity>> getEntityDeletionOrder() { return EntityDependencyOrder.DELETE_ORDER; } @Override
protected EventRegistryEngine buildEngine() { if (eventEngineConfiguration == null) { throw new FlowableException("EventRegistryEngineConfiguration is required"); } return eventEngineConfiguration.buildEventRegistryEngine(); } public EventRegistryEngineConfiguration getEventEngineConfiguration() { return eventEngineConfiguration; } public EventRegistryEngineConfigurator setEventEngineConfiguration(EventRegistryEngineConfiguration eventEngineConfiguration) { this.eventEngineConfiguration = eventEngineConfiguration; return this; } public EventRegistryEngine getEventRegistryEngine() { return buildEngine; } public void setEventRegistryEngine(EventRegistryEngine eventRegistryEngine) { this.buildEngine = eventRegistryEngine; } }
repos\flowable-engine-main\modules\flowable-event-registry-configurator\src\main\java\org\flowable\eventregistry\impl\configurator\EventRegistryEngineConfigurator.java
2
请完成以下Java代码
public I_C_BPartner getC_BPartner() throws RuntimeException { return (I_C_BPartner)MTable.get(getCtx(), I_C_BPartner.Table_Name) .getPO(getC_BPartner_ID(), get_TrxName()); } /** Set Business Partner . @param C_BPartner_ID Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Prepayment_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Prepayment_Acct(), get_TrxName()); } /** Set Customer Prepayment. @param C_Prepayment_Acct Account for customer prepayments */ public void setC_Prepayment_Acct (int C_Prepayment_Acct) { set_Value (COLUMNNAME_C_Prepayment_Acct, Integer.valueOf(C_Prepayment_Acct)); } /** Get Customer Prepayment. @return Account for customer prepayments */ public int getC_Prepayment_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Prepayment_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Receivable_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Receivable_Acct(), get_TrxName()); } /** Set Customer Receivables. @param C_Receivable_Acct Account for Customer Receivables */ public void setC_Receivable_Acct (int C_Receivable_Acct)
{ set_Value (COLUMNNAME_C_Receivable_Acct, Integer.valueOf(C_Receivable_Acct)); } /** Get Customer Receivables. @return Account for Customer Receivables */ public int getC_Receivable_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getC_Receivable_Services_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getC_Receivable_Services_Acct(), get_TrxName()); } /** Set Receivable Services. @param C_Receivable_Services_Acct Customer Accounts Receivables Services Account */ public void setC_Receivable_Services_Acct (int C_Receivable_Services_Acct) { set_Value (COLUMNNAME_C_Receivable_Services_Acct, Integer.valueOf(C_Receivable_Services_Acct)); } /** Get Receivable Services. @return Customer Accounts Receivables Services Account */ public int getC_Receivable_Services_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Receivable_Services_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Customer_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public class ShpController { @Autowired private ShpService shpService; @GetMapping("/hello") public String sayHello(){ return "Hello Appleyk's Controller !"; } /** * 写一个shp文件 * @param shpInfo * @return * @throws Exception */ @PostMapping("/write") public ResponseResult write(@RequestBody ShpInfo shpInfo) throws Exception{ return shpService.writeShp(shpInfo); } /** * 查询一个shp文件 * @param shpFilePath 文件绝对路径 * @param limit 指定显示多少条shp特征【features】 * @return * @throws Exception */ @GetMapping("/query") public ResponseResult query(@RequestParam(value = "path",required = true) String shpFilePath, @RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit ) throws Exception{ return shpService.getShpDatas(shpFilePath,limit); }
/** * 将shp文件转换成png图片,图片或写入文件或通过response输出到界面【比如,客户端浏览器】 * @param path shp文件路径 * @param imagePath 如果imagePath不等于空,则shp文件转成图片文件存储进行存 * @param color 渲染颜色 */ @GetMapping("/show") public void show(@RequestParam(value = "path",required = true) String path, @RequestParam(value = "imagePath",required = false) String imagePath, @RequestParam(value = "color",required = false) String color, HttpServletResponse response) throws Exception{ // 设置响应消息的类型 response.setContentType("image/png"); // 设置页面不缓存 response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); shpService.showShp(path, imagePath,color ,response); } }
repos\springboot-demo-master\GeoTools\src\main\java\com\et\geotools\controller\ShpController.java
2
请完成以下Java代码
public TbQueueProducer<TbProtoQueueMsg<ToTransportMsg>> getTransportNotificationsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> getRuleEngineMsgProducer() { return toRuleEngine; } @Override public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> getTbCoreMsgProducer() { return toTbCore; } @Override public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineNotificationMsg>> getRuleEngineNotificationsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> getTbCoreNotificationsMsgProducer() { return toTbCoreNotifications; } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!");
} @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() { return toUsageStats; } @Override public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() { return toHousekeeper; } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } @Override public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() { throw new RuntimeException("Not Implemented! Should not be used by Transport!"); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbTransportQueueProducerProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class InstructorController { @Autowired private InstructorRepository instructorRepository; @GetMapping("/instructors") public List<Instructor> getInstructors() { return instructorRepository.findAll(); } @GetMapping("/instructors/{id}") public ResponseEntity<Instructor> getInstructorById( @PathVariable(value = "id") Long instructorId) throws ResourceNotFoundException { Instructor user = instructorRepository.findById(instructorId) .orElseThrow(() -> new ResourceNotFoundException("Instructor not found :: " + instructorId)); return ResponseEntity.ok().body(user); } @PostMapping("/instructors") public Instructor createUser(@Valid @RequestBody Instructor instructor) { return instructorRepository.save(instructor); } @PutMapping("/instructors/{id}") public ResponseEntity<Instructor> updateUser( @PathVariable(value = "id") Long instructorId, @Valid @RequestBody Instructor userDetails) throws ResourceNotFoundException { Instructor user = instructorRepository.findById(instructorId) .orElseThrow(() -> new ResourceNotFoundException("Instructor not found :: " + instructorId)); user.setEmail(userDetails.getEmail());
final Instructor updatedUser = instructorRepository.save(user); return ResponseEntity.ok(updatedUser); } @DeleteMapping("/instructors/{id}") public Map<String, Boolean> deleteUser( @PathVariable(value = "id") Long instructorId) throws ResourceNotFoundException { Instructor instructor = instructorRepository.findById(instructorId) .orElseThrow(() -> new ResourceNotFoundException("Instructor not found :: " + instructorId)); instructorRepository.delete(instructor); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-jpa-one-to-one-example\src\main\java\net\alanbinu\springboot\jpa\controller\InstructorController.java
2
请在Spring Boot框架中完成以下Java代码
public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } /** * An auto-configured {@link AnnotationRepositoryConfigurationSource}. */ private class AutoConfiguredAnnotationRepositoryConfigurationSource extends AnnotationRepositoryConfigurationSource {
AutoConfiguredAnnotationRepositoryConfigurationSource(AnnotationMetadata metadata, Class<? extends Annotation> annotation, ResourceLoader resourceLoader, Environment environment, BeanDefinitionRegistry registry, @Nullable BeanNameGenerator generator) { super(metadata, annotation, resourceLoader, environment, registry, generator); } @Override public Streamable<String> getBasePackages() { return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages(); } @Override public BootstrapMode getBootstrapMode() { return AbstractRepositoryConfigurationSourceSupport.this.getBootstrapMode(); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\data\AbstractRepositoryConfigurationSourceSupport.java
2
请在Spring Boot框架中完成以下Java代码
public void checkQueryOk() { super.checkQueryOk(); // latest() makes only sense when used with key() or keyLike() if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){ throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)"); } } // getters //////////////////////////////////////////// public String getId() { return id; } public String[] getIds() { return ids; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getDeploymentId() { return deploymentId; }
public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public Integer getVersion() { return version; } public boolean isLatest() { return latest; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionRequirementsDefinitionQueryImpl.java
2
请完成以下Java代码
private static UserId extractCurrentResponsibleId(final I_DD_Order ddOrder) { return UserId.ofRepoIdOrNullIfSystem(ddOrder.getAD_User_Responsible_ID()); } public void unassignFromResponsible(final DDOrderId ddOrderId) { final I_DD_Order ddOrder = getById(ddOrderId); unassignFromResponsibleAndSave(ddOrder); } public void removeAllNotStartedSchedules(final DDOrderId ddOrderId) { ddOrderMoveScheduleService.removeNotStarted(ddOrderId); } private void unassignFromResponsibleAndSave(final I_DD_Order ddOrder)
{ ddOrder.setAD_User_Responsible_ID(-1); save(ddOrder); } public Set<ProductId> getProductIdsByDDOrderIds(final Collection<DDOrderId> ddOrderIds) { return ddOrderLowLevelDAO.getProductIdsByDDOrderIds(ddOrderIds); } public Stream<I_DD_OrderLine> streamLinesByDDOrderIds(@NonNull final Collection<DDOrderId> ddOrderIds) { return ddOrderLowLevelDAO.streamLinesByDDOrderIds(ddOrderIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\DDOrderService.java
1
请在Spring Boot框架中完成以下Java代码
public class WebFluxConfiguration implements WebFluxConfigurer { @Bean public GlobalResponseBodyHandler responseWrapper(ServerCodecConfigurer serverCodecConfigurer, RequestedContentTypeResolver requestedContentTypeResolver) { return new GlobalResponseBodyHandler(serverCodecConfigurer.getWriters(), requestedContentTypeResolver); } // @Override // public void addCorsMappings(CorsRegistry registry) { // // 添加全局的 CORS 配置 // registry.addMapping("/**") // 匹配所有 URL ,相当于全局配置 // .allowedOrigins("*") // 允许所有请求来源 // .allowCredentials(true) // 允许发送 Cookie // .allowedMethods("*") // 允许所有请求 Method // .allowedHeaders("*") // 允许所有请求 Header //// .exposedHeaders("*") // 允许所有响应 Header // .maxAge(1800L); // 有效期 1800 秒,2 小时 // } @Bean @Order(0) // 设置 order 排序。这个顺序很重要哦,为避免麻烦请设置在最前 public CorsWebFilter corsFilter() { // 创建 UrlBasedCorsConfigurationSource 配置源,类似 CorsRegistry 注册表 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 创建 CorsConfiguration 配置,相当于 CorsRegistration 注册信息 CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("*")); // 允许所有请求来源 config.setAllowCredentials(true); // 允许发送 Cookie config.addAllowedMethod("*"); // 允许所有请求 Method config.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求 Header // config.setExposedHeaders(Collections.singletonList("*")); // 允许所有响应 Header config.setMaxAge(1800L); // 有效期 1800 秒,2 小时 source.registerCorsConfiguration("/**", config); // 创建 CorsWebFilter 对象 return new CorsWebFilter(source); // 创建 CorsFilter 过滤器 } // @Override // public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { // configurer.registerDefaults(false); // configurer.customCodecs().decoder(new Jaxb2XmlDecoder()); // <- here // configurer.customCodecs().encoder(new Jaxb2XmlEncoder()); // <- here // } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\config\WebFluxConfiguration.java
2
请完成以下Java代码
public String getServerID () { return "AlertProcessor" + get_ID(); } // getServerID /** * Get Date Next Run * @param requery requery * @return date next run */ @Override public Timestamp getDateNextRun (boolean requery) { if (requery) load(get_TrxName()); return getDateNextRun(); } // getDateNextRun /** * Get Logs * @return logs */ @Override public AdempiereProcessorLog[] getLogs () { ArrayList<MAlertProcessorLog> list = new ArrayList<>(); String sql = "SELECT * " + "FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=? " + "ORDER BY Created DESC"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlertProcessorLog (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } MAlertProcessorLog[] retValue = new MAlertProcessorLog[list.size ()]; list.toArray (retValue); return retValue; } // getLogs /** * Delete old Request Log * @return number of records */ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=" + getAD_AlertProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog /** * Get Alerts * @param reload reload data * @return array of alerts */ public MAlert[] getAlerts (boolean reload) { MAlert[] alerts = s_cacheAlerts.get(get_ID());
if (alerts != null && !reload) return alerts; String sql = "SELECT * FROM AD_Alert " + "WHERE AD_AlertProcessor_ID=? AND IsActive='Y' "; ArrayList<MAlert> list = new ArrayList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlert (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } // alerts = new MAlert[list.size ()]; list.toArray (alerts); s_cacheAlerts.put(get_ID(), alerts); return alerts; } // getAlerts @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MAlertProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessor.java
1
请完成以下Java代码
public void setStatusCode (java.lang.String StatusCode) { set_ValueNoCheck (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } /** * StepType AD_Reference_ID=53313 * Reference name: Migration step type */ public static final int STEPTYPE_AD_Reference_ID=53313; /** Application Dictionary = AD */ public static final String STEPTYPE_ApplicationDictionary = "AD"; /** SQL Statement = SQL */ public static final String STEPTYPE_SQLStatement = "SQL"; /** Set Step type. @param StepType Migration step type */ @Override public void setStepType (java.lang.String StepType) { set_ValueNoCheck (COLUMNNAME_StepType, StepType); } /** Get Step type. @return Migration step type */ @Override public java.lang.String getStepType ()
{ return (java.lang.String)get_Value(COLUMNNAME_StepType); } /** Set Name der DB-Tabelle. @param TableName Name der DB-Tabelle */ @Override public void setTableName (java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } /** Get Name der DB-Tabelle. @return Name der DB-Tabelle */ @Override public java.lang.String getTableName () { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationStep.java
1
请完成以下Java代码
public String getSignalRef() { return signalRef; } public void setSignalRef(String signalRef) { this.signalRef = signalRef; } public String getSignalExpression() { return signalExpression; } public void setSignalExpression(String signalExpression) { this.signalExpression = signalExpression; } public boolean isAsync() { return async; }
public void setAsync(boolean async) { this.async = async; } @Override public SignalEventDefinition clone() { SignalEventDefinition clone = new SignalEventDefinition(); clone.setValues(this); return clone; } public void setValues(SignalEventDefinition otherDefinition) { super.setValues(otherDefinition); setSignalRef(otherDefinition.getSignalRef()); setSignalExpression(otherDefinition.getSignalExpression()); setAsync(otherDefinition.isAsync()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SignalEventDefinition.java
1
请完成以下Java代码
public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location) { set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location); } /** Set Standort. @param C_BPartner_Location_ID Identifiziert die (Liefer-) Adresse des Geschäftspartners */ @Override public void setC_BPartner_Location_ID (int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID)); } /** Get Standort. @return Identifiziert die (Liefer-) Adresse des Geschäftspartners */ @Override public int getC_BPartner_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Body. @param LetterBody Body */ @Override public void setLetterBody (java.lang.String LetterBody) { set_Value (COLUMNNAME_LetterBody, LetterBody); } /** Get Body. @return Body */ @Override public java.lang.String getLetterBody ()
{ return (java.lang.String)get_Value(COLUMNNAME_LetterBody); } /** Set Subject. @param LetterSubject Subject */ @Override public void setLetterSubject (java.lang.String LetterSubject) { set_Value (COLUMNNAME_LetterSubject, LetterSubject); } /** Get Subject. @return Subject */ @Override public java.lang.String getLetterSubject () { return (java.lang.String)get_Value(COLUMNNAME_LetterSubject); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_T_Letter_Spool.java
1
请完成以下Java代码
public static LocalDateTime toLocalDateTime(Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } /** * 日期 格式化 * * @param localDateTime / * @param patten / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) { DateTimeFormatter df = DateTimeFormatter.ofPattern(patten); return df.format(localDateTime); } /** * 日期 格式化 * * @param localDateTime / * @param df / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) { return df.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return / */ public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) { return DFY_MD_HMS.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd * * @param localDateTime / * @return / */ public String localDateTimeFormatyMd(LocalDateTime localDateTime) { return DFY_MD.format(localDateTime); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd *
* @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) { return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) { return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime)); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java
1
请完成以下Java代码
protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } // allow for subclasses to expose a real id ///////////////////////////////// public String getId() { return String.valueOf(System.identityHashCode(this)); } // getters and setters ////////////////////////////////////////////////////// protected VariableStore<CoreVariableInstance> getVariableStore() { return variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } public ExecutionImpl getReplacedBy() { return (ExecutionImpl) replacedBy; } public void setExecutions(List<ExecutionImpl> executions) { this.executions = executions; } public String getCurrentActivityName() { String currentActivityName = null; if (this.activity != null) { currentActivityName = (String) activity.getProperty("name"); } return currentActivityName; } public FlowElement getBpmnModelElementInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl"); } public BpmnModelInstance getBpmnModelInstance() { throw new UnsupportedOperationException(BpmnModelExecutionContext.class.getName() +" is unsupported in transient ExecutionImpl");
} public ProcessEngineServices getProcessEngineServices() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); } public ProcessEngine getProcessEngine() { throw new UnsupportedOperationException(ProcessEngineServicesAware.class.getName() +" is unsupported in transient ExecutionImpl"); } public void forceUpdate() { // nothing to do } public void fireHistoricProcessStartEvent() { // do nothing } protected void removeVariablesLocalInternal(){ // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ExecutionImpl.java
1
请完成以下Java代码
public void setGLN (final @Nullable java.lang.String GLN) { set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() { return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); } @Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID); }
@Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_ValueNoCheck (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_HU_PI_Item_Product_Lookup_UPC_v.java
1
请完成以下Java代码
public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } @SuppressWarnings("rawtypes") public DiagramElement getDiagramElement() { Collection<Reference> incomingReferences = getIncomingReferencesByType(DiagramElement.class); for (Reference<?> reference : incomingReferences) { for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) { String referenceIdentifier = reference.getReferenceIdentifier(sourceElement); if (referenceIdentifier != null && referenceIdentifier.equals(getId())) { return (DiagramElement) sourceElement; } } } return null; } @SuppressWarnings("rawtypes") public Collection<Reference> getIncomingReferencesByType(Class<? extends ModelElementInstance> referenceSourceTypeClass) {
Collection<Reference> references = new ArrayList<Reference>(); // we traverse all incoming references in reverse direction for (Reference<?> reference : idAttribute.getIncomingReferences()) { ModelElementType sourceElementType = reference.getReferenceSourceElementType(); Class<? extends ModelElementInstance> sourceInstanceType = sourceElementType.getInstanceType(); // if the referencing element (source element) is a BPMNDI element, dig deeper if (referenceSourceTypeClass.isAssignableFrom(sourceInstanceType)) { references.add(reference); } } return references; } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BaseElementImpl.java
1
请完成以下Java代码
public void onApplicationEvent(EnableBodyCachingEvent event) { this.routesToCache.putIfAbsent(event.getRouteId(), true); } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // the cached ServerHttpRequest is used when the ServerWebExchange can not be // mutated, for example, during a predicate where the body is read, but still // needs to be cached. ServerHttpRequest cachedRequest = exchange.getAttribute(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR); if (cachedRequest != null) { exchange.getAttributes().remove(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR); return chain.filter(exchange.mutate().request(cachedRequest).build()); } // DataBuffer body = exchange.getAttribute(CACHED_REQUEST_BODY_ATTR); Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); if (body != null || route == null || !this.routesToCache.containsKey(route.getId())) { return chain.filter(exchange);
} return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> { // don't mutate and build if same request object if (serverHttpRequest == exchange.getRequest()) { return chain.filter(exchange); } return chain.filter(exchange.mutate().request(serverHttpRequest).build()); }); } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1000; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\AdaptCachedBodyGlobalFilter.java
1
请在Spring Boot框架中完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @ApiModelProperty(example = "testuser") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "John") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @ApiModelProperty(example = "Doe") public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } @ApiModelProperty(example = "John Doe") public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getPassword() { return passWord; } public void setPassword(String passWord) { this.passWord = passWord; } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String orderQuery(String payKey, String orderNo) { logger.info("鉴权记录查询,payKey:[{}],订单号:[{}]", payKey, orderNo); RpUserPayConfig rpUserPayConfig = userPayConfigService.getByPayKey(payKey); if (rpUserPayConfig == null) { throw new UserBizException(UserBizException.USER_PAY_CONFIG_ERRPR, "用户支付配置有误"); } String merchantNo = rpUserPayConfig.getUserNo();// 商户编号 RpUserBankAuth userBankAuth = userBankAuthService.findByMerchantNoAndPayOrderNo(merchantNo, orderNo); JSONObject resultJson = new JSONObject(); if (userBankAuth == null) { resultJson.put("status", "NO"); } else { resultJson.put("status", "YES"); resultJson.put("returnUrl", AuthConfigUtil.AUTH_ORDER_QUERY_URL + userBankAuth.getMerchantNo() + "/" + userBankAuth.getPayOrderNo()); } return resultJson.toJSONString(); }
/** * 获取错误返回信息 * * @param bindingResult * @return */ public String getErrorMsg(BindingResult bindingResult) { StringBuffer sb = new StringBuffer(); for (ObjectError objectError : bindingResult.getAllErrors()) { sb.append(objectError.getDefaultMessage()).append(","); } sb.delete(sb.length() - 1, sb.length()); return sb.toString(); } }
repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\auth\AuthController.java
2
请完成以下Java代码
public Optional<ServerMetrics> getCurrentServerMetrics() { return Optional.ofNullable(this.currentServerMetrics.get()); } /** * Returns the underlying, wrapped {@link ServerLoadProbe} backing this instance. * * @return the underlying, wrapped {@link ServerLoadProbe}. * @see org.apache.geode.cache.server.ServerLoadProbe */ protected ServerLoadProbe getDelegate() { return this.delegate; } @Override public ServerLoad getLoad(ServerMetrics metrics) {
this.currentServerMetrics.set(metrics); return getDelegate().getLoad(metrics); } @Override public void open() { getDelegate().open(); } @Override public void close() { getDelegate().close(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\health\support\ActuatorServerLoadProbeWrapper.java
1
请完成以下Java代码
public void setCdtrSchmeId(PartyIdentificationSEPA3 value) { this.cdtrSchmeId = value; } /** * Gets the value of the drctDbtTxInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the drctDbtTxInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDrctDbtTxInf().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DirectDebitTransactionInformationSDD } * * */ public List<DirectDebitTransactionInformationSDD> getDrctDbtTxInf() { if (drctDbtTxInf == null) { drctDbtTxInf = new ArrayList<DirectDebitTransactionInformationSDD>(); } return this.drctDbtTxInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentInstructionInformationSDD.java
1
请完成以下Java代码
public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public Map<String, TransitionImpl> getSequenceFlows() { return sequenceFlows; } public ProcessDefinitionEntity getCurrentProcessDefinition() { return currentProcessDefinition; } public void setCurrentProcessDefinition(ProcessDefinitionEntity currentProcessDefinition) { this.currentProcessDefinition = currentProcessDefinition; } public FlowElement getCurrentFlowElement() { return currentFlowElement; } public void setCurrentFlowElement(FlowElement currentFlowElement) { this.currentFlowElement = currentFlowElement; } public ActivityImpl getCurrentActivity() { return currentActivity; } public void setCurrentActivity(ActivityImpl currentActivity) { this.currentActivity = currentActivity; } public void setCurrentSubProcess(SubProcess subProcess) { currentSubprocessStack.push(subProcess); } public SubProcess getCurrentSubProcess() { return currentSubprocessStack.peek();
} public void removeCurrentSubProcess() { currentSubprocessStack.pop(); } public void setCurrentScope(ScopeImpl scope) { currentScopeStack.push(scope); } public ScopeImpl getCurrentScope() { return currentScopeStack.peek(); } public void removeCurrentScope() { currentScopeStack.pop(); } public BpmnParse setSourceSystemId(String systemId) { sourceSystemId = systemId; return this; } public String getSourceSystemId() { return this.sourceSystemId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParse.java
1