instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static String getAutoArchiveType(final Properties ctx) { final I_AD_Client client = Services.get(IClientDAO.class).retriveClient(ctx, Env.getAD_Client_ID(ctx)); final String aaClient = client.getAutoArchive(); final String aaRole = null; // role.getAutoArchive(); // TODO String aa = aaClient; if (aa == null) { aa = X_AD_Client.AUTOARCHIVE_None; } if (aaRole != null) { if (aaRole.equals(X_AD_Client.AUTOARCHIVE_AllReportsDocuments)) { aa = aaRole; } else if (aaRole.equals(X_AD_Client.AUTOARCHIVE_Documents) && !aaClient .equals(X_AD_Client.AUTOARCHIVE_AllReportsDocuments)) { aa = aaRole; } } return aa; } @Override public String getContentType(final I_AD_Archive archive) { // NOTE: at this moment we are storing only PDFs return "application/pdf"; } @Override public byte[] getBinaryData(final I_AD_Archive archive) { return archiveStorageFactory.getArchiveStorage(archive).getBinaryData(archive); } @Override public void setBinaryData(final I_AD_Archive archive, final byte[] data) { archiveStorageFactory.getArchiveStorage(archive).setBinaryData(archive, data); } @Override public InputStream getBinaryDataAsStream(final I_AD_Archive archive) { return archiveStorageFactory.getArchiveStorage(archive).getBinaryDataAsStream(archive); } @Override public Optional<AdArchive> getLastArchive( @NonNull final TableRecordReference reference) {
return getLastArchiveRecord(reference).map(this::toAdArchive); } @Override public Optional<I_AD_Archive> getLastArchiveRecord( @NonNull final TableRecordReference reference) { final IArchiveDAO archiveDAO = Services.get(IArchiveDAO.class); final List<I_AD_Archive> lastArchives = archiveDAO.retrieveLastArchives(Env.getCtx(), reference, QueryLimit.ONE); if (lastArchives.isEmpty()) { return Optional.empty(); } else { return Optional.of(lastArchives.get(0)); } } @Override public Optional<Resource> getLastArchiveBinaryData( @NonNull final TableRecordReference reference) { return getLastArchive(reference).map(AdArchive::getArchiveDataAsResource); } @Override public void updatePrintedRecords(final ImmutableSet<ArchiveId> ids, final UserId userId) { archiveDAO.updatePrintedRecords(ids, userId); } private AdArchive toAdArchive(final I_AD_Archive record) { return AdArchive.builder() .id(ArchiveId.ofRepoId(record.getAD_Archive_ID())) .archiveData(getBinaryData(record)) .contentType(getContentType(record)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveBL.java
1
请在Spring Boot框架中完成以下Java代码
public class AgentSyncBL implements IAgentSyncBL { private final SenderToProcurementWeb senderToProcurementWebUI; public AgentSyncBL(@NonNull final SenderToProcurementWeb senderToProcurementWebUI) { this.senderToProcurementWebUI = senderToProcurementWebUI; } @Override public void syncBPartners(@NonNull final PutBPartnersRequest request) { senderToProcurementWebUI.send(request); } @Override public void syncProducts(@NonNull final PutProductsRequest request) { senderToProcurementWebUI.send(request); } @Override public void syncInfoMessage(@NonNull final PutInfoMessageRequest request) { senderToProcurementWebUI.send(request); }
@Override public void confirm(@NonNull final List<SyncConfirmation> syncConfirmations) { senderToProcurementWebUI.send(PutConfirmationToProcurementWebRequest.of(syncConfirmations)); } @Override public void syncRfQs(@NonNull final List<SyncRfQ> syncRfqs) { senderToProcurementWebUI.send(PutRfQsRequest.builder() .syncRfqs(syncRfqs) .build()); } @Override public void closeRfQs(@NonNull final List<SyncRfQCloseEvent> syncRfQCloseEvents) { senderToProcurementWebUI.send(PutRfQCloseEventsRequest.of(syncRfQCloseEvents)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\AgentSyncBL.java
2
请完成以下Java代码
public Quantity getQtyRequired_NegateBecauseIsCOProduct() { return adjustCoProductQty(getQtyRequired()); } /** * @return co product already received (and processed) quantity, so we assume a positive value will be returned */ public Quantity getQtyIssuedOrReceived_NegateBecauseIsCOProduct() { return adjustCoProductQty(getQtyIssuedOrReceived()); } public void assertQtyToIssueToleranceIsRespected() { assertQtyToIssueToleranceIsRespected_LowerBound(qtyIssuedOrReceivedActual); assertQtyToIssueToleranceIsRespected_UpperBound(qtyIssuedOrReceivedActual); } private void assertQtyToIssueToleranceIsRespected_LowerBound(final Quantity qtyIssuedOrReceivedActual) { if (issuingToleranceSpec == null) { return; } final Quantity qtyIssuedOrReceivedActualMin = issuingToleranceSpec.subtractFrom(qtyRequired); if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMin) < 0) { final ITranslatableString qtyStr = TranslatableStrings.builder() .appendQty(qtyIssuedOrReceivedActualMin.toBigDecimal(), qtyIssuedOrReceivedActualMin.getUOMSymbol()) .append(" (") .appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol()) .append(" - ") .append(issuingToleranceSpec.toTranslatableString()) .append(")") .build(); throw new AdempiereException(MSG_CannotIssueLessThan, qtyStr) .markAsUserValidationError(); } }
private void assertQtyToIssueToleranceIsRespected_UpperBound(final Quantity qtyIssuedOrReceivedActual) { if (issuingToleranceSpec == null) { return; } final Quantity qtyIssuedOrReceivedActualMax = issuingToleranceSpec.addTo(qtyRequired); if (qtyIssuedOrReceivedActual.compareTo(qtyIssuedOrReceivedActualMax) > 0) { final ITranslatableString qtyStr = TranslatableStrings.builder() .appendQty(qtyIssuedOrReceivedActualMax.toBigDecimal(), qtyIssuedOrReceivedActualMax.getUOMSymbol()) .append(" (") .appendQty(qtyRequired.toBigDecimal(), qtyRequired.getUOMSymbol()) .append(" + ") .append(issuingToleranceSpec.toTranslatableString()) .append(")") .build(); throw new AdempiereException(MSG_CannotIssueMoreThan, qtyStr) .markAsUserValidationError(); } } @NonNull public OrderBOMLineQuantities convertQuantities(@NonNull final UnaryOperator<Quantity> converter) { return toBuilder() .qtyRequired(converter.apply(qtyRequired)) .qtyRequiredBeforeClose(converter.apply(qtyRequiredBeforeClose)) .qtyIssuedOrReceived(converter.apply(qtyIssuedOrReceived)) .qtyIssuedOrReceivedActual(converter.apply(qtyIssuedOrReceivedActual)) .qtyReject(converter.apply(qtyReject)) .qtyScrap(converter.apply(qtyScrap)) .qtyUsageVariance(converter.apply(qtyUsageVariance)) .qtyPost(converter.apply(qtyPost)) .qtyReserved(converter.apply(qtyReserved)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\OrderBOMLineQuantities.java
1
请完成以下Java代码
public class DeleteProcessInstancesDto { protected List<String> processInstanceIds; protected ProcessInstanceQueryDto processInstanceQuery; protected String deleteReason; protected boolean skipCustomListeners; protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; protected boolean skipSubprocesses; protected boolean skipIoMappings; public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners;
} public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public boolean isSkipSubprocesses() { return skipSubprocesses; } public void setSkipSubprocesses(Boolean skipSubprocesses) { this.skipSubprocesses = skipSubprocesses; } public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\batch\DeleteProcessInstancesDto.java
1
请完成以下Java代码
public final class JsonDocumentCreator { public static final String JSON = "{\"foo\":[\"bar\",null,2.33],\"bar\":{\"hello\":\"world\",\"helloo\":true},\"baz\":\"hello\",\"tada\":[{\"foo\":\"bar\"},{\"baz\":false},\"boo\",{},[]]}"; /** * Private Constructor, not used. */ private JsonDocumentCreator() { throw new AssertionError("Not permitted to call constructor!"); } /** * Create simple test document containing all supported node kinds. * * @param wtx {@link JsonNodeWriteTrx} to write to * @throws SirixException if anything weird happens */ public static void create(final JsonNodeTrx wtx) { wtx.insertObjectAsFirstChild(); wtx.insertObjectRecordAsFirstChild("foo", new ArrayValue()) .insertStringValueAsFirstChild("bar") .insertNullValueAsRightSibling() .insertNumberValueAsRightSibling(2.33); wtx.moveToParent().trx().moveToParent(); wtx.insertObjectRecordAsRightSibling("bar", new ObjectValue()) .insertObjectRecordAsFirstChild("hello", new StringValue("world")) .moveToParent(); wtx.insertObjectRecordAsRightSibling("helloo", new BooleanValue(true)) .moveToParent().trx().moveToParent().trx().moveToParent(); wtx.insertObjectRecordAsRightSibling("baz", new StringValue("hello")) .moveToParent(); wtx.insertObjectRecordAsRightSibling("tada", new ArrayValue()) .insertObjectAsFirstChild() .insertObjectRecordAsFirstChild("foo", new StringValue("bar")) .moveToParent().trx().moveToParent(); wtx.insertObjectAsRightSibling()
.insertObjectRecordAsFirstChild("baz", new BooleanValue(false)) .moveToParent().trx().moveToParent(); wtx.insertStringValueAsRightSibling("boo") .insertObjectAsRightSibling() .insertArrayAsRightSibling(); wtx.moveToDocumentRoot(); } public static void createVersioned(final JsonNodeTrx wtx) { // Create sample document. JsonDocumentCreator.create(wtx); wtx.commit(); // Add changes and commit a second revision. wtx.moveToDocumentRoot().trx().moveToFirstChild(); wtx.insertObjectRecordAsFirstChild("revision2", new StringValue("yes")); wtx.commit(); // Add changes and commit a third revision. wtx.moveToDocumentRoot().trx().moveToFirstChild().trx().moveToFirstChild(); wtx.insertObjectRecordAsRightSibling("revision3", new StringValue("yes")); wtx.commit(); } }
repos\tutorials-master\persistence-modules\sirix\src\main\java\io\sirix\tutorial\json\JsonDocumentCreator.java
1
请完成以下Java代码
private static byte[] textToNumericFormatV4(String text) { if (text.length() == 0) { return new byte[0]; } byte[] bytes = new byte[4]; String[] elements = text.split("\\.", -1); try { long l; int i; switch (elements.length) { case 1: l = Long.parseLong(elements[0]); if ((l < 0L) || (l > 4294967295L)) { return new byte[0]; } bytes[0] = (byte) (int) (l >> 24 & 0xFF); bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 2: l = Integer.parseInt(elements[0]); if ((l < 0L) || (l > 255L)) { return new byte[0]; } bytes[0] = (byte) (int) (l & 0xFF); l = Integer.parseInt(elements[1]); if ((l < 0L) || (l > 16777215L)) { return new byte[0]; } bytes[1] = (byte) (int) (l >> 16 & 0xFF); bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 3: for (i = 0; i < 2; ++i) { l = Integer.parseInt(elements[i]); if ((l < 0L) || (l > 255L)) { return new byte[0]; } bytes[i] = (byte) (int) (l & 0xFF); } l = Integer.parseInt(elements[2]); if ((l < 0L) || (l > 65535L)) { return new byte[0];
} bytes[2] = (byte) (int) (l >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 4: for (i = 0; i < 4; ++i) { l = Integer.parseInt(elements[i]); if ((l < 0L) || (l > 255L)) { return new byte[0]; } bytes[i] = (byte) (int) (l & 0xFF); } break; default: return new byte[0]; } } catch (NumberFormatException e) { return new byte[0]; } return bytes; } }
repos\springboot-demo-master\ipfilter\src\main\java\com\et\ipfilter\util\AddressUtils.java
1
请在Spring Boot框架中完成以下Java代码
public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @ApiModelProperty(example = "Script task") public String getElementName() { return elementName; } public void setElementName(String elementName) { this.elementName = elementName; } public void setHandlerType(String handlerType) { this.handlerType = handlerType; } @ApiModelProperty(example = "cmmn-trigger-timer") public String getHandlerType() { return handlerType; } @ApiModelProperty(example = "3") public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } @ApiModelProperty(example = "null") public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @ApiModelProperty(example = "2023-06-04T22:05:05.474+0000") public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() {
return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobResponse.java
2
请完成以下Java代码
private I_C_Campaign_Price createCampaignPrice(final I_I_Campaign_Price importRecord) { final I_C_Campaign_Price campaignPrice = InterfaceWrapperHelper.newInstance(I_C_Campaign_Price.class); campaignPrice.setAD_Org_ID(importRecord.getAD_Org_ID()); campaignPrice.setM_Product_ID(importRecord.getM_Product_ID()); campaignPrice.setC_BPartner_ID(importRecord.getC_BPartner_ID()); campaignPrice.setC_BP_Group_ID(importRecord.getC_BP_Group_ID()); campaignPrice.setM_PricingSystem_ID(importRecord.getM_PricingSystem_ID()); campaignPrice.setC_Country_ID(importRecord.getC_Country_ID()); campaignPrice.setC_Currency_ID(importRecord.getC_Currency_ID()); campaignPrice.setC_UOM_ID(importRecord.getC_UOM_ID()); campaignPrice.setC_TaxCategory_ID(importRecord.getC_TaxCategory_ID()); campaignPrice.setPriceStd(importRecord.getPriceStd()); campaignPrice.setValidFrom(importRecord.getValidFrom());
campaignPrice.setValidTo(importRecord.getValidTo()); campaignPrice.setInvoicableQtyBasedOn(importRecord.getInvoicableQtyBasedOn()); //campaignPrice.setDescription("Created via import"); return campaignPrice; } @Override protected void markImported(@NonNull final I_I_Campaign_Price importRecord) { importRecord.setI_IsImported(X_I_Campaign_Price.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\impexp\CampaignPriceImportProcess.java
1
请完成以下Java代码
public class ProductsLoadingCache { @NonNull private final IProductBL productBL; private final HashMap<ProductId, ProductInfo> byId = new HashMap<>(); public <T> void warnUp(final Collection<T> objects, Function<T, ProductId> productIdMapper) { final ImmutableSet<ProductId> productIds = objects.stream().map(productIdMapper).collect(ImmutableSet.toImmutableSet()); getByIds(productIds); } public ProductInfo getById(@NonNull final ProductId productId) { final Collection<ProductInfo> productInfos = getByIds(ImmutableSet.of(productId)); return CollectionUtils.singleElement(productInfos); } private Collection<ProductInfo> getByIds(final Set<ProductId> productIds) { return CollectionUtils.getAllOrLoad(byId, productIds, this::retrieveProductInfos); } private Map<ProductId, ProductInfo> retrieveProductInfos(final Set<ProductId> productIds) { return productBL.getByIds(productIds) .stream() .map(ProductsLoadingCache::fromRecord)
.collect(ImmutableMap.toImmutableMap(ProductInfo::getProductId, productInfo -> productInfo)); } private static ProductInfo fromRecord(final I_M_Product product) { final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(product); return ProductInfo.builder() .productId(productId) .productNo(product.getValue()) .productName(trls.getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\ProductsLoadingCache.java
1
请在Spring Boot框架中完成以下Java代码
public Saml2ResponseAssertionAccessor getCredentials() { return this.assertion; } public String getRelyingPartyRegistrationId() { return this.relyingPartyRegistrationId; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link Saml2AssertionAuthentication} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends Saml2Authentication.Builder<B> { private Saml2ResponseAssertionAccessor assertion; private String relyingPartyRegistrationId; protected Builder(Saml2AssertionAuthentication token) { super(token); this.assertion = token.assertion; this.relyingPartyRegistrationId = token.relyingPartyRegistrationId; } /** * Use these credentials. They must be of type * {@link Saml2ResponseAssertionAccessor}.
* @param credentials the credentials to use * @return the {@link Builder} for further configurations */ @Override public B credentials(@Nullable Object credentials) { Assert.isInstanceOf(Saml2ResponseAssertionAccessor.class, credentials, "credentials must be of type Saml2ResponseAssertionAccessor"); saml2Response(((Saml2ResponseAssertionAccessor) credentials).getResponseValue()); this.assertion = (Saml2ResponseAssertionAccessor) credentials; return (B) this; } /** * Use this registration id * @param relyingPartyRegistrationId the * {@link RelyingPartyRegistration#getRegistrationId} to use * @return the {@link Builder} for further configurations */ public B relyingPartyRegistrationId(String relyingPartyRegistrationId) { this.relyingPartyRegistrationId = relyingPartyRegistrationId; return (B) this; } @Override public Saml2AssertionAuthentication build() { return new Saml2AssertionAuthentication(this); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2AssertionAuthentication.java
2
请完成以下Java代码
public boolean hasTUs(final I_C_Order order) { final Properties ctx = InterfaceWrapperHelper.getCtx(order); final int bpartnerId = order.getC_BPartner_ID(); final int productId = order.getM_Product_ID(); final Date date = order.getDateOrdered(); return hasTUs(ctx, bpartnerId, productId, date); } @Override public boolean hasTUs(final Properties ctx, final int bpartnerId, final int productId, final Date date) { final IHUPIItemProductDAO piItemProductDAO = Services.get(IHUPIItemProductDAO.class); final IHUPIItemProductQuery queryVO = piItemProductDAO.createHUPIItemProductQuery(); queryVO.setC_BPartner_ID(bpartnerId); queryVO.setM_Product_ID(productId); queryVO.setDate(TimeUtil.asZonedDateTime(date)); queryVO.setAllowAnyProduct(false); queryVO.setHU_UnitType(X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit); return piItemProductDAO.matches(ctx, queryVO, ITrx.TRXNAME_None); } @Override public void findM_HU_PI_Item_ProductForForecast(@NonNull final I_M_Forecast forecast, final ProductId productId, final Consumer<I_M_HU_PI_Item_Product> pipConsumer) { final IHUDocumentHandlerFactory huDocumentHandlerFactory = Services.get(IHUDocumentHandlerFactory.class); final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class); if (forecast.getC_BPartner_ID() <= 0 || forecast.getDatePromised() == null) { return; } final IHUDocumentHandler handler = huDocumentHandlerFactory.createHandler(I_M_Forecast.Table_Name); if (null != handler && productId != null) { final I_M_HU_PI_Item_Product overridePip = handler.getM_HU_PI_ItemProductFor(forecast, productId); // If we have a default price and it has an M_HU_PI_Item_Product, suggest it in quick entry. if (null != overridePip && overridePip.getM_HU_PI_Item_Product_ID() > 0) { if (overridePip.isAllowAnyProduct()) { pipConsumer.accept(null); } else { pipConsumer.accept(overridePip); } return; }
} // // Try fetching best matching PIP final I_M_HU_PI_Item_Product pip = hupiItemProductDAO.retrieveMaterialItemProduct( productId, BPartnerId.ofRepoIdOrNull(forecast.getC_BPartner_ID()), TimeUtil.asZonedDateTime(forecast.getDatePromised()), X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true); // allowInfiniteCapacity = true if (pip == null) { // nothing to do, product is not included in any Transport Units return; } else if (pip.isAllowAnyProduct()) { return; } else { pipConsumer.accept(pip); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\HUOrderBL.java
1
请在Spring Boot框架中完成以下Java代码
public DataSize getSizeInDefaultUnit() { return sizeInDefaultUnit; } public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { this.sizeInDefaultUnit = sizeInDefaultUnit; } public DataSize getSizeInGB() { return sizeInGB; } public void setSizeInGB(DataSize sizeInGB) { this.sizeInGB = sizeInGB; } public DataSize getSizeInTB() { return sizeInTB;
} public void setSizeInTB(DataSize sizeInTB) { this.sizeInTB = sizeInTB; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\PropertyConversion.java
2
请在Spring Boot框架中完成以下Java代码
public Boolean hHasKey(String key, String hashKey) { return redisTemplate.opsForHash().hasKey(key, hashKey); } @Override public Long hIncr(String key, String hashKey, Long delta) { return redisTemplate.opsForHash().increment(key, hashKey, delta); } @Override public Long hDecr(String key, String hashKey, Long delta) { return redisTemplate.opsForHash().increment(key, hashKey, -delta); } @Override public Set<Object> sMembers(String key) { return redisTemplate.opsForSet().members(key); } @Override public Long sAdd(String key, Object... values) { return redisTemplate.opsForSet().add(key, values); } @Override public Long sAdd(String key, long time, Object... values) { Long count = redisTemplate.opsForSet().add(key, values); expire(key, time); return count; } @Override public Boolean sIsMember(String key, Object value) { return redisTemplate.opsForSet().isMember(key, value); } @Override public Long sSize(String key) { return redisTemplate.opsForSet().size(key); } @Override public Long sRemove(String key, Object... values) { return redisTemplate.opsForSet().remove(key, values); } @Override public List<Object> lRange(String key, long start, long end) { return redisTemplate.opsForList().range(key, start, end); } @Override public Long lSize(String key) { return redisTemplate.opsForList().size(key); } @Override
public Object lIndex(String key, long index) { return redisTemplate.opsForList().index(key, index); } @Override public Long lPush(String key, Object value) { return redisTemplate.opsForList().rightPush(key, value); } @Override public Long lPush(String key, Object value, long time) { Long index = redisTemplate.opsForList().rightPush(key, value); expire(key, time); return index; } @Override public Long lPushAll(String key, Object... values) { return redisTemplate.opsForList().rightPushAll(key, values); } @Override public Long lPushAll(String key, Long time, Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); expire(key, time); return count; } @Override public Long lRemove(String key, long count, Object value) { return redisTemplate.opsForList().remove(key, count, value); } }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\service\impl\RedisServiceImpl.java
2
请完成以下Java代码
public Long getPassQps() { return passQps; } public void setPassQps(Long passQps) { this.passQps = passQps; } public Long getBlockQps() { return blockQps; } public void setBlockQps(Long blockQps) { this.blockQps = blockQps; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) {
this.exceptionQps = exceptionQps; } public Double getRt() { return rt; } public void setRt(Double rt) { this.rt = rt; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } @Override public int compareTo(MetricVo o) { return Long.compare(this.timestamp, o.timestamp); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\MetricVo.java
1
请在Spring Boot框架中完成以下Java代码
protected final SmooksDataFormat getSDFForConfiguration(final String propertiesConfigurationPath) { final String smooksConfigurationPath = Util.resolveProperty(getContext(), propertiesConfigurationPath); try { return new SmooksDataFormat(smooksConfigurationPath); } catch (final Exception e) { throw new RuntimeCamelException(e); } } /** * @return Decimal format from EDI configuration */ private DecimalFormat getDecimalFormatForConfiguration() { final DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getInstance(); final CamelContext context = getContext(); decimalFormat.setMaximumFractionDigits(Integer.parseInt(Util.resolveProperty(context, "edi.decimalformat.maximumFractionDigits"))); final boolean isGroupingUsed = Boolean.parseBoolean(Util.resolveProperty(context, "edi.decimalformat.isGroupingUsed")); decimalFormat.setGroupingUsed(isGroupingUsed);
final DecimalFormatSymbols decimalFormatSymbols = decimalFormat.getDecimalFormatSymbols(); if (isGroupingUsed) { final char groupingSeparator = Util.resolveProperty(context, "edi.decimalformat.symbol.groupingSeparator").charAt(0); decimalFormatSymbols.setGroupingSeparator(groupingSeparator); } final char decimalSeparator = Util.resolveProperty(context, "edi.decimalformat.symbol.decimalSeparator").charAt(0); decimalFormatSymbols.setDecimalSeparator(decimalSeparator); decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols); // though it seems redundant, it won't be set otherwise for some reason... return decimalFormat; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\route\AbstractEDIRoute.java
2
请完成以下Java代码
public final CustomsInvoiceUserNotificationsProducer notifyGenerated(@NonNull final CustomsInvoice customsInvoice) { notifyGenerated(ImmutableList.of(customsInvoice)); return this; } private final UserNotificationRequest createUserNotification(@NonNull final CustomsInvoice customsInvoice) { final TableRecordReference customsInvoiceRef = toTableRecordRef(customsInvoice); return newUserNotificationRequest() .recipientUserId(getNotificationRecipientUserId(customsInvoice)) .contentADMessage(MSG_Event_CustomsInvoiceGenerated) .contentADMessageParam(customsInvoiceRef) .targetAction(TargetRecordAction.ofRecordAndWindow(customsInvoiceRef, WINDOW_CUSTOMS_INVOICE)) .build(); } private static TableRecordReference toTableRecordRef(final CustomsInvoice customsInvoice) { return TableRecordReference.of(I_C_Customs_Invoice.Table_Name, customsInvoice.getId()); } private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC); } private final UserId getNotificationRecipientUserId(final CustomsInvoice customsInvoice) { // // In case of reversal i think we shall notify the current user too if (customsInvoice.getDocStatus().isReversedOrVoided()) { return customsInvoice.getLastUpdatedBy(); } // // Fallback: notify only the creator else { return customsInvoice.getCreatedBy(); } } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\event\CustomsInvoiceUserNotificationsProducer.java
1
请在Spring Boot框架中完成以下Java代码
private HUQRCodeProductInfo getProductInfo(@Nullable final ProductId productId) { if (productId == null) { return null; } return cache.productInfos.computeIfAbsent(productId, this::computeProductInfo); } private HUQRCodeProductInfo computeProductInfo(final ProductId productId) { final I_M_Product product = productBL.getById(productId); return HUQRCodeProductInfo.builder() .id(productId) .code(product.getValue()) .name(product.getName()) .build(); } private HUQRCodeAttribute toHUQRCodeAttribute(final HUQRCodeGenerateRequest.Attribute request) { final AttributeId attributeId; final I_M_Attribute attribute; if (request.getAttributeId() != null) { attributeId = request.getAttributeId(); attribute = attributeDAO.getAttributeRecordById(attributeId); } else if (request.getCode() != null) { attribute = attributeDAO.retrieveAttributeByValue(request.getCode()); attributeId = AttributeId.ofRepoId(attribute.getM_Attribute_ID()); } else { throw new AdempiereException("Cannot find M_Attribute_ID by " + request); } final String value; final String valueRendered; final AttributeValueType valueType = AttributeValueType.ofCode(attribute.getAttributeValueType()); switch (valueType) { case STRING: value = StringUtils.trimBlankToNull(request.getValueString()); valueRendered = null; break; case NUMBER: value = request.getValueNumber() != null ? request.getValueNumber().toString() : null; valueRendered = null; break; case DATE: value = request.getValueDate() != null ? request.getValueDate().toString() : null; valueRendered = null;
break; case LIST: if (request.getValueListId() != null) { AttributeListValue listItem = attributeDAO.retrieveAttributeValueOrNull(attributeId, request.getValueListId()); if (listItem == null) { throw new AdempiereException("No list item found for attribute " + attributeId + " and list value " + request.getValueListId()); } value = String.valueOf(listItem.getId().getRepoId()); valueRendered = listItem.getName(); } else { value = null; valueRendered = null; } break; default: throw new AdempiereException("Unsupported attribute value type: " + valueType); } return HUQRCodeAttribute.builder() .code(AttributeCode.ofString(attribute.getValue())) .displayName(attribute.getName()) .value(value) .valueRendered(valueRendered) .build(); } // // // public static class Cache { private final HashMap<ProductId, HUQRCodeProductInfo> productInfos = new HashMap<>(); private final HashMap<HuPackingInstructionsId, HUQRCodePackingInfo> packingInfos = new HashMap<>(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateCommand.java
2
请在Spring Boot框架中完成以下Java代码
static class GeodeConfiguration { @Bean("YellowPages") public ReplicatedRegionFactoryBean<String, Person> yellowPagesRegion(GemFireCache gemfireCache, @Qualifier("YellowPagesAttributes") RegionAttributes<String, Person> exampleAttributes) { ReplicatedRegionFactoryBean<String, Person> yellowPagesRegion = new ReplicatedRegionFactoryBean<>(); yellowPagesRegion.setAttributes(exampleAttributes); yellowPagesRegion.setCache(gemfireCache); yellowPagesRegion.setClose(false); yellowPagesRegion.setPersistent(false); return yellowPagesRegion; } @Bean("YellowPagesAttributes") public RegionAttributesFactoryBean<String, Person> exampleRegionAttributes() {
RegionAttributesFactoryBean<String, Person> yellowPagesRegionAttributes = new RegionAttributesFactoryBean<>(); yellowPagesRegionAttributes.setEnableSubscriptionConflation(true); return yellowPagesRegionAttributes; } } // end::geode-configuration[] // tag::locator-manager[] @Configuration @EnableLocator @EnableManager(start = true) @Profile("locator-manager") static class LocatorManagerConfiguration { } // end::locator-manager[] } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\near\src\main\java\example\app\caching\near\server\BootGeodeNearCachingCacheServerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public String getUsername() { return this.properties.determineUsername(); } @Override public @Nullable String getPassword() { return this.properties.determinePassword(); } @Override public @Nullable String getVirtualHost() { return this.properties.determineVirtualHost(); } @Override public List<Address> getAddresses() { List<Address> addresses = new ArrayList<>(); for (String address : this.properties.determineAddresses()) { int portSeparatorIndex = address.lastIndexOf(':'); String host = address.substring(0, portSeparatorIndex); String port = address.substring(portSeparatorIndex + 1);
addresses.add(new Address(host, Integer.parseInt(port))); } return addresses; } @Override public @Nullable SslBundle getSslBundle() { Ssl ssl = this.properties.getSsl(); if (!ssl.determineEnabled()) { return null; } if (StringUtils.hasLength(ssl.getBundle())) { Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context"); return this.sslBundles.getBundle(ssl.getBundle()); } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\PropertiesRabbitConnectionDetails.java
2
请完成以下Spring Boot application配置
spring.mail.host=smtp.qq.com #spring.mail.host=smtp.gmail.com spring.mail.username=772704457@qq.com spring.mail.password=xxxxxxxxx授权码 # Other properties spring.mail.protocol=smtp spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.connectiontimeout=5000 spring.mail.properties.mail.smtp.timeout=5000 spring.mail.properties.mail.smtp.writetimeout=5000 spring.mail.default-encoding=UTF-8 # TLS , port 587 spring.mail.properties.mail.smtp.starttls.enable=true spring.
mail.properties.mail.smtp.starttls.required=true # SSL, post 465 #spring.mail.properties.mail.smtp.socketFactory.port = 465 #spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
repos\spring-boot-quick-master\quick-mail\src\main\resources\application.properties
2
请完成以下Java代码
private Stream<I_Carrier_ShipmentOrder_Item> createItems(@NonNull final DeliveryOrderParcel orderLine, @NonNull final DeliveryOrderParcelId deliveryOrderParcelId) { return orderLine.getItems() .stream() .map(item -> createItem(item, deliveryOrderParcelId)); } private I_Carrier_ShipmentOrder_Item createItem(final DeliveryOrderItem item, final @NonNull DeliveryOrderParcelId deliveryOrderParcelId) { final I_Carrier_ShipmentOrder_Item po; if (item.getId() != null) { po = InterfaceWrapperHelper.load(item.getId(), I_Carrier_ShipmentOrder_Item.class); Check.assumeEquals(po.getCarrier_ShipmentOrder_Parcel_ID(), item.getId().getRepoId()); } else { po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Item.class); po.setCarrier_ShipmentOrder_Parcel_ID(deliveryOrderParcelId.getRepoId()); } po.setProductName(item.getProductName()); po.setArticleValue(item.getProductValue()); Check.assumeEquals(item.getTotalValue().getCurrencyId(), item.getUnitPrice().getCurrencyId()); po.setPrice(item.getUnitPrice().toBigDecimal()); po.setC_Currency_ID(item.getUnitPrice().getCurrencyId().getRepoId()); po.setTotalPrice(item.getTotalValue().toBigDecimal()); po.setTotalWeightInKg(item.getTotalWeightInKg()); po.setC_UOM_ID(item.getShippedQuantity().getUomId().getRepoId()); po.setQtyShipped(item.getShippedQuantity().toBigDecimal()); return po; } private I_Carrier_ShipmentOrder_Parcel createParcel(final @NonNull DeliveryOrderParcel parcelRequest, @NonNull final DeliveryOrderId deliveryOrderId) { final I_Carrier_ShipmentOrder_Parcel po; if (parcelRequest.getId() != null) {
po = InterfaceWrapperHelper.load(parcelRequest.getId(), I_Carrier_ShipmentOrder_Parcel.class); Check.assumeEquals(po.getCarrier_ShipmentOrder_ID(), parcelRequest.getId().getRepoId()); } else { po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Parcel.class); po.setCarrier_ShipmentOrder_ID(deliveryOrderId.getRepoId()); } final PackageDimensions packageDimensions = parcelRequest.getPackageDimensions(); po.setHeightInCm(packageDimensions.getHeightInCM()); po.setLengthInCm(packageDimensions.getLengthInCM()); po.setWidthInCm(packageDimensions.getWidthInCM()); po.setWeightInKg(parcelRequest.getGrossWeightKg()); po.setM_Package_ID(PackageId.toRepoId(parcelRequest.getPackageId())); return po; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\ShipmentOrderRepository.java
1
请完成以下Java代码
public class Teacher { private Integer id; @ChineseNameSensitive private String name; @IdCardNumberSensitive private String idCard; @PhoneNumberSensitive private String tel; @EmailSensitive private String email; @PasswordSensitive private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email;
} public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Teacher() { } public Teacher(Integer id, String name, String idCard, String tel, String email, String password) { this.id = id; this.name = name; this.idCard = idCard; this.tel = tel; this.email = email; this.password = password; } @Override public String toString() { return "Teacher{" + "id=" + id + ", name='" + name + '\'' + ", idCard='" + idCard + '\'' + ", tel='" + tel + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + '}'; } }
repos\springboot-demo-master\desensitization\src\main\java\com\et\desensization\dto\Teacher.java
1
请完成以下Java代码
public final class PlainTourInstanceQueryParams implements ITourInstanceQueryParams { // NOTE: please make sure everything is set to NULL (i.e. no default values for our parameters) private I_M_Tour tour = null; private Date deliveryDate = null; private Boolean processed = null; private Boolean genericTourInstance = null; private int shipperTransportationId = -1; @Override public String toString() { return "PlainTourInstanceQueryParams [" + "tour=" + tour + ", deliveryDate=" + deliveryDate + ", processed=" + processed + ", genericTourInstance=" + genericTourInstance + ", shipperTransportationId=" + shipperTransportationId + "]"; } @Override public I_M_Tour getM_Tour() { return tour; } @Override public void setM_Tour(I_M_Tour tour) { this.tour = tour; } @Override public Date getDeliveryDate() { return deliveryDate; } @Override public void setDeliveryDate(final Date deliveryDate) { this.deliveryDate = deliveryDate; } @Override public Boolean getProcessed() { return processed; } @Override
public void setProcessed(Boolean processed) { this.processed = processed; } @Override public Boolean getGenericTourInstance() { return genericTourInstance; } @Override public void setGenericTourInstance(Boolean genericTourInstance) { this.genericTourInstance = genericTourInstance; } @Override public int getM_ShipperTransportation_ID() { return shipperTransportationId; } @Override public void setM_ShipperTransportation_ID(final int shipperTransportationId) { this.shipperTransportationId = shipperTransportationId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\PlainTourInstanceQueryParams.java
1
请在Spring Boot框架中完成以下Java代码
public Binary encrypt(String value, String algorithm) { Objects.requireNonNull(value); Objects.requireNonNull(algorithm); return encrypt(new BsonString(value), algorithm); } public Binary encrypt(Integer value, String algorithm) { Objects.requireNonNull(value); Objects.requireNonNull(algorithm); return encrypt(new BsonInt32(value), algorithm); } public BsonValue decryptProperty(Binary value) { Objects.requireNonNull(value); return clientEncryption.decrypt(new BsonBinary(value.getType(), value.getData())); } private Citizen decrypt(EncryptedCitizen encrypted) {
Objects.requireNonNull(encrypted); Citizen citizen = new Citizen(); citizen.setName(encrypted.getName()); BsonValue decryptedBirthYear = encrypted.getBirthYear() != null ? decryptProperty(encrypted.getBirthYear()) : null; if (decryptedBirthYear != null) { citizen.setBirthYear(decryptedBirthYear.asInt32().intValue()); } BsonValue decryptedEmail = encrypted.getEmail() != null ? decryptProperty(encrypted.getEmail()) : null; if (decryptedEmail != null) { citizen.setEmail(decryptedEmail.asString().getValue()); } return citizen; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\csfle\service\CitizenService.java
2
请完成以下Java代码
public Criteria andRoleIdBetween(Long value1, Long value2) { addCriterion("role_id between", value1, value2, "roleId"); return (Criteria) this; } public Criteria andRoleIdNotBetween(Long value1, Long value2) { addCriterion("role_id not between", value1, value2, "roleId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; }
protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminRoleRelationExample.java
1
请在Spring Boot框架中完成以下Java代码
public DataSource dataSource() { return new RoutingDS(dataSource(false, false), dataSource(true, true)); } @Bean public EntityManagerFactory entityManagerFactory(DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean(); managerFactoryBean.setJpaVendorAdapter(vendorAdapter); managerFactoryBean.setPackagesToScan(BookEntity.class.getPackage() .getName()); managerFactoryBean.setDataSource(dataSource); Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "validate"); managerFactoryBean.setJpaProperties(properties); managerFactoryBean.afterPropertiesSet(); return managerFactoryBean.getObject(); } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { return new JpaTransactionManager(entityManagerFactory); } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\mysql\spring\Config.java
2
请完成以下Java代码
public class SiscResultStringElement { private final String name; private final int position; private final Format format; public SiscResultStringElement(final String name, final int position, final Format format) { this.name = name; this.position = position; this.format = format; } public String getName() { return name;
} public int getPosition() { return position; } public Format getFormat() { return format; } @Override public String toString() { return "SiscResultStringElement [name=" + name + ", position=" + position + ", format=" + format + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\sics\SiscResultStringElement.java
1
请完成以下Java代码
class JsonOLCandUtil { /** * Sends the given request's JSON to std-out in a pretty-printed way */ public static void printJsonString(@NonNull final JsonOLCandCreateBulkRequest object) { System.out.println(writeValueAsString(object)); } private static String writeValueAsString(@NonNull final JsonOLCandCreateBulkRequest object) { final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.newJsonObjectMapper() .enable(SerializationFeature.INDENT_OUTPUT); try { final String json = jsonObjectMapper.writeValueAsString(object); return json; } catch (final JsonProcessingException e) { throw new JsonOLCandUtilException("JsonProcessingException", e); } } public static class JsonOLCandUtilException extends RuntimeException { private static final long serialVersionUID = -626001461757553239L; public JsonOLCandUtilException(final String msg, final Throwable cause) { super(msg, cause); } } public static JsonOLCandCreateBulkRequest loadJsonOLCandCreateBulkRequest(@NonNull final String resourceName) { return fromRessource(resourceName, JsonOLCandCreateBulkRequest.class); } public static JsonOLCandCreateRequest loadJsonOLCandCreateRequest(@NonNull final String resourceName) { return fromRessource(resourceName, JsonOLCandCreateRequest.class); } private static <T> T fromRessource(@NonNull final String resourceName, @NonNull final Class<T> clazz) { final InputStream inputStream = Check.assumeNotNull(
JsonOLCandUtil.class.getResourceAsStream(resourceName), "There needs to be a loadable resource with name={}", resourceName); final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); try { return jsonObjectMapper.readValue(inputStream, clazz); } catch (final JsonParseException e) { throw new JsonOLCandUtilException("JsonParseException", e); } catch (final JsonMappingException e) { throw new JsonOLCandUtilException("JsonMappingException", e); } catch (final IOException e) { throw new JsonOLCandUtilException("IOException", e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonOLCandUtil.java
1
请完成以下Java代码
public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Anfangsdatum. @param StartDate First effective day (inclusive)
*/ @Override public void setStartDate (java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Anfangsdatum. @return First effective day (inclusive) */ @Override public java.sql.Timestamp getStartDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_I_Flatrate_Term.java
1
请在Spring Boot框架中完成以下Java代码
public class MoveWFActivityHandler implements WFActivityHandler { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("distribution.move"); public static final UIComponentType COMPONENT_TYPE = UIComponentType.ofString("distribution/move"); @NonNull private final DistributionRestService distributionRestService; @Override public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;} @Override public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { final MobileUIDistributionConfig config = distributionRestService.getConfig(); final DistributionJob job = DistributionMobileApplication.getDistributionJob(wfProcess); final JsonDistributionJob json = JsonDistributionJob.builderFrom(job, jsonOpts) .qtyRejectedReasons(JsonRejectReasonsList.of(distributionRestService.getQtyRejectedReasons(), jsonOpts)) .requireScanningProductCode(config.isRequireScanningProductCode())
.completeJobAutomatically(config.isCompleteJobAutomatically()) .navigateToJobsListAfterPickFromComplete(config.isNavigateToJobsListAfterPickFromComplete()) .build(); return UIComponent.builderFrom(COMPONENT_TYPE, wfActivity) .properties(Params.builder() .valueObj("job", json) .build()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final DistributionJob job = DistributionMobileApplication.getDistributionJob(wfProcess); return job.getStatus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\workflows_api\activity_handlers\MoveWFActivityHandler.java
2
请完成以下Java代码
public static PInstanceId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PInstanceId(repoId) : null; } public static Optional<PInstanceId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PInstanceId id) { return toRepoIdOr(id, -1); } public static int toRepoIdOr(@Nullable final PInstanceId id, final int defaultValue) { return id != null ? id.getRepoId() : defaultValue; }
private PInstanceId(final int adPInstanceId) { repoId = Check.assumeGreaterThanZero(adPInstanceId, "adPInstanceId"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(final PInstanceId o1, final PInstanceId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\PInstanceId.java
1
请完成以下Java代码
public void delete(@NonNull final String url) { try (final MDCCloseable ignored = MDC.putCloseable("httpMethod", "DELETE"); final MDCCloseable ignored1 = MDC.putCloseable("url", url)) { final RestTemplate restTemplate = createRestTemplate(); final HttpEntity<?> entity = new HttpEntity<>(createHeaders()); restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class); } catch (final RuntimeException e) { throw convertException(e) .setParameter("httpMethod", "DELETE") .setParameter("url", url); } } private RestTemplate createRestTemplate() { return new RestTemplateBuilder().rootUri(BASE_URL).build(); } private HttpHeaders createHeaders() { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON)); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.set(HttpHeaders.AUTHORIZATION, "Bearer " + authToken); return httpHeaders; } private static AdempiereException convertException(@NonNull final RuntimeException rte) { if (rte instanceof HttpClientErrorException) {
final HttpClientErrorException hcee = (HttpClientErrorException)rte; final JSONObjectMapper<ErrorResponse> mapper = JSONObjectMapper.forClass(ErrorResponse.class); final ErrorResponse errorResponse = mapper.readValue(hcee.getResponseBodyAsString()); return new AdempiereException(errorResponse.getError().getMessage(), hcee) .markAsUserValidationError() .appendParametersToMessage() .setParameter("code", errorResponse.getError().getCode()) .setParameter("message", errorResponse.getError().getMessage()); } return AdempiereException.wrapIfNeeded(rte) .appendParametersToMessage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachLowLevelClient.java
1
请完成以下Java代码
public static final class Token { private static final String TOKEN_SETTINGS_NAMESPACE = SETTINGS_NAMESPACE.concat("token."); /** * Set the time-to-live for an authorization code. */ public static final String AUTHORIZATION_CODE_TIME_TO_LIVE = TOKEN_SETTINGS_NAMESPACE .concat("authorization-code-time-to-live"); /** * Set the time-to-live for an access token. */ public static final String ACCESS_TOKEN_TIME_TO_LIVE = TOKEN_SETTINGS_NAMESPACE .concat("access-token-time-to-live"); /** * Set the {@link OAuth2TokenFormat token format} for an access token. */ public static final String ACCESS_TOKEN_FORMAT = TOKEN_SETTINGS_NAMESPACE.concat("access-token-format"); /** * Set the time-to-live for a device code. */ public static final String DEVICE_CODE_TIME_TO_LIVE = TOKEN_SETTINGS_NAMESPACE .concat("device-code-time-to-live"); /** * Set to {@code true} if refresh tokens are reused when returning the access * token response, or {@code false} if a new refresh token is issued. */
public static final String REUSE_REFRESH_TOKENS = TOKEN_SETTINGS_NAMESPACE.concat("reuse-refresh-tokens"); /** * Set the time-to-live for a refresh token. */ public static final String REFRESH_TOKEN_TIME_TO_LIVE = TOKEN_SETTINGS_NAMESPACE .concat("refresh-token-time-to-live"); /** * Set the {@link SignatureAlgorithm JWS} algorithm for signing the * {@link OidcIdToken ID Token}. */ public static final String ID_TOKEN_SIGNATURE_ALGORITHM = TOKEN_SETTINGS_NAMESPACE .concat("id-token-signature-algorithm"); /** * Set to {@code true} if access tokens must be bound to the client * {@code X509Certificate} received during client authentication when using the * {@code tls_client_auth} or {@code self_signed_tls_client_auth} method. */ public static final String X509_CERTIFICATE_BOUND_ACCESS_TOKENS = TOKEN_SETTINGS_NAMESPACE .concat("x509-certificate-bound-access-tokens"); private Token() { } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\ConfigurationSettingNames.java
1
请在Spring Boot框架中完成以下Java代码
private void deleteCostCollectors( @NonNull final Collection<ServiceRepairProjectCostCollector> costCollectors, final boolean deleteHUReservations) { if (costCollectors.isEmpty()) { return; } final HashSet<HuId> reservedVHUIds = new HashSet<>(); final HashSet<ServiceRepairProjectCostCollectorId> costCollectorIdsToDelete = new HashSet<>(); final ArrayList<AddQtyToProjectTaskRequest> addQtyToProjectTaskRequests = new ArrayList<>(); for (final ServiceRepairProjectCostCollector costCollector : costCollectors) { if (deleteHUReservations && costCollector.getVhuId() != null) { reservedVHUIds.add(costCollector.getVhuId()); } addQtyToProjectTaskRequests.add(extractAddQtyToProjectTaskRequest(costCollector).negate());
costCollectorIdsToDelete.add(costCollector.getId()); } huReservationService.deleteReservationsByVHUIds(reservedVHUIds); projectCostCollectorRepository.deleteByIds(costCollectorIdsToDelete); addQtyToProjectTaskRequests.forEach(this::addQtyToProjectTask); } public void unlinkQuotationFromProject(@NonNull final ProjectId projectId, @NonNull final OrderId quotationId) { projectCostCollectorRepository.unsetCustomerQuotation(projectId, quotationId); } public void unlinkProposalLineFromProject(@NonNull final OrderAndLineId proposalLineId) { projectCostCollectorRepository.unsetCustomerQuotationLine(proposalLineId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\ServiceRepairProjectService.java
2
请在Spring Boot框架中完成以下Java代码
public ScannableCodeFormatsCollection getAll() { return cache.getOrLoad(0, this::retrieveAll); } private ScannableCodeFormatsCollection retrieveAll() { return newLoaderAndSaver().loadAll(); } private ScannableCodeFormatLoaderAndSaver newLoaderAndSaver() { return ScannableCodeFormatLoaderAndSaver.builder().queryBL(queryBL).build(); } public ScannableCodeFormat create(@NotNull final ScannableCodeFormatCreateRequest request) { return newLoaderAndSaver().create(request); } public int delete(@NotNull final ScannableCodeFormatQuery query) { final ImmutableSet<ScannableCodeFormatId> formatIds = toSqlQuery(query).create().idsAsSet(ScannableCodeFormatId::ofRepoId); if (formatIds.isEmpty()) { return 0; } queryBL.createQueryBuilder(I_C_ScannableCode_Format_Part.class) .addInArrayFilter(I_C_ScannableCode_Format_Part.COLUMNNAME_C_ScannableCode_Format_ID, formatIds) .create() .delete(); return queryBL.createQueryBuilder(I_C_ScannableCode_Format.class) .addInArrayFilter(I_C_ScannableCode_Format.COLUMNNAME_C_ScannableCode_Format_ID, formatIds) .create()
.delete(); } private IQueryBuilder<I_C_ScannableCode_Format> toSqlQuery(final ScannableCodeFormatQuery query) { final IQueryBuilder<I_C_ScannableCode_Format> sqlQuery = queryBL.createQueryBuilder(I_C_ScannableCode_Format.class) .orderBy(I_C_ScannableCode_Format.COLUMNNAME_C_ScannableCode_Format_ID) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_ScannableCode_Format.COLUMNNAME_AD_Client_ID, ClientId.METASFRESH); if (query.getDescription() != null) { sqlQuery.addEqualsFilter(I_C_ScannableCode_Format.COLUMNNAME_Description, query.getDescription()); } return sqlQuery; } public void deleteParts(@NotNull final ScannableCodeFormatId formatId) { queryBL.createQueryBuilder(I_C_ScannableCode_Format_Part.class) .addEqualsFilter(I_C_ScannableCode_Format_Part.COLUMNNAME_C_ScannableCode_Format_ID, formatId) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\repository\ScannableCodeFormatRepository.java
2
请完成以下Java代码
public void execute(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) { ProcessDefinitionEntity processDefinitionEntity = ProcessDefinitionUtil .getProcessDefinitionFromDatabase(job.getProcessDefinitionId()); // From DB -> need to get latest suspended state if (processDefinitionEntity == null) { throw new FlowableException("Could not find process definition needed for timer start event for job " + job); } try { if (!processDefinitionEntity.isSuspended()) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_FIRED, job), processEngineConfiguration.getEngineCfgKey()); } // Find initial flow element matching the signal start event org.flowable.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(job.getProcessDefinitionId()); String activityId = TimerEventHandler.getActivityIdFromConfiguration(configuration); if (activityId != null) { FlowElement flowElement = process.getFlowElement(activityId, true); if (flowElement == null) { throw new FlowableException("Could not find matching FlowElement for activityId " + activityId + " in " + processDefinitionEntity); } ProcessInstanceHelper processInstanceHelper = processEngineConfiguration.getProcessInstanceHelper(); processInstanceHelper.createAndStartProcessInstanceWithInitialFlowElement(processDefinitionEntity, null, null, null, flowElement, process
, null, null, null, null, true); } else { new StartProcessInstanceCmd(processDefinitionEntity.getKey(), null, null, null, job.getTenantId()).execute(commandContext); } } else { LOGGER.debug("ignoring timer of suspended process definition {}", processDefinitionEntity.getId()); } } catch (RuntimeException e) { LOGGER.error("exception during timer execution for {}", job, e); throw e; } catch (Exception e) { LOGGER.error("exception during timer execution for {}", job, e); throw new FlowableException("exception during timer execution for " + job, e); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\TimerStartEventJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } public static class OffHeapProperties { private String memorySize; private String[] regionNames = {}; public String getMemorySize() { return this.memorySize;
} public void setMemorySize(String memorySize) { this.memorySize = memorySize; } public String[] getRegionNames() { return this.regionNames; } public void setRegionNames(String[] regionNames) { this.regionNames = regionNames; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Boolean update(User user, Long id) { User exist = getUser(id); if (StrUtil.isNotBlank(user.getPassword())) { String rawPass = user.getPassword(); String salt = IdUtil.simpleUUID(); String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt); user.setPassword(pass); user.setSalt(salt); } BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true)); exist.setLastUpdateTime(new DateTime()); return userDao.update(exist, id) > 0; } /** * 获取单个用户 * * @param id 主键id * @return 单个用户对象 */
@Override public User getUser(Long id) { return userDao.findOneById(id); } /** * 获取用户列表 * * @param user 用户实体 * @return 用户列表 */ @Override public List<User> getUser(User user) { return userDao.findByExample(user); } }
repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\service\impl\UserServiceImpl.java
2
请完成以下Java代码
public String getRmtLctnElctrncAdr() { return rmtLctnElctrncAdr; } /** * Sets the value of the rmtLctnElctrncAdr property. * * @param value * allowed object is * {@link String } * */ public void setRmtLctnElctrncAdr(String value) { this.rmtLctnElctrncAdr = value; } /** * Gets the value of the rmtLctnPstlAdr property. * * @return * possible object is * {@link NameAndAddress10 } * */
public NameAndAddress10 getRmtLctnPstlAdr() { return rmtLctnPstlAdr; } /** * Sets the value of the rmtLctnPstlAdr property. * * @param value * allowed object is * {@link NameAndAddress10 } * */ public void setRmtLctnPstlAdr(NameAndAddress10 value) { this.rmtLctnPstlAdr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceLocation2.java
1
请完成以下Java代码
public String getPermission() { return permission; } /** * 设置 权限名称. * * @param permission 权限名称. */ public void setPermission(String permission) { this.permission = permission; } /** * 获取 权限说明. * * @return 权限说明. */ public String getDescription() { return description; } /** * 设置 权限说明. * * @param description 权限说明. */ public void setDescription(String description) { this.description = description; } /** * 获取 创建时间. * * @return 创建时间. */
public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 更新时间. * * @return 更新时间. */ public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Permission.java
1
请完成以下Java代码
public JsonAttributeSetInstance extractJsonAttributeSetInstance( @NonNull final ImmutableAttributeSet attributeSet, @NonNull final OrgId orgId) { final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final JsonAttributeSetInstance.JsonAttributeSetInstanceBuilder jsonAttributeSetInstance = JsonAttributeSetInstance.builder(); for (final AttributeId attributeId : attributeSet.getAttributeIds()) { final AttributeCode attributeCode = attributeSet.getAttributeCode(attributeId); final JsonAttributeInstance.JsonAttributeInstanceBuilder instanceBuilder = JsonAttributeInstance.builder() .attributeCode(attributeCode.getCode()); final String attributeValueType = attributeSet.getAttributeValueType(attributeId); if (X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(attributeValueType)) { final Date valueAsDate = attributeSet.getValueAsDate(attributeCode); if (valueAsDate != null) { final ZoneId timeZone = orgDAO.getTimeZone(orgId); final LocalDate localDate = valueAsDate.toInstant().atZone(timeZone).toLocalDate(); instanceBuilder.valueDate(localDate); } } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40.equals(attributeValueType)) { instanceBuilder.valueStr(attributeSet.getValueAsString(attributeCode)); } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(attributeValueType)) { instanceBuilder.valueStr(attributeSet.getValueAsString(attributeCode)); } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_Number.equals(attributeValueType)) {
instanceBuilder.valueNumber(attributeSet.getValueAsBigDecimal(attributeCode)); } jsonAttributeSetInstance.attributeInstance(instanceBuilder.build()); } return jsonAttributeSetInstance.build(); } @NonNull public Quantity getQuantity(final JsonPurchaseCandidateCreateItem request) { final IUOMDAO uomDAO = Services.get(IUOMDAO.class); final JsonQuantity jsonQuantity = request.getQty(); final String uomCode = jsonQuantity.getUomCode(); final Optional<I_C_UOM> uom = uomDAO.getByX12DE355IfExists(X12DE355.ofCode(uomCode)); if (!uom.isPresent()) { throw MissingResourceException.builder().resourceIdentifier("quantity.uomCode").resourceIdentifier(uomCode).build(); } return Quantity.of(jsonQuantity.getQty(), uom.get()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\RestApiUtilsV2.java
1
请完成以下Java代码
public Date getTriggerTime() { return triggerTime; } public void setTriggerTime(Date triggerTime) { this.triggerTime = triggerTime; } public int getTriggerCode() { return triggerCode; } public void setTriggerCode(int triggerCode) { this.triggerCode = triggerCode; } public String getTriggerMsg() { return triggerMsg; } public void setTriggerMsg(String triggerMsg) { this.triggerMsg = triggerMsg; } public Date getHandleTime() { return handleTime; } public void setHandleTime(Date handleTime) { this.handleTime = handleTime; } public int getHandleCode() { return handleCode; } public void setHandleCode(int handleCode) { this.handleCode = handleCode; }
public String getHandleMsg() { return handleMsg; } public void setHandleMsg(String handleMsg) { this.handleMsg = handleMsg; } public int getAlarmStatus() { return alarmStatus; } public void setAlarmStatus(int alarmStatus) { this.alarmStatus = alarmStatus; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java
1
请完成以下Java代码
public class AuthenticationEntryPointFailureHandler implements AuthenticationFailureHandler { private boolean rethrowAuthenticationServiceException = true; private final AuthenticationEntryPoint authenticationEntryPoint; public AuthenticationEntryPointFailureHandler(AuthenticationEntryPoint authenticationEntryPoint) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (!this.rethrowAuthenticationServiceException) { this.authenticationEntryPoint.commence(request, response, exception); return; }
if (!AuthenticationServiceException.class.isAssignableFrom(exception.getClass())) { this.authenticationEntryPoint.commence(request, response, exception); return; } throw exception; } /** * Set whether to rethrow {@link AuthenticationServiceException}s (defaults to true) * @param rethrowAuthenticationServiceException whether to rethrow * {@link AuthenticationServiceException}s * @since 5.8 */ public void setRethrowAuthenticationServiceException(boolean rethrowAuthenticationServiceException) { this.rethrowAuthenticationServiceException = rethrowAuthenticationServiceException; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AuthenticationEntryPointFailureHandler.java
1
请完成以下Java代码
private AdUIElementGroupId getAdElementGroupId() { return AdUIElementGroupId.ofRepoId(getRecord_ID()); } @Override protected String doIt() { final I_AD_Field adField = loadOutOfTrx(adFieldId, I_AD_Field.class); final AdTabId adTabId = AdTabId.ofRepoId(adField.getAD_Tab_ID()); // // final AdUIElementGroupId uiElementGroupId = getAdElementGroupId(); I_AD_UI_Element uiElement = getUIElementByTabAndFieldId(adTabId, adFieldId); if (uiElement == null) { uiElement = createUIElement(adField, uiElementGroupId); } else { uiElement.setAD_UI_ElementGroup_ID(uiElementGroupId.getRepoId()); } final int seqNo = Services.get(IADWindowDAO.class).getUIElementNextSeqNo(uiElementGroupId); uiElement.setIsDisplayed(true); uiElement.setSeqNo(seqNo); // if (afterUIElementId != null) // { // // TODO implement // addLog("WARNING: Adding after a given element not yet implemented, so your element will be added last."); // } saveRecord(uiElement); return MSG_OK; } private I_AD_UI_Element getUIElementByTabAndFieldId(final AdTabId adTabId, final AdFieldId adFieldId)
{ return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_UI_Element.class) .addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Tab_ID, adTabId) .addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Field_ID, adFieldId) .create() .firstOnly(I_AD_UI_Element.class); } private I_AD_UI_Element createUIElement( @NonNull final I_AD_Field adField, @NonNull final AdUIElementGroupId uiElementGroupId) { final I_AD_UI_Element uiElement = WindowUIElementsGenerator.createUIElementNoSave(uiElementGroupId, adField); uiElement.setIsDisplayed(true); uiElement.setSeqNo(10); return uiElement; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\process\AD_UI_ElementGroup_AddField.java
1
请在Spring Boot框架中完成以下Java代码
public String getOrderTime() { return orderTime; } public void setOrderTime(String orderTime) { this.orderTime = orderTime; } public Integer getOrderPeriod() { return orderPeriod; } public void setOrderPeriod(Integer orderPeriod) { this.orderPeriod = orderPeriod; } public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getPayType() {
return payType; } public void setPayType(String payType) { this.payType = payType; } public Integer getNumberOfStages() { return numberOfStages; } public void setNumberOfStages(Integer numberOfStages) { this.numberOfStages = numberOfStages; } @Override public String toString() { return "ScanPayRequestBo{" + "payKey='" + payKey + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", orderPeriod=" + orderPeriod + ", returnUrl='" + returnUrl + '\'' + ", notifyUrl='" + notifyUrl + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + ", numberOfStages=" + numberOfStages + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ScanPayRequestBo.java
2
请完成以下Java代码
public DpdClientConfig getByShipperId(@NonNull final ShipperId shipperId) { final int repoId = shipperId.getRepoId(); return cache.getOrLoad(repoId, () -> retrieveConfig(repoId)); } @NonNull private static DpdClientConfig retrieveConfig(final int shipperId) { final I_DPD_Shipper_Config configPO = Services.get(IQueryBL.class) .createQueryBuilder(I_DPD_Shipper_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DPD_Shipper_Config.COLUMNNAME_M_Shipper_ID, shipperId) .create() .firstOnly(I_DPD_Shipper_Config.class); // we have a UC on M_Shipper_ID if (configPO == null) { throw new AdempiereException("No DPD shipper configuration found for shipperId=" + shipperId);
} return DpdClientConfig.builder() .loginApiUrl(configPO.getLoginApiUrl()) .shipmentServiceApiUrl(configPO.getShipmentServiceApiUrl()) .delisID(configPO.getDelisID()) .delisPassword(configPO.getDelisPassword()) .trackingUrlBase(retrieveTrackingUrl(configPO.getM_Shipper_ID())) .paperFormat(DpdPaperFormat.ofCode(configPO.getPaperFormat())) .shipperProduct(DpdShipperProduct.ofCode(configPO.getShipperProduct())) .build(); } private static String retrieveTrackingUrl(final int shipperId) { final I_M_Shipper shipperPo = InterfaceWrapperHelper.load(shipperId, I_M_Shipper.class); return shipperPo.getTrackingURL(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\model\DpdClientConfigRepository.java
1
请在Spring Boot框架中完成以下Java代码
protected static Class<?> resolve(String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException { if (classLoader != null) { return Class.forName(className, false, classLoader); } return Class.forName(className); } protected enum ClassNameFilter { PRESENT { @Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return isPresent(className, classLoader); } }, MISSING { @Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return !isPresent(className, classLoader); } }; abstract boolean matches(String className, @Nullable ClassLoader classLoader);
private static boolean isPresent(String className, @Nullable ClassLoader classLoader) { if (classLoader == null) { classLoader = ClassUtils.getDefaultClassLoader(); } try { resolve(className, classLoader); return true; } catch (Throwable ex) { return false; } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\FilteringSpringBootCondition.java
2
请在Spring Boot框架中完成以下Java代码
final class AccountingDocsToRepostDBTableRepository { private static final String Table_Name = "\"de_metas_acct\".accounting_docs_to_repost"; public List<AccountingDocToRepost> retrieve(final int limit) { Check.assumeGreaterThanZero(limit, "limit"); return DB.retrieveRowsOutOfTrx( "SELECT * FROM " + Table_Name + " ORDER BY SeqNo LIMIT ?", Collections.singletonList(limit), this::retrieveRow); } private AccountingDocToRepost retrieveRow(final ResultSet rs) throws SQLException { return AccountingDocToRepost.builder() .seqNo(rs.getInt("SeqNo")) .recordRef(TableRecordReference.of( rs.getString("TableName"), rs.getInt("Record_ID"))) .clientId(ClientId.ofRepoId(rs.getInt("AD_Client_ID"))) .force(StringUtils.toBoolean(rs.getString("force")))
.onErrorNotifyUserId(UserId.ofRepoIdOrNullIfSystem(rs.getInt("on_error_notify_user_id"))) .build(); } public void delete(@NonNull final Collection<AccountingDocToRepost> docsToRepost) { if (docsToRepost.isEmpty()) {return;} final ImmutableSet<Integer> seqNos = docsToRepost.stream() .map(AccountingDocToRepost::getSeqNo) .collect(ImmutableSet.toImmutableSet()); DB.executeUpdateAndThrowExceptionOnFail( "DELETE FROM " + Table_Name + " WHERE " + DB.buildSqlList("SeqNo", seqNos), null, ITrx.TRXNAME_None); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\server\accouting_docs_to_repost_db_table\AccountingDocsToRepostDBTableRepository.java
2
请完成以下Java代码
public ModelQuery orderByCreateTime() { return orderBy(ModelQueryProperty.MODEL_CREATE_TIME); } public ModelQuery orderByLastUpdateTime() { return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME); } public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getModelEntityManager().findModelCountByQueryCriteria(this); } public List<Model> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; }
public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请完成以下Java代码
public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public String updateProcessBusinessKey(String bzKey) { if (isProcessInstanceType() && bzKey != null) { setBusinessKey(bzKey); Context.getCommandContext().getHistoryManager().updateProcessBusinessKeyInHistory(this); if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } return bzKey; } return null; } public void deleteIdentityLink(String userId, String groupId, String type) { List<IdentityLinkEntity> identityLinks = Context.getCommandContext().getIdentityLinkEntityManager() .findIdentityLinkByProcessInstanceUserGroupAndType(id, userId, groupId, type); for (IdentityLinkEntity identityLink : identityLinks) { Context.getCommandContext().getIdentityLinkEntityManager().deleteIdentityLink(identityLink, true); } getIdentityLinks().removeAll(identityLinks); } // NOT IN V5
@Override public boolean isMultiInstanceRoot() { return false; } @Override public void setMultiInstanceRoot(boolean isMultiInstanceRoot) { } @Override public String getPropagatedStageInstanceId() { return null; } protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity, ProcessEngineConfigurationImpl processEngineConfiguration) { JobProcessorContextImpl jobProcessorContext = new JobProcessorContextImpl(processorType, abstractJobEntity); for (JobProcessor jobProcessor : processEngineConfiguration.getJobProcessors()) { jobProcessor.process(jobProcessorContext); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntity.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final Optional<ProcessPreconditionsResolution> preconditionsResolution = checkValidSelection(); if (preconditionsResolution.isPresent()) { return preconditionsResolution.get(); } if (isForceDelivery()) { return ProcessPreconditionsResolution.rejectWithInternalReason(" Use 'WEBUI_Picking_ForcePickToComputedHU' in case of force shipping! "); } if (noSourceHUAvailable()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_MISSING_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { pickQtyToNewHUs(this::pickQtyToNewHU); invalidatePackablesView(); // left side view invalidatePickingSlotsView(); // right side view return MSG_OK; } protected final void pickQtyToNewHUs(@NonNull final Consumer<Quantity> pickQtyConsumer) { Quantity qtyToPack = getQtyToPack(); if (qtyToPack.signum() <= 0) { throw new AdempiereException("@QtyCU@ > 0"); } final Capacity piipCapacity = getPIIPCapacity(); if (piipCapacity.isInfiniteCapacity()) { pickQtyConsumer.accept(qtyToPack); return; } final Quantity piipQtyCapacity = piipCapacity.toQuantity(); while (qtyToPack.toBigDecimal().signum() > 0) { final Quantity qtyToProcess = piipQtyCapacity.min(qtyToPack); pickQtyConsumer.accept(qtyToProcess);
qtyToPack = qtyToPack.subtract(qtyToProcess); } } @NonNull private QuantityTU getQtyTU() { return getPIIPCapacity().calculateQtyTU(qtyCUsPerTU, getCurrentShipmentScheuduleUOM(), uomConversionBL) .orElseThrow(() -> new AdempiereException("QtyTU cannot be obtained for the current request!") .appendParametersToMessage() .setParameter("QtyCU", qtyCUsPerTU) .setParameter("ShipmentScheduleId", getCurrentShipmentScheduleId())); } @NonNull protected final Capacity getPIIPCapacity() { final I_M_ShipmentSchedule currentShipmentSchedule = getCurrentShipmentSchedule(); final ProductId productId = ProductId.ofRepoId(currentShipmentSchedule.getM_Product_ID()); final I_C_UOM stockUOM = productBL.getStockUOM(productId); return huCapacityBL.getCapacity(huPIItemProduct, productId, stockUOM); } @NonNull private BigDecimal getDefaultNrOfHUs() { if (qtyCUsPerTU == null || huPIItemProduct == null) { return BigDecimal.ONE; } return getQtyTU().toBigDecimal(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToComputedHU.java
1
请完成以下Java代码
private Optional<List<I_C_Order>> getSalesOrders() { final ImmutableSet.Builder<OrderId> salesOrderIds = ImmutableSet.builder(); salesOrderIds.addAll(orderDAO.getSalesOrderIdsViaPOAllocation(selectedPurchaseOrderId)); if (purchaseOrder.getLink_Order_ID() > 0) // there might be no C_PO_OrderLine_Alloc records, but a 1:1 linked sales order { salesOrderIds.add(OrderId.ofRepoId(purchaseOrder.getLink_Order_ID())); } purchaseCandidateRepository.getAllByPurchaseOrderId(selectedPurchaseOrderId) .stream() .map(PurchaseCandidate::getSalesOrderAndLineIdOrNull) .filter(Objects::nonNull) .map(OrderAndLineId::getOrderId) .forEach(salesOrderIds::add); return Optional.of(orderDAO.getByIds(salesOrderIds.build())); } @NonNull private Map<TableRecordReference, I_C_Order> getSalesOrdersRecordRef(@NonNull final List<I_C_Order> salesOrders) { return salesOrders .stream() .collect(ImmutableMap.toImmutableMap(order -> TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID()), Function.identity()));
} @NonNull private ImmutableSet<TableRecordReference> getSalesOrderPartnersRecordRef(@NonNull final List<I_C_Order> salesOrders) { return salesOrders .stream() .map(order -> TableRecordReference.of(I_C_BPartner.Table_Name, order.getC_BPartner_ID())) .collect(ImmutableSet.toImmutableSet()); } @NonNull private Optional<Map<TableRecordReference, I_Alberta_PrescriptionRequest>> getAlbertaPrescriptionsRecordRefs(@NonNull final Set<OrderId> salesOrderIds) { if (salesOrderIds.isEmpty()) { return Optional.empty(); } return Optional.of(albertaPrescriptionRequestDAO.getByOrderIds(salesOrderIds) .stream() .collect(ImmutableMap.toImmutableMap(prescription -> TableRecordReference.of(I_Alberta_PrescriptionRequest.Table_Name, prescription.getAlberta_PrescriptionRequest_ID()), Function.identity()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRowsLoader.java
1
请完成以下Java代码
public class Document { @XmlElement(name = "BkToCstmrDbtCdtNtfctn", required = true) protected BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn; /** * Gets the value of the bkToCstmrDbtCdtNtfctn property. * * @return * possible object is * {@link BankToCustomerDebitCreditNotificationV02 } * */ public BankToCustomerDebitCreditNotificationV02 getBkToCstmrDbtCdtNtfctn() { return bkToCstmrDbtCdtNtfctn;
} /** * Sets the value of the bkToCstmrDbtCdtNtfctn property. * * @param value * allowed object is * {@link BankToCustomerDebitCreditNotificationV02 } * */ public void setBkToCstmrDbtCdtNtfctn(BankToCustomerDebitCreditNotificationV02 value) { this.bkToCstmrDbtCdtNtfctn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_02\de\metas\payment\camt054_001_02\Document.java
1
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } public static class Cors { /** * Enable/disable CORS filter. */ private boolean enabled = false; /** * Allow/disallow CORS credentials. */ private boolean allowCredentials = false; /** * Allowed CORS origins, use * for all, but not in production. Default empty. */ private Set<String> allowedOrigins; /** * Allowed CORS headers, use * for all, but not in production. Default empty. */ private Set<String> allowedHeaders; /** * Exposed CORS headers, use * for all, but not in production. Default empty. */ private Set<String> exposedHeaders; /** * Allowed CORS methods, use * for all, but not in production. Default empty. */ private Set<String> allowedMethods; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isAllowCredentials() { return allowCredentials; } public void setAllowCredentials(boolean allowCredentials) { this.allowCredentials = allowCredentials; } public Set<String> getAllowedOrigins() {
return allowedOrigins == null ? Collections.emptySet() : allowedOrigins; } public void setAllowedOrigins(Set<String> allowedOrigins) { this.allowedOrigins = allowedOrigins; } public Set<String> getAllowedHeaders() { return allowedHeaders == null ? Collections.emptySet() : allowedHeaders; } public void setAllowedHeaders(Set<String> allowedHeaders) { this.allowedHeaders = allowedHeaders; } public Set<String> getExposedHeaders() { return exposedHeaders == null ? Collections.emptySet() : exposedHeaders; } public void setExposedHeaders(Set<String> exposedHeaders) { this.exposedHeaders = exposedHeaders; } public Set<String> getAllowedMethods() { return allowedMethods == null ? Collections.emptySet() : allowedMethods; } public void setAllowedMethods(Set<String> allowedMethods) { this.allowedMethods = allowedMethods; } } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\RestAppProperties.java
1
请在Spring Boot框架中完成以下Java代码
private List<I_C_Phonecall_Schema_Version_Line> retrieveLinesWithDifferentSchemas(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Phonecall_Schema_Version_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Phonecall_Schema_Version_Line.COLUMNNAME_C_Phonecall_Schema_Version_ID, phonecallSchemaVersionId) .addNotEqualsFilter(I_C_Phonecall_Schema_Version_Line.COLUMNNAME_C_Phonecall_Schema_ID, phonecallSchemaVersionId.getPhonecallSchemaId()) .create() .list(); } public void updateSchedulesOnSchemaChanged(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { final PhonecallSchemaId phonecallSchemaId = phonecallSchemaVersionId.getPhonecallSchemaId(); final List<I_C_Phonecall_Schedule> schedulesWithDifferentSchema = retrieveSchedulesWithDifferentSchemas(phonecallSchemaVersionId); for (final I_C_Phonecall_Schedule schedule : schedulesWithDifferentSchema) {
schedule.setC_Phonecall_Schema_ID(phonecallSchemaId.getRepoId()); saveRecord(schedule); } } private List<I_C_Phonecall_Schedule> retrieveSchedulesWithDifferentSchemas(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Phonecall_Schedule.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Phonecall_Schedule.COLUMNNAME_C_Phonecall_Schema_Version_ID, phonecallSchemaVersionId) .addNotEqualsFilter(I_C_Phonecall_Schedule.COLUMNNAME_C_Phonecall_Schema_ID, phonecallSchemaVersionId.getPhonecallSchemaId()) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallSchemaRepository.java
2
请完成以下Java代码
public String getF_STARTDATE() { return F_STARTDATE; } public void setF_STARTDATE(String f_STARTDATE) { F_STARTDATE = f_STARTDATE; } public String getF_STOPDATE() { return F_STOPDATE; } public void setF_STOPDATE(String f_STOPDATE) { F_STOPDATE = f_STOPDATE; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() { return F_AUDITTIME; }
public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public Timestamp getF_EDITTIME() { return F_EDITTIME; } public void setF_EDITTIME(Timestamp f_EDITTIME) { F_EDITTIME = f_EDITTIME; } public Integer getF_PLATFORM_ID() { return F_PLATFORM_ID; } public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) { F_PLATFORM_ID = f_PLATFORM_ID; } public String getF_ISPRINTBILL() { return F_ISPRINTBILL; } public void setF_ISPRINTBILL(String f_ISPRINTBILL) { F_ISPRINTBILL = f_ISPRINTBILL; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
1
请在Spring Boot框架中完成以下Java代码
public class Event { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private LocalDateTime createdAt; private LocalDateTime updatedAt; public Event() {} public Event(String name, LocalDateTime createdAt) { this.name = name; this.createdAt = createdAt; } @PreUpdate protected void onUpdate() { updatedAt = LocalDateTime.now(); } // Getters and setters 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 LocalDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt; } public LocalDateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Event{" + "id=" + id + ", name='" + name + '\'' + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + '}'; } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\localdatetimequery\Event.java
2
请完成以下Java代码
public class KnowledgeRequirementImpl extends DmnModelElementInstanceImpl implements KnowledgeRequirement { protected static ElementReference<BusinessKnowledgeModel, RequiredKnowledgeReference> requiredKnowledgeRef; public KnowledgeRequirementImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public BusinessKnowledgeModel getRequiredKnowledge() { return requiredKnowledgeRef.getReferenceTargetElement(this); } public void setRequiredKnowledge(BusinessKnowledgeModel requiredKnowledge) { requiredKnowledgeRef.setReferenceTargetElement(this, requiredKnowledge); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(KnowledgeRequirement.class, DMN_ELEMENT_KNOWLEDGE_REQUIREMENT) .namespaceUri(LATEST_DMN_NS) .instanceProvider(new ModelTypeInstanceProvider<KnowledgeRequirement>() { public KnowledgeRequirement newInstance(ModelTypeInstanceContext instanceContext) {
return new KnowledgeRequirementImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); requiredKnowledgeRef = sequenceBuilder.element(RequiredKnowledgeReference.class) .required() .uriElementReference(BusinessKnowledgeModel.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\KnowledgeRequirementImpl.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsCountGroupedByActivity(this); } public List<HistoricActivityStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricStatisticsManager() .getHistoricStatisticsGroupedByActivity(this, page); } protected void checkQueryOk() { super.checkQueryOk(); ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId); } // getters ///////////////////////////////////////////////// public String getProcessDefinitionId() { return processDefinitionId; } public boolean isIncludeFinished() {
return includeFinished; } public boolean isIncludeCanceled() { return includeCanceled; } public boolean isIncludeCompleteScope() { return includeCompleteScope; } public String[] getProcessInstanceIds() { return processInstanceIds; } public boolean isIncludeIncidents() { return includeIncidents; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityStatisticsQueryImpl.java
1
请完成以下Java代码
public int getA_Asset_Use_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Use_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Use_ID())); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set UseDate. @param UseDate UseDate */
public void setUseDate (Timestamp UseDate) { set_Value (COLUMNNAME_UseDate, UseDate); } /** Get UseDate. @return UseDate */ public Timestamp getUseDate () { return (Timestamp)get_Value(COLUMNNAME_UseDate); } /** Set Use units. @param UseUnits Currently used units of the assets */ public void setUseUnits (int UseUnits) { set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits)); } /** Get Use units. @return Currently used units of the assets */ public int getUseUnits () { Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits); 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_A_Asset_Use.java
1
请在Spring Boot框架中完成以下Java代码
QueueChannel remainderIsOneChannel() { return new QueueChannel(); } @Bean QueueChannel remainderIsTwoChannel() { return new QueueChannel(); } boolean isMultipleOfThree(Integer number) { return number % 3 == 0; } boolean isRemainderOne(Integer number) { return number % 3 == 1; }
boolean isRemainderTwo(Integer number) { return number % 3 == 2; } @Bean public IntegrationFlow classify() { return flow -> flow.split() .publishSubscribeChannel(subscription -> subscription.subscribe(subflow -> subflow.<Integer> filter(this::isMultipleOfThree) .channel("multipleofThreeChannel")) .subscribe(subflow -> subflow.<Integer> filter(this::isRemainderOne) .channel("remainderIsOneChannel")) .subscribe(subflow -> subflow.<Integer> filter(this::isRemainderTwo) .channel("remainderIsTwoChannel"))); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\publishsubscribechannel\PublishSubscibeChannelExample.java
2
请完成以下Java代码
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_Product_Relationship_ID (final int M_Product_Relationship_ID) { if (M_Product_Relationship_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, M_Product_Relationship_ID); } @Override public int getM_Product_Relationship_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Relationship_ID); }
@Override public void setRelatedProduct_ID (final int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_Value (COLUMNNAME_RelatedProduct_ID, null); else set_Value (COLUMNNAME_RelatedProduct_ID, RelatedProduct_ID); } @Override public int getRelatedProduct_ID() { return get_ValueAsInt(COLUMNNAME_RelatedProduct_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Relationship.java
1
请在Spring Boot框架中完成以下Java代码
protected Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("itemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("step1", jobRepository) .<Transaction, Transaction> chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(itemWriter3) .build(); } @Bean(name = "firstBatchJob") public Job job(@Qualifier("step1") Step step1, JobRepository jobRepository) { return new JobBuilder("firstBatchJob", jobRepository).start(step1).build(); } @Bean public Step skippingStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("skippingStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(itemWriter3) .faultTolerant() .skipLimit(2) .skip(MissingUsernameException.class) .skip(NegativeAmountException.class) .build(); } @Bean(name = "skippingBatchJob") public Job skippingJob(JobRepository jobRepository, @Qualifier("skippingStep") Step skippingStep) { return new JobBuilder("skippingBatchJob", jobRepository) .start(skippingStep) .build();
} @Bean(name = "skipPolicyStep") public Step skipPolicyStep(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("skippingItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> itemWriter3) { return new StepBuilder("skipPolicyStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(invalidInputCsv)) .processor(processor) .writer(itemWriter3) .faultTolerant() .skipPolicy(new CustomSkipPolicy()) .build(); } @Bean(name = "skipPolicyBatchJob") public Job skipPolicyBatchJob(JobRepository jobRepository, @Qualifier("skipPolicyStep") Step skipPolicyStep) { return new JobBuilder("skipPolicyBatchJob", jobRepository) .start(skipPolicyStep) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\springboot\SpringBootBatchConfig.java
2
请完成以下Java代码
public static void assertNotOldValues(@NonNull final Object model) { if (isOldValues(model)) { throw new AdempiereException("Model was expected to not use old values: " + model + " (" + model.getClass() + ")"); } } /** * If the given <code>model</code> is not null and has all the columns which are defined inside the given <code>clazz</code>'s {@link IModelClassInfo},<br> * then return an instance using {@link #create(Object, Class)}.<br> * Otherwise, return <code>null</code> . */ public static <T> T asColumnReferenceAwareOrNull(final Object model, final Class<T> clazz) { if (model == null) { return null; } if (clazz.isAssignableFrom(model.getClass())) { return clazz.cast(model); } final IModelClassInfo clazzInfo = ModelClassIntrospector .getInstance() .getModelClassInfo(clazz); for (final String columnName : clazzInfo.getDefinedColumnNames()) { if (!hasModelColumnName(model, columnName)) { // not all columns of clazz are also in model => we can't do it. return null; } } return InterfaceWrapperHelper.create(model, clazz); }
/** * Disables the read only (i.e. not updateable) columns enforcement. * So basically, after you are calling this method you will be able to change the values for any not updateable column. * <p> * WARNING: please make sure you know what are you doing before calling this method. If you are not sure, please don't use it. */ public static void disableReadOnlyColumnCheck(final Object model) { Check.assumeNotNull(model, "model not null"); ATTR_ReadOnlyColumnCheckDisabled.setValue(model, Boolean.TRUE); } public static final ModelDynAttributeAccessor<Object, Boolean> ATTR_ReadOnlyColumnCheckDisabled = new ModelDynAttributeAccessor<>(InterfaceWrapperHelper.class.getName(), "ReadOnlyColumnCheckDisabled", Boolean.class); public static int getFirstValidIdByColumnName(final String columnName) { return POWrapper.getFirstValidIdByColumnName(columnName); } // NOTE: public until we move everything to "org.adempiere.ad.model.util" package. public static Object checkZeroIdValue(final String columnName, final Object value) { return POWrapper.checkZeroIdValue(columnName, value); } public static boolean isCopy(final Object model) { return helpers.isCopy(model); } public static boolean isCopying(final Object model) { return helpers.isCopying(model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\InterfaceWrapperHelper.java
1
请完成以下Java代码
public static UUID generateType5UUID(String name) { try { final byte[] bytes = name.getBytes(StandardCharsets.UTF_8); final MessageDigest md = MessageDigest.getInstance("SHA-1"); final byte[] hash = md.digest(bytes); long msb = getLeastAndMostSignificantBitsVersion5(hash, 0); long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8); // Set the version field msb &= ~(0xfL << 12); msb |= 5L << 12; // Set the variant field to 2 lsb &= ~(0x3L << 62); lsb |= 2L << 62;
return new UUID(msb, lsb); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } } private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) { long ans = 0; for (int i = offset + 7; i >= offset; i -= 1) { ans <<= 8; ans |= src[i] & 0xffL; } return ans; } }
repos\tutorials-master\core-java-modules\core-java-uuid-generation\src\main\java\com\baeldung\uuid\UUIDGenerator.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyBook (final BigDecimal QtyBook) { set_ValueNoCheck (COLUMNNAME_QtyBook, QtyBook); } @Override public BigDecimal getQtyBook() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBook); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCsv (final BigDecimal QtyCsv) { set_Value (COLUMNNAME_QtyCsv, QtyCsv); } @Override public BigDecimal getQtyCsv() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCsv); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInternalUse (final @Nullable BigDecimal QtyInternalUse) { set_Value (COLUMNNAME_QtyInternalUse, QtyInternalUse); } @Override public BigDecimal getQtyInternalUse() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInternalUse); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); } @Override public java.lang.String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } @Override public org.compiere.model.I_M_InventoryLine getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class); }
@Override public void setReversalLine(final org.compiere.model.I_M_InventoryLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class, ReversalLine); } @Override public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID); } @Override public int getReversalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public void setUPC (final @Nullable java.lang.String UPC) { throw new IllegalArgumentException ("UPC is virtual column"); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValue (final @Nullable java.lang.String Value) { throw new IllegalArgumentException ("Value is virtual column"); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLine.java
1
请完成以下Java代码
public String getBillToAddress() { return delegate.getBillToAddress(); } @Override public void setBillToAddress(final String address) { delegate.setBillToAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentBillLocationAdapter.super.setRenderedAddress(from); } public void setFromBillLocation(@NonNull final I_C_Order from) { setFrom(OrderDocumentLocationAdapterFactory.billLocationAdapter(from).toDocumentLocation()); }
@Override public I_C_Order getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderBillLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderBillLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderBillLocationAdapter.java
1
请完成以下Java代码
private static final Set<IShipmentScheduleSegment> extractAffectedStorageSegments(final I_M_Shipment_Constraint constraint, final ModelChangeType changeType) { final Set<IShipmentScheduleSegment> storageSegments = new LinkedHashSet<>(); if (changeType.isNewOrChange()) { if (constraint.isActive()) { storageSegments.add(createStorageSegment(constraint)); } } if (changeType.isChangeOrDelete()) { final I_M_Shipment_Constraint constraintOld = InterfaceWrapperHelper.createOld(constraint, I_M_Shipment_Constraint.class); if (constraintOld.isActive()) { storageSegments.add(createStorageSegment(constraintOld));
} } return storageSegments; } private static IShipmentScheduleSegment createStorageSegment(final I_M_Shipment_Constraint constraint) { return ImmutableShipmentScheduleSegment.builder() .anyBPartner() .billBPartnerId(constraint.getBill_BPartner_ID()) .anyProduct() .anyLocator() .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_Shipment_Constraint.java
1
请完成以下Java代码
public class OptionalDeferredException<T extends Throwable> { public static <T extends Throwable> OptionalDeferredException<T> noError() { @SuppressWarnings("unchecked") final OptionalDeferredException<T> noError = (OptionalDeferredException<T>)NO_ERROR; return noError; } public static <T extends Throwable> OptionalDeferredException<T> of(@NonNull final Supplier<T> exceptionSupplier) { return new OptionalDeferredException<>(exceptionSupplier); } private static final OptionalDeferredException<Throwable> NO_ERROR = new OptionalDeferredException<>(); private final Supplier<T> exceptionSupplier; private OptionalDeferredException() { exceptionSupplier = null; } private OptionalDeferredException(@NonNull final Supplier<T> exceptionSupplier) { this.exceptionSupplier = exceptionSupplier;
} public boolean isNoError() { return exceptionSupplier == null; } public void throwIfError() throws T { if (exceptionSupplier == null) { return; } final T exception = exceptionSupplier.get(); if (exception == null) { return; } throw exception; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalDeferredException.java
1
请完成以下Java代码
protected IllegalArgumentException unsupportedConversion(ValueType typeToConvertTo) { return new IllegalArgumentException("The type " + getName() + " supports no conversion from type: " + typeToConvertTo.getName()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractValueTypeImpl other = (AbstractValueTypeImpl) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true;
} protected Boolean isTransient(Map<String, Object> valueInfo) { if (valueInfo != null && valueInfo.containsKey(VALUE_INFO_TRANSIENT)) { Object isTransient = valueInfo.get(VALUE_INFO_TRANSIENT); if (isTransient instanceof Boolean) { return (Boolean) isTransient; } else { throw new IllegalArgumentException("The property 'transient' should have a value of type 'boolean'."); } } return false; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\AbstractValueTypeImpl.java
1
请完成以下Java代码
public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public Medium getMedium() { return medium; } public void setMedium(Medium medium) { this.medium = medium; }
public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } public List<Course> getPrerequisite() { return prerequisite; } public void setPrerequisite(List<Course> prerequisite) { this.prerequisite = prerequisite; } }
repos\tutorials-master\video-tutorials\jackson-annotations-video\src\main\java\com\baeldung\jacksonannotation\domain\Course.java
1
请完成以下Java代码
public class HistoricCaseActivityStatisticsDto { protected String id; protected long available; protected long enabled; protected long disabled; protected long active; protected long completed; protected long terminated; public String getId() { return id; } public long getAvailable() { return available; } public long getEnabled() { return enabled; } public long getDisabled() { return disabled; } public long getActive() { return active; } public long getCompleted() { return completed; } public long getTerminated() {
return terminated; } public static HistoricCaseActivityStatisticsDto fromHistoricCaseActivityStatistics(HistoricCaseActivityStatistics statistics) { HistoricCaseActivityStatisticsDto result = new HistoricCaseActivityStatisticsDto(); result.id = statistics.getId(); result.available = statistics.getAvailable(); result.enabled = statistics.getEnabled(); result.disabled = statistics.getDisabled(); result.active = statistics.getActive(); result.completed = statistics.getCompleted(); result.terminated = statistics.getTerminated(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityStatisticsDto.java
1
请完成以下Java代码
public Optional<PaymentRow> getPaymentRowByPaymentId( @NonNull final PaymentId paymentId, @NonNull final ZonedDateTime evaluationDate) { final List<PaymentRow> paymentRows = getPaymentRowsListByPaymentId(ImmutableList.of(paymentId), evaluationDate); if (paymentRows.isEmpty()) { return Optional.empty(); } else if (paymentRows.size() == 1) { return Optional.of(paymentRows.get(0)); } else { throw new AdempiereException("Expected only one row for " + paymentId + " but got " + paymentRows); }
} @Value @Builder private static class InvoiceRowLoadingContext { @NonNull ZonedDateTime evaluationDate; @NonNull ImmutableSet<InvoiceId> invoiceIdsWithServiceInvoiceAlreadyGenetated; public boolean isServiceInvoiceAlreadyGenerated(@NonNull final InvoiceId invoiceId) { return invoiceIdsWithServiceInvoiceAlreadyGenetated.contains(invoiceId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\PaymentAndInvoiceRowsRepo.java
1
请完成以下Java代码
public void onMessage(@NonNull final JsonExternalSystemMessage message) { if (message.getType().equals(JsonExternalSystemMessageType.REQUEST_AUTHORIZATION)) { try (final IAutoCloseable ignored = Loggables.temporarySetLoggable(getProcessLoggable())) { authorizationService.postAuthorizationReply(); } } else { throw new AdempiereException("Received JsonExternalSystemMessageType is not supported!") .appendParametersToMessage() .setParameter("JsonExternalSystemMessageType", message.getType()); }
} @NonNull private ADProcessLoggable getProcessLoggable() { final AdProcessId sendAuthTokenProcessID = processDAO.retrieveProcessIdByClass(SendAuthTokenProcess.class); final PInstanceId pInstanceId = PInstanceId.ofRepoId(pInstanceDAO.createAD_PInstance(sendAuthTokenProcessID).getAD_PInstance_ID()); return ADProcessLoggable.builder() .pInstanceId(pInstanceId) .pInstanceDAO(pInstanceDAO) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmq\custom\listener\ExternalSystemToMFRabbitMQListener.java
1
请完成以下Java代码
public final IHUIterator getHUIterator() { return iterator; } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return getDefaultResult(); } @Override public Result afterHU(final I_M_HU hu) { return getDefaultResult(); } @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return getDefaultResult(); }
@Override public Result afterHUItem(final I_M_HU_Item item) { return getDefaultResult(); } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return getDefaultResult(); } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return getDefaultResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractJpaService<T extends Serializable> extends AbstractService<T> implements IOperations<T> { @Override public T findOne(final long id) { return super.findOne(id); } @Override public List<T> findAll() { return super.findAll(); } @Override public void create(final T entity) { super.create(entity); }
@Override public T update(final T entity) { return super.update(entity); } @Override public void delete(final T entity) { super.delete(entity); } @Override public void deleteById(final long entityId) { super.deleteById(entityId); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\service\common\AbstractJpaService.java
2
请完成以下Java代码
public void addEncapsulatedDecision(DmnElementReference encapsulatedDecision) { this.encapsulatedDecisions.add(encapsulatedDecision); } public List<DmnElementReference> getInputDecisions() { return inputDecisions; } public void setInputDecisions(List<DmnElementReference> inputDecisions) { this.inputDecisions = inputDecisions; } public void addInputDecision(DmnElementReference inputDecision) { this.inputDecisions.add(inputDecision); } public List<DmnElementReference> getInputData() { return inputData; } public void setInputData(List<DmnElementReference> inputData) {
this.inputData = inputData; } public void addInputData(DmnElementReference inputData) { this.inputData.add(inputData); } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionService.java
1
请完成以下Java代码
public void setIntercompanyDueFrom_Acct (int IntercompanyDueFrom_Acct) { set_Value (COLUMNNAME_IntercompanyDueFrom_Acct, Integer.valueOf(IntercompanyDueFrom_Acct)); } /** Get Intercompany Due From Acct. @return Intercompany Due From / Receivables Account */ public int getIntercompanyDueFrom_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueFrom_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getIntercompanyDueTo_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getIntercompanyDueTo_Acct(), get_TrxName()); }
/** Set Intercompany Due To Acct. @param IntercompanyDueTo_Acct Intercompany Due To / Payable Account */ public void setIntercompanyDueTo_Acct (int IntercompanyDueTo_Acct) { set_Value (COLUMNNAME_IntercompanyDueTo_Acct, Integer.valueOf(IntercompanyDueTo_Acct)); } /** Get Intercompany Due To Acct. @return Intercompany Due To / Payable Account */ public int getIntercompanyDueTo_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueTo_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_InterOrg_Acct.java
1
请完成以下Java代码
public class Item implements Serializable { private static final long serialVersionUID = 1L; private Integer itemId; private String itemName; private String itemDescription; private Integer itemPrice; // constructors public Item() { } public Item(final Integer itemId, final String itemName, final String itemDescription) { super(); this.itemId = itemId; this.itemName = itemName; this.itemDescription = itemDescription; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((itemId == null) ? 0 : itemId.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Item other = (Item) obj; if (itemId == null) { if (other.itemId != null) return false; } else if (!itemId.equals(other.itemId)) return false; return true; } public Integer getItemId() { return itemId; } public void setItemId(final Integer itemId) { this.itemId = itemId;
} public String getItemName() { return itemName; } public void setItemName(final String itemName) { this.itemName = itemName; } public String getItemDescription() { return itemDescription; } public Integer getItemPrice() { return itemPrice; } public void setItemPrice(final Integer itemPrice) { this.itemPrice = itemPrice; } public void setItemDescription(final String itemDescription) { this.itemDescription = itemDescription; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\model\Item.java
1
请完成以下Java代码
private void updateHUStatusToActive(@NonNull final I_M_HU hu) { final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class); final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); final IMutableHUContext huContext = huContextFactory.createMutableHUContext(Env.getCtx(), ITrx.TRXNAME_ThreadInherited); huStatusBL.setHUStatus(huContext, hu, X_M_HU.HUSTATUS_Active); handlingUnitsDAO.saveHU(hu); } private void restoreHUsFromSourceHUs(final HuId huId) { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final SourceHUsService sourceHUsService = SourceHUsService.get(); final Collection<I_M_HU> sourceHUs = sourceHUsRepository.retrieveActualSourceHUs(ImmutableSet.of(huId)); for (final I_M_HU sourceHU : sourceHUs)
{ if (!handlingUnitsBL.isDestroyed(sourceHU)) { continue; } sourceHUsService.restoreHuFromSourceHuMarkerIfPossible(sourceHU); } } private void changeStatusToDraftAndSave(final PickingCandidate pickingCandidate) { pickingCandidate.changeStatusToDraft(); pickingCandidateRepository.save(pickingCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\UnProcessPickingCandidatesAndRestoreSourceHUsCommand.java
1
请完成以下Java代码
final class LoadedPemSslStore implements PemSslStore { private final PemSslStoreDetails details; private final ResourceLoader resourceLoader; private final Supplier<CertificatesHolder> certificatesSupplier; private final Supplier<PrivateKeyHolder> privateKeySupplier; LoadedPemSslStore(PemSslStoreDetails details, ResourceLoader resourceLoader) { Assert.notNull(details, "'details' must not be null"); Assert.notNull(resourceLoader, "'resourceLoader' must not be null"); this.details = details; this.resourceLoader = resourceLoader; this.certificatesSupplier = supplier(() -> loadCertificates(details, resourceLoader)); this.privateKeySupplier = supplier(() -> loadPrivateKey(details, resourceLoader)); } private static <T> Supplier<T> supplier(ThrowingSupplier<T> supplier) { return SingletonSupplier.of(supplier.throwing(LoadedPemSslStore::asUncheckedIOException)); } private static UncheckedIOException asUncheckedIOException(String message, Exception cause) { return new UncheckedIOException(message, (IOException) cause); } private static CertificatesHolder loadCertificates(PemSslStoreDetails details, ResourceLoader resourceLoader) throws IOException { PemContent pemContent = PemContent.load(details.certificates(), resourceLoader); if (pemContent == null) { return new CertificatesHolder(null); } return new CertificatesHolder(pemContent.getCertificates()); } private static PrivateKeyHolder loadPrivateKey(PemSslStoreDetails details, ResourceLoader resourceLoader) throws IOException { PemContent pemContent = PemContent.load(details.privateKey(), resourceLoader); return new PrivateKeyHolder( (pemContent != null) ? pemContent.getPrivateKey(details.privateKeyPassword()) : null); }
@Override public @Nullable String type() { return this.details.type(); } @Override public @Nullable String alias() { return this.details.alias(); } @Override public @Nullable String password() { return this.details.password(); } @Override public @Nullable List<X509Certificate> certificates() { return this.certificatesSupplier.get().certificates(); } @Override public @Nullable PrivateKey privateKey() { return this.privateKeySupplier.get().privateKey(); } @Override public PemSslStore withAlias(@Nullable String alias) { return new LoadedPemSslStore(this.details.withAlias(alias), this.resourceLoader); } @Override public PemSslStore withPassword(@Nullable String password) { return new LoadedPemSslStore(this.details.withPassword(password), this.resourceLoader); } private record PrivateKeyHolder(@Nullable PrivateKey privateKey) { } private record CertificatesHolder(@Nullable List<X509Certificate> certificates) { } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\LoadedPemSslStore.java
1
请完成以下Java代码
public ProcessEngineException exceptionWhilePerformingOperationStep(String opName, String stepName, Exception e) { return new ProcessEngineException(exceptionMessage( "043", "Exception while performing '{}' => '{}': {}", opName, stepName, e.getMessage()), e); } public void exceptionWhilePerformingOperationStep(String name, Exception e) { logError( "044", "Exception while performing '{}': {}", name, e.getMessage(), e); } public void debugRejectedExecutionException(RejectedExecutionException e) { logDebug( "045", "RejectedExecutionException while scheduling work", e); } public void foundTomcatDeploymentDescriptor(String bpmPlatformFileLocation, String fileLocation) { logInfo( "046", "Found Camunda Platform configuration in CATALINA_BASE/CATALINA_HOME conf directory [{}] at '{}'", bpmPlatformFileLocation, fileLocation); } public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) { throw new ProcessEngineException(exceptionMessage( "047", "'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e); } public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) { logInfo(
"048", "Camunda Platform sucessfully started at '{}'.", serverInfo); } public void camundaBpmPlatformStopped(String serverInfo) { logInfo( "049", "Camunda Platform stopped at '{}'", serverInfo); } public void paDeployed(String name) { logInfo( "050", "Process application {} successfully deployed", name); } public void paUndeployed(String name) { logInfo( "051", "Process application {} undeployed", name); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class NotifyReplicationTrxRequest { @NonNull String clientValue; @NonNull String trxName; boolean finished; boolean error; @Nullable String errorMsg;
@NonNull public static NotifyReplicationTrxRequestBuilder finished() { return NotifyReplicationTrxRequest.builder() .finished(true); } @NonNull public static NotifyReplicationTrxRequestBuilder error(@NonNull final String errorMsg) { return NotifyReplicationTrxRequest.builder() .error(true) .errorMsg(errorMsg); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\route\notifyreplicationtrx\NotifyReplicationTrxRequest.java
2
请在Spring Boot框架中完成以下Java代码
public static ServiceName forMscExecutorService() { return BPM_PLATFORM.append("executor-service"); } /** * @return the {@link ServiceName} of the {@link MscRuntimeContainerJobExecutor} */ public static ServiceName forMscRuntimeContainerJobExecutorService(String jobExecutorName) { return JOB_EXECUTOR.append(jobExecutorName); } /** * @return the {@link ServiceName} of the {@link MscBpmPlatformPlugins} */ public static ServiceName forBpmPlatformPlugins() { return BPM_PLATFORM_PLUGINS; } /** * @return the {@link ServiceName} of the {@link ProcessApplicationStopService}
*/ public static ServiceName forProcessApplicationStopService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("STOP"); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.BoundedQueueThreadPoolService} */ public static ServiceName forManagedThreadPool(String threadPoolName) { return JOB_EXECUTOR.append(threadPoolName); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.ThreadFactoryService} */ public static ServiceName forThreadFactoryService(String threadFactoryName) { return ThreadsServices.threadFactoryName(threadFactoryName); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ServiceNames.java
2
请完成以下Java代码
public static ProductionDetail cast(@NonNull final BusinessCaseDetail businessCaseDetail) { return (ProductionDetail)businessCaseDetail; } ResourceId plantId; @Nullable ResourceId workstationId; int productPlanningId; int productBomLineId; String description; @Nullable PPOrderRef ppOrderRef; DocStatus ppOrderDocStatus; Flag advised; Flag pickDirectlyIfFeasible; BigDecimal qty; @Builder(toBuilder = true) private ProductionDetail( final ResourceId plantId, @Nullable final ResourceId workstationId, final int productPlanningId, final int productBomLineId, final String description, @Nullable final PPOrderRef ppOrderRef, final DocStatus ppOrderDocStatus, @NonNull final Flag advised, @NonNull final Flag pickDirectlyIfFeasible, @NonNull final BigDecimal qty) { this.advised = advised; this.pickDirectlyIfFeasible = pickDirectlyIfFeasible; final boolean detailIsAboutPPOrderHeader = productBomLineId <= 0; if (advised.isTrue() && detailIsAboutPPOrderHeader) { // plantId needs to be available when using this productionDetail to request a ppOrder being created Check.errorIf(plantId == null, "Parameter plantId needs to set for and advised PPOrder 'Header' productionDetail"); } this.plantId = plantId; this.workstationId = workstationId; this.productPlanningId = productPlanningId; this.productBomLineId = productBomLineId; this.description = description; this.ppOrderRef = ppOrderRef; this.ppOrderDocStatus = ppOrderDocStatus; this.qty = qty; } @Override public CandidateBusinessCase getCandidateBusinessCase() { return CandidateBusinessCase.PRODUCTION;
} @Nullable public PPOrderCandidateId getPpOrderCandidateId() {return ppOrderRef != null ? ppOrderRef.getPpOrderCandidateId() : null;} public int getPpOrderLineCandidateId() {return ppOrderRef != null ? ppOrderRef.getPpOrderLineCandidateId() : -1;} @Nullable public PPOrderId getPpOrderId() {return ppOrderRef != null ? ppOrderRef.getPpOrderId() : null;} @Nullable public PPOrderBOMLineId getPpOrderBOMLineId() {return ppOrderRef != null ? ppOrderRef.getPpOrderBOMLineId() : null;} @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return ppOrderRef != null ? ppOrderRef.getPpOrderAndBOMLineId() : null;} public boolean isFinishedGoods() { return this.ppOrderRef != null && this.ppOrderRef.isFinishedGoods(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isBOMLine() { return this.ppOrderRef != null && this.ppOrderRef.isBOMLine(); } public ProductionDetail withPPOrderId(@Nullable final PPOrderId newPPOrderId) { final PPOrderRef ppOrderRefNew = PPOrderRef.withPPOrderId(ppOrderRef, newPPOrderId); if (Objects.equals(this.ppOrderRef, ppOrderRefNew)) { return this; } return toBuilder().ppOrderRef(ppOrderRefNew).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\ProductionDetail.java
1
请在Spring Boot框架中完成以下Java代码
public Processor asSetPropertiesToExchangeProcessor() { return new Processor() { private final HeaderExpression headerFileName = new HeaderExpression(Exchange.FILE_NAME); @Override public void process(Exchange exchange) throws Exception { // NOTE: use the Header FILE_NAME instead of our context property // because that's dynamic and also the filename is not set when creating the context from CamelContext exchange.setProperty(Exchange.FILE_NAME, headerFileName.evaluate(exchange, String.class)); // exchange.setProperty(CONTEXT_EDIMessageDatePattern, EDIMessageDatePattern); exchange.setProperty(CONTEXT_AD_Client_Value, AD_Client_Value); exchange.setProperty(CONTEXT_AD_Org_ID, AD_Org_ID); exchange.setProperty(CONTEXT_ADInputDataDestination_InternalName, ADInputDataDestination_InternalName); exchange.setProperty(CONTEXT_ADInputDataSourceID, ADInputDataSourceID); exchange.setProperty(CONTEXT_ADUserEnteredByID, ADUserEnteredByID); exchange.setProperty(CONTEXT_DELIVERY_RULE, DeliveryRule); exchange.setProperty(CONTEXT_DELIVERY_VIA_RULE, DeliveryViaRule); // exchange.setProperty(CONTEXT_CurrencyISOCode, currencyISOCode); } }; } /** @return Excel filename which is currently imported */ public String getCamelFileName() { return CamelFileName; } // public String getEDIMessageDatePattern() // { // return EDIMessageDatePattern; // } public String getAD_Client_Value()
{ return AD_Client_Value; } public int getAD_Org_ID() { return AD_Org_ID; } public String getADInputDataDestination_InternalName() { return ADInputDataDestination_InternalName; } public BigInteger getADInputDataSourceID() { return ADInputDataSourceID; } public BigInteger getADUserEnteredByID() { return ADUserEnteredByID; } public String getDeliveryRule() { return DeliveryRule; } public String getDeliveryViaRule() { return DeliveryViaRule; } public String getCurrencyISOCode() { return currencyISOCode; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelConfigurationContext.java
2
请完成以下Java代码
public boolean isZeroQty() { return getQtyToOrder().signum() == 0 && getQtyToOrder_TU().signum() == 0; } /** * * @return the <code>model</code>'s date promised value, truncated to "day". */ public Timestamp getDatePromised() { return TimeUtil.trunc(model.getDatePromised(), TimeUtil.TRUNC_DAY); } public Object getHeaderAggregationKey() { // the pricelist is no aggregation criterion, because // the orderline's price is manually set, i.e. the pricing system is not invoked // and we often want to combine candidates with C_Flatrate_Terms (-> no pricelist, price take from the term) // and candidates without a term, where the candidate's price is computed by the pricing system return Util.mkKey(getAD_Org_ID(), getM_Warehouse_ID(), getC_BPartner_ID(), getDatePromised().getTime(), getM_PricingSystem_ID(), // getM_PriceList_ID(), getC_Currency_ID()); } /** * This method is actually used by the item aggregation key builder of {@link OrderLinesAggregator}. * * @return */ public Object getLineAggregationKey() { return Util.mkKey( getM_Product_ID(), getAttributeSetInstanceId().getRepoId(), getC_UOM_ID(), getM_HU_PI_Item_Product_ID(), getPrice()); }
/** * Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the whole candidate's QtyToOrder. * * @param orderLine */ /* package */void createAllocation(final I_C_OrderLine orderLine) { Check.assumeNotNull(orderLine, "orderLine not null"); final BigDecimal qtyToOrder = getQtyToOrder(); final BigDecimal qtyToOrderTU = getQtyToOrder_TU(); // // Create allocation final I_PMM_PurchaseCandidate_OrderLine alloc = InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine); alloc.setC_OrderLine(orderLine); alloc.setPMM_PurchaseCandidate(model); alloc.setQtyOrdered(qtyToOrder); alloc.setQtyOrdered_TU(qtyToOrderTU); InterfaceWrapperHelper.save(alloc); // NOTE: on alloc's save we expect the model's quantities to be updated InterfaceWrapperHelper.markStaled(model); // FIXME: workaround because we are modifying the model from alloc's model interceptor } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PurchaseCandidate.java
1
请完成以下Java代码
public void setStoreAttachmentsOnFileSystem (boolean StoreAttachmentsOnFileSystem) { set_Value (COLUMNNAME_StoreAttachmentsOnFileSystem, Boolean.valueOf(StoreAttachmentsOnFileSystem)); } /** Get Store Attachments On File System. @return Store Attachments On File System */ @Override public boolean isStoreAttachmentsOnFileSystem () { Object oo = get_Value(COLUMNNAME_StoreAttachmentsOnFileSystem); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Unix Archive Path. @param UnixArchivePath Unix Archive Path */ @Override public void setUnixArchivePath (java.lang.String UnixArchivePath) { set_Value (COLUMNNAME_UnixArchivePath, UnixArchivePath); } /** Get Unix Archive Path. @return Unix Archive Path */ @Override public java.lang.String getUnixArchivePath () { return (java.lang.String)get_Value(COLUMNNAME_UnixArchivePath); } /** Set Unix Attachment Path. @param UnixAttachmentPath Unix Attachment Path */ @Override public void setUnixAttachmentPath (java.lang.String UnixAttachmentPath) { set_Value (COLUMNNAME_UnixAttachmentPath, UnixAttachmentPath); } /** Get Unix Attachment Path. @return Unix Attachment Path */ @Override public java.lang.String getUnixAttachmentPath () { return (java.lang.String)get_Value(COLUMNNAME_UnixAttachmentPath); } /** 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); } /** Set Windows Archive Path. @param WindowsArchivePath Windows Archive Path */ @Override public void setWindowsArchivePath (java.lang.String WindowsArchivePath) { set_Value (COLUMNNAME_WindowsArchivePath, WindowsArchivePath); } /** Get Windows Archive Path. @return Windows Archive Path */ @Override public java.lang.String getWindowsArchivePath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsArchivePath); } /** Set Windows Attachment Path. @param WindowsAttachmentPath Windows Attachment Path */ @Override public void setWindowsAttachmentPath (java.lang.String WindowsAttachmentPath) { set_Value (COLUMNNAME_WindowsAttachmentPath, WindowsAttachmentPath); } /** Get Windows Attachment Path. @return Windows Attachment Path */ @Override public java.lang.String getWindowsAttachmentPath () { return (java.lang.String)get_Value(COLUMNNAME_WindowsAttachmentPath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Client.java
1
请完成以下Java代码
private Optional<ESRType> extractType(@NonNull final EntryTransaction2 txDtls) { return txDtls.getRmtInf() .getStrd() .stream() .map(strd -> Optional.ofNullable(strd.getCdtrRefInf())) // Safely map to CreditorReferenceInformation2 .filter(Optional::isPresent) .map(Optional::get) .filter(ReferenceStringHelper::isSupportedESRType) // Validate the ESR type .map(this::extractESRType) // Extract ESRType .filter(Objects::nonNull) .findFirst(); } private ESRType extractESRType(final de.metas.payment.camt054_001_02.CreditorReferenceInformation2 cdtrRefInf) { final String code = Optional.ofNullable(cdtrRefInf.getTp()) .map(tp -> tp.getCdOrPrtry()) .map(cdOrPrtry -> { if (cdOrPrtry.getCd() != null) { return cdOrPrtry.getCd().value(); // Check the enum (DocumentType3Code) } else { return cdOrPrtry.getPrtry(); // Check the string (Prtry) } }) .orElse(null); if (code == null) { return null; } ESRType esrType = ESRType.ofNullableCode(code); validateESRType(esrType, code); // Validate the extracted ESRType return esrType; } private void validateESRType(@Nullable final ESRType esrType, final String rawCode) { if (esrType == null || !(esrType == ESRType.TYPE_ESR || esrType == ESRType.TYPE_QRR || esrType == ESRType.TYPE_SCOR)) { // Log the error with the invalid value final String errorMsg = String.format("Invalid ESRType: '%s'. Accepted types are: ESR, QRR, SCOR.", rawCode);
// Optionally, throw an exception to halt processing throw new AdempiereException(errorMsg); } } /** * extractReferenceFallback for version 2 <code>BankToCustomerDebitCreditNotificationV02</code> * * @param txDtls * @return * @task https://github.com/metasfresh/metasfresh/issues/2107 */ private Optional<String> extractReferenceFallback(@NonNull final EntryTransaction2 txDtls) { // get the esr reference string out of the XML tree final Optional<String> esrReferenceNumberString = txDtls.getRmtInf().getStrd().stream() .map(strd -> strd.getCdtrRefInf()) .filter(cdtrRefInf -> cdtrRefInf != null) .map(cdtrRefInf -> cdtrRefInf.getRef()) .findFirst(); return esrReferenceNumberString; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\camt54\ReferenceStringHelper.java
1
请完成以下Java代码
private AttributeSetInstanceId getAttributeSetInstanceId(@Nullable final JsonAttributeSetInstance attributeSetInstance) { if (attributeSetInstance == null || Check.isEmpty(attributeSetInstance.getAttributeInstances())) { return AttributeSetInstanceId.NONE; } final ImmutableAttributeSet.Builder attributeSetBuilder = ImmutableAttributeSet.builder(); for (final JsonAttributeInstance attributeValue : attributeSetInstance.getAttributeInstances()) { attributeSetBuilder.attributeValue( AttributeCode.ofString(attributeValue.getAttributeCode()), CoalesceUtil.coalesce(attributeValue.getValueStr(), attributeValue.getValueDate(), attributeValue.getValueNumber())); } return AttributeSetInstanceId.ofRepoId(attributeSetInstanceBL.createASIFromAttributeSet(attributeSetBuilder.build()).getM_AttributeSetInstance_ID()); } private ZonedDateTime getOrDefaultDatePromised(@Nullable final ZonedDateTime purchaseDatePromised, final OrgId orgId) { return purchaseDatePromised != null ? purchaseDatePromised : SystemTime.asZonedDateTime(orgDAO.getTimeZone(orgId)); } @NonNull private BPartnerId getBPartnerId(@NonNull final OrgId orgId, @NonNull final JsonVendor vendor) { final String bpartnerIdentifierStr = vendor.getBpartnerIdentifier(); if (Check.isBlank(bpartnerIdentifierStr)) { throw new MissingPropertyException("vendor.bpartnerIdentifier", vendor); } final ExternalIdentifier bpartnerIdentifier = ExternalIdentifier.of(bpartnerIdentifierStr); final BPartnerId bPartnerId; try {
bPartnerId = jsonRetrieverService.resolveBPartnerExternalIdentifier(bpartnerIdentifier, orgId) .orElseThrow(() -> MissingResourceException.builder() .resourceName("bpartnerIdentifier") .resourceIdentifier(bpartnerIdentifier.getRawValue()) .parentResource(vendor) .build()); } catch (final AdempiereException e) { throw MissingResourceException.builder() .resourceName("vendor.bpartnerIdentifier") .resourceIdentifier(bpartnerIdentifier.getRawValue()) .cause(e) .build(); } return bPartnerId; } @NonNull private Optional<UomId> getPriceUOMId(@NonNull final JsonPrice price) { return X12DE355.ofCodeOrOptional(price.getPriceUomCode()) .map(uomDAO::getByX12DE355) .map(I_C_UOM::getC_UOM_ID) .map(UomId::ofRepoId); } @Nullable private CurrencyId getCurrencyId(@NonNull final JsonPrice price) { return Optional.ofNullable(price.getCurrencyCode()) .map(CurrencyCode::ofThreeLetterCode) .map(currencyRepository::getCurrencyIdByCurrencyCode) .orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\CreatePurchaseCandidatesService.java
1
请完成以下Java代码
public class DDOrderHUDocumentFactory extends AbstractHUDocumentFactory<I_DD_Order> { public DDOrderHUDocumentFactory() { super(I_DD_Order.class); } private IHUDocumentFactory getHandlingUnitsHUDocumentFactory() { return new HandlingUnitHUDocumentFactory() { @Override protected I_M_HU getInnerHU(final I_M_HU hu) { // NOTE: we are always returning the HU, even if it does not have a parent return hu; } }; } @Override protected void createHUDocumentsFromTypedModel(final HUDocumentsCollector documentsCollector, final I_DD_Order ddOrder) { final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class); final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final IHUDocumentFactory huFactory = getHandlingUnitsHUDocumentFactory(); final Set<Integer> seenHuIds = new HashSet<>(); final DDOrderLowLevelDAO ddOrderLowLevelDAO = SpringContextHolder.instance.getBean(DDOrderLowLevelDAO.class); for (final I_DD_OrderLine line : ddOrderLowLevelDAO.retrieveLines(ddOrder)) { // // Create HUDocuments final LocatorId locatorId = warehouseDAO.getLocatorIdByRepoId(line.getM_Locator_ID()); final Iterator<I_M_HU> hus = handlingUnitsDAO.retrieveTopLevelHUsForLocator(locatorId); while (hus.hasNext()) { final I_M_HU hu = hus.next(); final int huId = hu.getM_HU_ID(); if (!seenHuIds.add(huId))
{ // already added continue; } final List<IHUDocument> lineDocuments = huFactory.createHUDocumentsFromModel(hu); documentsCollector.getHUDocuments().addAll(lineDocuments); } // // Create target Capacities final Quantity qtyToDeliver = Quantitys.of( line.getQtyOrdered().subtract(line.getQtyDelivered()), UomId.ofRepoId(line.getC_UOM_ID())); final Capacity targetCapacity = Capacity.createCapacity( qtyToDeliver.toBigDecimal(), // qty ProductId.ofRepoId(line.getM_Product_ID()), qtyToDeliver.getUOM(), false// allowNegativeCapacity ); documentsCollector.getTargetCapacities().add(targetCapacity); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\hu_spis\DDOrderHUDocumentFactory.java
1
请完成以下Java代码
public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getError() {
return error; } public void setError(String error) { this.error = error; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\model\BadApiRequest.java
1
请完成以下Java代码
public void onStatsPersistMsg(StatsPersistMsg msg) { if (msg.isEmpty()) { return; } systemContext.getEventService().saveAsync(StatisticsEvent.builder() .tenantId(msg.getTenantId()) .entityId(msg.getEntityId().getId()) .serviceId(systemContext.getServiceInfoProvider().getServiceId()) .messagesProcessed(msg.getMessagesProcessed()) .errorsOccurred(msg.getErrorsOccurred()) .build() ); } private JsonNode toBodyJson(String serviceId, long messagesProcessed, long errorsOccurred) { return JacksonUtil.newObjectNode().put("server", serviceId).put("messagesProcessed", messagesProcessed).put("errorsOccurred", errorsOccurred); } public static class ActorCreator extends ContextBasedCreator { private final String actorId;
public ActorCreator(ActorSystemContext context, String actorId) { super(context); this.actorId = actorId; } @Override public TbActorId createActorId() { return new TbStringActorId(actorId); } @Override public TbActor createActor() { return new StatsActor(context); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\stats\StatsActor.java
1
请完成以下Java代码
public abstract class DelegateInvocation { protected Object invocationResult; protected BaseDelegateExecution contextExecution; protected ResourceDefinitionEntity contextResource; /** * Provide a context execution or resource definition in which context the invocation * should be performed. If both parameters are null, the invocation is performed in the * current context. * * @param contextExecution set to an execution */ public DelegateInvocation(BaseDelegateExecution contextExecution, ResourceDefinitionEntity contextResource) { // This constructor forces sub classes to call it, thereby making it more visible // whether a context switch is going to be performed for them. this.contextExecution = contextExecution; this.contextResource = contextResource; } /** * make the invocation proceed, performing the actual invocation of the user * code. * * @throws Exception * the exception thrown by the user code */ public void proceed() throws Exception { invoke(); } protected abstract void invoke() throws Exception; /** * @return the result of the invocation (can be null if the invocation does
* not return a result) */ public Object getInvocationResult() { return invocationResult; } /** * returns the execution in which context this delegate is invoked. may be null */ public BaseDelegateExecution getContextExecution() { return contextExecution; } public ResourceDefinitionEntity getContextResource() { return contextResource; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\delegate\DelegateInvocation.java
1
请完成以下Java代码
public boolean isTenantCheckEnabled() { return tenantCheckEnabled; } public JobEntity getCurrentJob() { return currentJob; } public void setCurrentJob(JobEntity currentJob) { this.currentJob = currentJob; } public boolean isRestrictUserOperationLogToAuthenticatedUsers() { return restrictUserOperationLogToAuthenticatedUsers; } public void setRestrictUserOperationLogToAuthenticatedUsers(boolean restrictUserOperationLogToAuthenticatedUsers) { this.restrictUserOperationLogToAuthenticatedUsers = restrictUserOperationLogToAuthenticatedUsers; } public String getOperationId() { if (!getOperationLogManager().isUserOperationLogEnabled()) { return null; } if (operationId == null) { operationId = Context.getProcessEngineConfiguration().getIdGenerator().getNextId(); } return operationId; } public void setOperationId(String operationId) { this.operationId = operationId; } public OptimizeManager getOptimizeManager() { return getSession(OptimizeManager.class); } public <T> void executeWithOperationLogPrevented(Command<T> command) {
boolean initialLegacyRestrictions = isRestrictUserOperationLogToAuthenticatedUsers(); disableUserOperationLog(); setRestrictUserOperationLogToAuthenticatedUsers(true); try { command.execute(this); } finally { enableUserOperationLog(); setRestrictUserOperationLogToAuthenticatedUsers(initialLegacyRestrictions); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
public SqlDocumentQueryBuilder setRecordIds(final Set<DocumentId> recordIds) { this.recordIds = recordIds != null ? ImmutableSet.copyOf(recordIds) : ImmutableSet.of(); return this; } public SqlDocumentQueryBuilder noSorting(final boolean noSorting) { this.noSorting = noSorting; if (noSorting) { orderBys = DocumentQueryOrderByList.EMPTY; } return this; } public boolean isSorting() { return !isNoSorting(); } public SqlDocumentQueryBuilder setOrderBys(final DocumentQueryOrderByList orderBys) { // Don't throw exception if noSorting is true. Just do nothing. // REASON: it gives us better flexibility when this builder is handled by different methods, each of them adding stuff to it // Check.assume(!noSorting, "sorting enabled for {}", this); if (noSorting) { return this; } this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY; return this; } public SqlDocumentQueryBuilder setPage(final int firstRow, final int pageLength) { this.firstRow = firstRow; this.pageLength = pageLength; return this; } private int getFirstRow() { return firstRow; } private int getPageLength() { return pageLength;
} public static SqlComposedKey extractComposedKey( final DocumentId recordId, final List<? extends SqlEntityFieldBinding> keyFields) { final int count = keyFields.size(); if (count < 1) { throw new AdempiereException("Invalid composed key: " + keyFields); } final List<Object> composedKeyParts = recordId.toComposedKeyParts(); if (composedKeyParts.size() != count) { throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size()); } final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder(); final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder(); for (int i = 0; i < count; i++) { final SqlEntityFieldBinding keyField = keyFields.get(i); final String keyColumnName = keyField.getColumnName(); keyColumnNames.add(keyColumnName); final Object valueObj = composedKeyParts.get(i); @Nullable final Object valueConv = DataTypes.convertToValueClass( keyColumnName, valueObj, keyField.getWidgetType(), keyField.getSqlValueClass(), null); if (!JSONNullValue.isNull(valueConv)) { values.put(keyColumnName, valueConv); } } return SqlComposedKey.of(keyColumnNames.build(), values.build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java
1
请完成以下Java代码
protected <T> T performContextSwitch(final Callable<T> callable) { ProcessApplicationReference targetProcessApplication = ProcessApplicationContextUtil.getTargetProcessApplication(deploymentId); if(targetProcessApplication != null) { return Context.executeWithinProcessApplication(new Callable<T>() { public T call() throws Exception { return doCall(callable); } }, targetProcessApplication); } else { return doCall(callable); } } protected <T> T doCall(Callable<T> callable) { try { return callable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) {
throw new ProcessEngineException(e); } } public void submitFormVariables(final VariableMap properties, final VariableScope variableScope) { performContextSwitch(new Callable<Void> () { public Void call() throws Exception { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new SubmitFormVariablesInvocation(formHandler, properties, variableScope)); return null; } }); } public abstract FormHandler getFormHandler(); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DelegateFormHandler.java
1
请完成以下Java代码
public void deleteEditorSource(ModelEntity model) { if (model.getEditorSourceValueId() != null) { ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId(), null); ref.delete(engineConfiguration.getEngineCfgKey()); } } @Override public void deleteEditorSourceExtra(ModelEntity model) { if (model.getEditorSourceExtraValueId() != null) { ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId(), null); ref.delete(engineConfiguration.getEngineCfgKey()); } } @Override public void insertEditorSourceExtraForModel(String modelId, byte[] modelSource) { ModelEntity model = findById(modelId); if (model != null) { ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId(), null); ref.setValue("source-extra", modelSource, engineConfiguration.getEngineCfgKey()); if (model.getEditorSourceExtraValueId() == null) { model.setEditorSourceExtraValueId(ref.getId()); updateModel(model); } } } @Override public List<Model> findModelsByQueryCriteria(ModelQueryImpl query) { return dataManager.findModelsByQueryCriteria(query); } @Override public long findModelCountByQueryCriteria(ModelQueryImpl query) { return dataManager.findModelCountByQueryCriteria(query); } @Override public byte[] findEditorSourceByModelId(String modelId) { ModelEntity model = findById(modelId); if (model == null || model.getEditorSourceValueId() == null) { return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId(), null); return ref.getBytes(engineConfiguration.getEngineCfgKey()); }
@Override public byte[] findEditorSourceExtraByModelId(String modelId) { ModelEntity model = findById(modelId); if (model == null || model.getEditorSourceExtraValueId() == null) { return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId(), null); return ref.getBytes(engineConfiguration.getEngineCfgKey()); } @Override public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findModelsByNativeQuery(parameterMap); } @Override public long findModelCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findModelCountByNativeQuery(parameterMap); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ModelEntityManagerImpl.java
1
请完成以下Java代码
public SuspendedJobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public SuspendedJobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public SuspendedJobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobCountByQueryCriteria(this); } public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getSuspendedJobEntityManager().findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id;
} public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\SuspendedJobQueryImpl.java
1
请完成以下Java代码
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) { try { Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null); method.setAccessible(true); Object annotationData = method.invoke(targetClass); Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS); annotations.setAccessible(true); Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData); map.put(targetAnnotation, targetValue); } catch (Exception e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) { try { Field annotations = Class.class.getDeclaredField(ANNOTATIONS); annotations.setAccessible(true); Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass); System.out.println(map); map.put(targetAnnotation, targetValue); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\reflection\GreetingAnnotation.java
1