instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static BPartnerLocationId ofRepoIdOrNull( @Nullable final BPartnerId bpartnerId, @Nullable final Integer bpartnerLocationId) { return bpartnerId != null && bpartnerLocationId != null && bpartnerLocationId > 0 ? ofRepoId(bpartnerId, bpartnerLocationId) : null; } @Jacksonized @Builder private BPartnerLocationId(@NonNull final BPartnerId bpartnerId, final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "bpartnerLocationId"); this.bpartnerId = bpartnerId; }
public static int toRepoId(@Nullable final BPartnerLocationId bpLocationId) { return bpLocationId != null ? bpLocationId.getRepoId() : -1; } @Nullable public static Integer toRepoIdOrNull(@Nullable final BPartnerLocationId bpLocationId) { return bpLocationId != null ? bpLocationId.getRepoId() : null; } public static boolean equals(final BPartnerLocationId id1, final BPartnerLocationId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerLocationId.java
1
请完成以下Java代码
private int expireLocks() { final String sql = "UPDATE "+I_R_Group_Prospect.Table_Name+" SET " +" "+I_R_Group_Prospect.COLUMNNAME_Locked+"=?" +","+I_R_Group_Prospect.COLUMNNAME_LockedBy+"=?" +","+I_R_Group_Prospect.COLUMNNAME_LockedDate+"=?" +" WHERE " +" "+I_R_Group_Prospect.COLUMNNAME_AD_Client_ID+"=?" +" AND "+I_R_Group_Prospect.COLUMNNAME_Locked+"=?" +" AND addDays("+I_R_Group_Prospect.COLUMNNAME_LockedDate+",?) > getDate()" ; int expireDays = (int)Math.round( (double)MRGroupProspect.LOCK_EXPIRE_MIN / (double)60 + 0.5 ); int count = DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[]{false, null, null, getAD_Client_ID(), true, expireDays}, get_TrxName()); addLog("Unlocked #"+count); return count; } private void updateCCM_Bundle_Status()
{ int[] ids = new Query(getCtx(), X_R_Group.Table_Name, null, get_TrxName()) //.setOnlyActiveRecords(true) // check all bundles .setClient_ID() .getIDs(); int count = 0; for (int R_Group_ID : ids) { boolean updated = BundleUtil.updateCCM_Bundle_Status(R_Group_ID, get_TrxName()); if (updated) count++; } addLog("@Updated@ @CCM_Bundle_Status@ #"+count); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\process\CallCenterDailyMaintenance.java
1
请在Spring Boot框架中完成以下Java代码
public class LongPollingBakeryClient { public String callBakeWithRestTemplate(RestTemplateBuilder restTemplateBuilder) { RestTemplate restTemplate = restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(10)) .setReadTimeout(Duration.ofSeconds(10)) .build(); try { return restTemplate.getForObject("/api/bake/cookie?bakeTime=1000", String.class); } catch (ResourceAccessException e) { throw e; } }
public String callBakeWithWebClient() { WebClient webClient = WebClient.create(); try { return webClient.get() .uri("/api/bake/cookie?bakeTime=1000") .retrieve() .bodyToFlux(String.class) .timeout(Duration.ofSeconds(10)) .blockFirst(); } catch (ReadTimeoutException e) { throw e; } } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\longpolling\client\LongPollingBakeryClient.java
2
请完成以下Java代码
InputStream openStream() throws IOException { Assert.state(this.file != null, "'file' must not be null"); return new FileInputStream(this.file); } /** * Return the scope of the library. * @return the scope */ public @Nullable LibraryScope getScope() { return this.scope; } /** * Return the {@linkplain LibraryCoordinates coordinates} of the library. * @return the coordinates */ public @Nullable LibraryCoordinates getCoordinates() { return this.coordinates; } /** * Return if the file cannot be used directly as a nested jar and needs to be * unpacked. * @return if unpack is required */ public boolean isUnpackRequired() { return this.unpackRequired; } long getLastModified() { Assert.state(this.file != null, "'file' must not be null"); return this.file.lastModified(); }
/** * Return if the library is local (part of the same build) to the application that is * being packaged. * @return if the library is local */ public boolean isLocal() { return this.local; } /** * Return if the library is included in the uber jar. * @return if the library is included */ public boolean isIncluded() { return this.included; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Library.java
1
请完成以下Java代码
public void onASIorDiscountChange(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { Services.get(IInvoiceLineBL.class).updatePrices(invoiceLine); } /** * Recalculate priceActual on discount or priceEntered change. * Don't invoice the pricing engine. */ @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_PriceEntered, I_C_InvoiceLine.COLUMNNAME_Discount }) public void recomputePriceActual(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { final CurrencyPrecision pricePrecision = extractPrecision(invoiceLine); if (pricePrecision == null) { return; } InvoiceLinePriceAndDiscount.of(invoiceLine, pricePrecision) .withUpdatedPriceActual() .applyTo(invoiceLine); } @Nullable private CurrencyPrecision extractPrecision(@NonNull final I_C_InvoiceLine invoiceLine) { final IPriceListBL priceListBL = Services.get(IPriceListBL.class); if (invoiceLine.getC_Invoice_ID() <= 0) { return null; } final I_C_Invoice invoice = invoiceLine.getC_Invoice(); return priceListBL.getPricePrecision(PriceListId.ofRepoId(invoice.getM_PriceList_ID())); } /** * Set the product as soon as the order line is set */ @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID }) public void setProduct(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { if (InterfaceWrapperHelper.isNull(invoiceLine, I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID)) {
// set the product to null if the orderline was set to null invoiceLine.setM_Product_ID(-1); return; } final I_C_OrderLine ol = invoiceLine.getC_OrderLine(); invoiceLine.setM_Product_ID(ol.getM_Product_ID()); } @CalloutMethod(columnNames = { I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID }) public void setIsPackagingMaterial(final I_C_InvoiceLine invoiceLine, final ICalloutField field) { if (InterfaceWrapperHelper.isNull(invoiceLine, I_C_InvoiceLine.COLUMNNAME_C_OrderLine_ID)) { // in case the c_orderline_id is removed, make sure the flag is on false. The user can set it on true, manually invoiceLine.setIsPackagingMaterial(false); return; } final de.metas.interfaces.I_C_OrderLine ol = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), de.metas.interfaces.I_C_OrderLine.class); invoiceLine.setIsPackagingMaterial(ol.isPackagingMaterial()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\callout\C_InvoiceLine.java
1
请完成以下Java代码
public int getPP_Order_Node_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_ID); } @Override public void setPP_Order_Node_ID(final int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, PP_Order_Node_ID); } @Override public int getPP_Order_Node_Product_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_Product_ID); } @Override public void setPP_Order_Node_Product_ID(final int PP_Order_Node_Product_ID) { if (PP_Order_Node_Product_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, PP_Order_Node_Product_ID); } @Override public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() { return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class); } @Override public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow) { set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow); } @Override public int getPP_Order_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID); } @Override public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID) { if (PP_Order_Workflow_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty(final @Nullable BigDecimal Qty) { set_Value(COLUMNNAME_Qty, Qty); } @Override public int getSeqNo()
{ return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNo(final int SeqNo) { set_Value(COLUMNNAME_SeqNo, SeqNo); } @Override public java.lang.String getSpecification() { return get_ValueAsString(COLUMNNAME_Specification); } @Override public void setSpecification(final @Nullable java.lang.String Specification) { set_Value(COLUMNNAME_Specification, Specification); } @Override public BigDecimal getYield() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield(final @Nullable BigDecimal Yield) { set_Value(COLUMNNAME_Yield, Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java
1
请完成以下Java代码
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item.java
1
请完成以下Java代码
public Integer getAttendCount() { return attendCount; } public void setAttendCount(Integer attendCount) { this.attendCount = attendCount; } public Integer getAttentionCount() { return attentionCount; } public void setAttentionCount(Integer attentionCount) { this.attentionCount = attentionCount; } public Integer getReadCount() { return readCount; } public void setReadCount(Integer readCount) { this.readCount = readCount; } public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public String getAttendType() { return attendType; } public void setAttendType(String attendType) { this.attendType = attendType; } public String getContent() { return content; } public void setContent(String content) { this.content = content; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", categoryId=").append(categoryId); sb.append(", name=").append(name); sb.append(", createTime=").append(createTime); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", attendCount=").append(attendCount); sb.append(", attentionCount=").append(attentionCount); sb.append(", readCount=").append(readCount); sb.append(", awardName=").append(awardName); sb.append(", attendType=").append(attendType); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopic.java
1
请完成以下Java代码
public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return Ein Fehler ist bei der Durchführung aufgetreten */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText);
} /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
1
请完成以下Java代码
public void setIsSimulation (final boolean IsSimulation) { throw new IllegalArgumentException ("IsSimulation is virtual column"); } @Override public boolean isSimulation() { return get_ValueAsBoolean(COLUMNNAME_IsSimulation); } @Override public void setM_Product_DataEntry_ID (final int M_Product_DataEntry_ID) { if (M_Product_DataEntry_ID < 1) set_Value (COLUMNNAME_M_Product_DataEntry_ID, null); else set_Value (COLUMNNAME_M_Product_DataEntry_ID, M_Product_DataEntry_ID); } @Override public int getM_Product_DataEntry_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_DataEntry_ID); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing()
{ return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQty_Planned (final @Nullable BigDecimal Qty_Planned) { set_Value (COLUMNNAME_Qty_Planned, Qty_Planned); } @Override public BigDecimal getQty_Planned() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Planned); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=540263 * Reference name: C_Flatrate_DataEntry Type */ public static final int TYPE_AD_Reference_ID=540263; /** Invoicing_PeriodBased = IP */ public static final String TYPE_Invoicing_PeriodBased = "IP"; /** Correction_PeriodBased = CP */ public static final String TYPE_Correction_PeriodBased = "CP"; /** Procurement_PeriodBased = PC */ public static final String TYPE_Procurement_PeriodBased = "PC"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java
1
请在Spring Boot框架中完成以下Java代码
public static boolean hasAdminIntersection(String usernames) { if (oConvertUtils.isEmpty(usernames)) { return false; } // 使用HashSet提高查找效率 Set<String> adminSet = Arrays.stream(ADMIN_ACCOUNT) .map(String::toLowerCase) .collect(Collectors.toSet()); return Arrays.stream(usernames.split(SymbolConstant.COMMA)) .map(String::trim) .map(String::toLowerCase) .anyMatch(adminSet::contains); } /** * 根据用户ids获取部门名称 * * @param userIdList * @param symbol * @return */ private Map<String, String> getDepartOtherPostByUserIds(List<String> userIdList, String symbol) { Map<String, String> departPostMap = new HashMap<>(); List<SysUserSysDepPostModel> departPost = sysDepartMapper.getDepartOtherPostByUserIds(userIdList); if (CollectionUtil.isNotEmpty(departPost)) { ISysDepartService service = SpringContextUtils.getBean(SysDepartServiceImpl.class); departPost.forEach(item -> { if (oConvertUtils.isNotEmpty(item.getId()) && oConvertUtils.isNotEmpty(item.getOtherDepPostId())) { String postName = service.getDepartPathNameByOrgCode(item.getOrgCode(), ""); if (departPostMap.containsKey(item.getId())) { departPostMap.put(item.getId(), departPostMap.get(item.getId()) + symbol + postName); } else { departPostMap.put(item.getId(), postName); } } }); } return departPostMap; } /** * 根据用户ids获取部门名称 * * @param userIdList
* @param symbol * @return */ private Map<String, String> getDepartNamesByUserIds(List<String> userIdList, String symbol) { Map<String, String> userOrgCodeMap = new HashMap<>(); if (CollectionUtil.isNotEmpty(userIdList)) { List<SysUserSysDepPostModel> userDepPosts = sysUserDepartMapper.getUserDepPostByUserIds(userIdList); if (CollectionUtil.isNotEmpty(userDepPosts)) { ISysDepartService service = SpringContextUtils.getBean(SysDepartServiceImpl.class); userDepPosts.forEach(item -> { if (oConvertUtils.isNotEmpty(item.getId()) && oConvertUtils.isNotEmpty(item.getOrgCode())) { String departNamePath = service.getDepartPathNameByOrgCode(item.getOrgCode(), ""); if (userOrgCodeMap.containsKey(item.getId())) { userOrgCodeMap.put(item.getId(), userOrgCodeMap.get(item.getId()) + symbol + departNamePath); } else { userOrgCodeMap.put(item.getId(), departNamePath); } } }); } } return userOrgCodeMap; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserServiceImpl.java
2
请完成以下Java代码
public JsonExternalId toJsonOrNull(@Nullable final ExternalId externalId) { if (externalId == null) { return null; } return JsonExternalId.of(externalId.getValue()); } public ExternalId fromJsonOrNull(@Nullable final JsonExternalId jsonExternalId) { if (jsonExternalId == null) { return null; } return ExternalId.of(jsonExternalId.getValue()); } @NonNull
public JsonAttachmentType toJsonAttachmentType(@NonNull final AttachmentEntryType type) { switch (type) { case Data: return JsonAttachmentType.Data; case URL: return JsonAttachmentType.URL; case LocalFileURL: return JsonAttachmentType.LocalFileURL; default: throw new AdempiereException("Unknown AttachmentEntryType") .appendParametersToMessage() .setParameter("type", type); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\JsonConverters.java
1
请完成以下Java代码
public class C_DunningDoc { @ModelChange(timings = ModelValidator.TYPE_BEFORE_NEW) public void setDocTypeId(final I_C_DunningDoc dunningDoc) { final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final DocTypeQuery query = DocTypeQuery .builder() .adClientId(dunningDoc.getAD_Client_ID()) .adOrgId(dunningDoc.getAD_Org_ID()) .docBaseType(Dunning_Constants.DocBaseType_Dunnig) .build(); final DocTypeId docTypeId = docTypeDAO.getDocTypeId(query); dunningDoc.setC_DocType_ID(docTypeId.getRepoId()); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, // ifColumnsChanged = I_C_DunningDoc.COLUMNNAME_Processed) public void createDocResponsible(final I_C_DunningDoc dunningDoc) { if (dunningDoc.isProcessed()) { Services.get(IWorkflowBL.class).createDocResponsible(dunningDoc, dunningDoc.getAD_Org_ID()); } }
/** * Updates <code>C_DunningDoc.BPartnerAddress</code> when the the <code>C_BPartner_Location_ID</code> column is changed. * Task 07359 */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = I_C_DunningDoc.COLUMNNAME_C_BPartner_Location_ID) public void updateAddressField(final I_C_DunningDoc dunningDoc) { final IDocumentLocationBL documentLocationBL = SpringContextHolder.instance.getBean(IDocumentLocationBL.class); documentLocationBL.updateRenderedAddressAndCapturedLocation(DunningDocDocumentLocationAdapterFactory.locationAdapter(dunningDoc)); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void scheduleDataExport(final I_C_DunningDoc dunningDoc) { C_DunningDoc_CreateExportData.scheduleOnTrxCommit(dunningDoc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\modelvalidator\C_DunningDoc.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAdditionalText(final @Nullable String AdditionalText) { set_Value(COLUMNNAME_AdditionalText, AdditionalText); } @Override public @NotNull String getAdditionalText() { return get_ValueAsString(COLUMNNAME_AdditionalText); } @Override public I_C_BPartner_DocType getC_BPartner_DocType() { return get_ValueAsPO(COLUMNNAME_C_BPartner_DocType_ID, I_C_BPartner_DocType.class); } @Override public void setC_BPartner_DocType(final I_C_BPartner_DocType C_BPartner_DocType) { set_ValueFromPO(COLUMNNAME_C_BPartner_DocType_ID, I_C_BPartner_DocType.class, C_BPartner_DocType); } @Override public void setC_BPartner_DocType_ID(final int C_BPartner_DocType_ID) { if (C_BPartner_DocType_ID < 1) set_Value(COLUMNNAME_C_BPartner_DocType_ID, null); else set_Value(COLUMNNAME_C_BPartner_DocType_ID, C_BPartner_DocType_ID); } @Override public int getC_BPartner_DocType_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_DocType_ID); }
@Override public void setC_BPartner_ID(final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value(COLUMNNAME_C_BPartner_ID, null); else set_Value(COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_BPartner_Report_Text_ID(final int C_BPartner_Report_Text_ID) { if (C_BPartner_Report_Text_ID < 1) set_ValueNoCheck(COLUMNNAME_C_BPartner_Report_Text_ID, null); else set_ValueNoCheck(COLUMNNAME_C_BPartner_Report_Text_ID, C_BPartner_Report_Text_ID); } @Override public int getC_BPartner_Report_Text_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Report_Text_ID); } @Override public void setValue(final String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\partnerreporttext\model\X_C_BPartner_Report_Text.java
1
请完成以下Java代码
public class PPOrderCreatedEvent implements MaterialEvent { private final EventDescriptor eventDescriptor; private final PPOrder ppOrder; private final boolean directlyPickIfFeasible; public static final String TYPE = "PPOrderCreatedEvent"; @JsonCreator @Builder public PPOrderCreatedEvent( @JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor, @JsonProperty("ppOrder") final @NonNull PPOrder ppOrder, @JsonProperty("directlyPickIfFeasible") final boolean directlyPickIfFeasible) { this.eventDescriptor = eventDescriptor; this.ppOrder = ppOrder; this.directlyPickIfFeasible = directlyPickIfFeasible; } public void validate() { final PPOrder ppOrder = getPpOrder();
final PPOrderId ppOrderId = ppOrder.getPpOrderId(); Check.errorIf(ppOrderId == null, "The given ppOrderCreatedEvent event has a ppOrder with ppOrderId={}", ppOrderId); ppOrder.getLines().forEach(this::validateLine); } private void validateLine(final PPOrderLine ppOrderLine) { final int ppOrderLineId = ppOrderLine.getPpOrderLineId(); Check.errorIf(ppOrderLineId <= 0, "The given ppOrderCreatedEvent event has a ppOrderLine with ppOrderLineId={}; ppOrderLine={}", ppOrderLineId, ppOrderLine); } @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_PP_Order.Table_Name, ppOrder.getPpOrderId()); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderCreatedEvent.java
1
请完成以下Java代码
public static void applyFieldDeclaration(FieldDeclaration declaration, Object target) { Method setterMethod = ReflectUtil.getSetter(declaration.getName(), target.getClass(), declaration.getValue().getClass()); if(setterMethod != null) { try { setterMethod.invoke(target, declaration.getValue()); } catch (Exception e) { throw LOG.exceptionWhileApplyingFieldDeclatation(declaration.getName(), target.getClass().getName(), e); } } else { Field field = ReflectUtil.getField(declaration.getName(), target); ensureNotNull("Field definition uses unexisting field '" + declaration.getName() + "' on class " + target.getClass().getName(), "field", field); // Check if the delegate field's type is correct if (!fieldTypeCompatible(declaration, field)) {
throw LOG.incompatibleTypeForFieldDeclaration(declaration, target, field); } ReflectUtil.setField(field, target, declaration.getValue()); } } public static boolean fieldTypeCompatible(FieldDeclaration declaration, Field field) { if(declaration.getValue() != null) { return field.getType().isAssignableFrom(declaration.getValue().getClass()); } else { // Null can be set any field type return true; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClassDelegateUtil.java
1
请完成以下Java代码
protected boolean hasPlanItemDefinition(CmmnModel model, String elementId) { return model.getPrimaryCase().getAllCaseElements().containsKey(elementId); } protected CaseDefinition resolveCaseDefinition(CaseInstanceMigrationDocument document, CommandContext commandContext) { if (document.getMigrateToCaseDefinitionId() != null) { CaseDefinitionEntityManager caseDefinitionEntityManager = CommandContextUtil.getCaseDefinitionEntityManager(commandContext); return caseDefinitionEntityManager.findById(document.getMigrateToCaseDefinitionId()); } else { return resolveCaseDefinition(document.getMigrateToCaseDefinitionKey(), document.getMigrateToCaseDefinitionVersion(), document.getMigrateToCaseDefinitionTenantId(), commandContext); } } protected CaseDefinition resolveCaseDefinition(HistoricCaseInstanceMigrationDocument document, CommandContext commandContext) { if (document.getMigrateToCaseDefinitionId() != null) { CaseDefinitionEntityManager caseDefinitionEntityManager = CommandContextUtil.getCaseDefinitionEntityManager(commandContext); return caseDefinitionEntityManager.findById(document.getMigrateToCaseDefinitionId()); } else { return resolveCaseDefinition(document.getMigrateToCaseDefinitionKey(), document.getMigrateToCaseDefinitionVersion(), document.getMigrateToCaseDefinitionTenantId(), commandContext); } }
protected String printCaseDefinitionIdentifierMessage(CaseInstanceMigrationDocument document) { String id = document.getMigrateToCaseDefinitionId(); String key = document.getMigrateToCaseDefinitionKey(); Integer version = document.getMigrateToCaseDefinitionVersion(); String tenantId = document.getMigrateToCaseDefinitionTenantId(); return id != null ? "[id:'" + id + "']" : "[key:'" + key + "', version:'" + version + "', tenantId:'" + tenantId + "']"; } protected String printCaseDefinitionIdentifierMessage(HistoricCaseInstanceMigrationDocument document) { String id = document.getMigrateToCaseDefinitionId(); String key = document.getMigrateToCaseDefinitionKey(); Integer version = document.getMigrateToCaseDefinitionVersion(); String tenantId = document.getMigrateToCaseDefinitionTenantId(); return id != null ? "[id:'" + id + "']" : "[key:'" + key + "', version:'" + version + "', tenantId:'" + tenantId + "']"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
private <C> void setSharedObject(B http, Class<C> clazz, C object) { if (http.getSharedObject(clazz) == null) { http.setSharedObject(clazz, object); } } static class PathQueryRequestMatcher implements RequestMatcher { private final RequestMatcher matcher; PathQueryRequestMatcher(RequestMatcher pathMatcher, String... params) { List<RequestMatcher> matchers = new ArrayList<>(); matchers.add(pathMatcher); for (String param : params) { String[] parts = param.split("="); if (parts.length == 1) { matchers.add(new ParameterRequestMatcher(parts[0])); } else { matchers.add(new ParameterRequestMatcher(parts[0], parts[1])); } } this.matcher = new AndRequestMatcher(matchers);
} @Override public boolean matches(HttpServletRequest request) { return matcher(request).isMatch(); } @Override public MatchResult matcher(HttpServletRequest request) { return this.matcher.matcher(request); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\saml2\Saml2LoginConfigurer.java
2
请完成以下Java代码
public static class Builder { private final List<DocumentFilterDescriptor> descriptors = new ArrayList<>(); private Builder() { } public ImmutableDocumentFilterDescriptorsProvider build() { if (descriptors.isEmpty()) { return EMPTY; } return new ImmutableDocumentFilterDescriptorsProvider(descriptors); } public Builder addDescriptor(@NonNull final DocumentFilterDescriptor descriptor) { descriptors.add(descriptor); return this;
} public Builder addDescriptors(@NonNull final Collection<DocumentFilterDescriptor> descriptors) { if (descriptors.isEmpty()) { return this; } this.descriptors.addAll(descriptors); return this; } public Builder addDescriptors(@NonNull final DocumentFilterDescriptorsProvider provider) { addDescriptors(provider.getAll()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\ImmutableDocumentFilterDescriptorsProvider.java
1
请完成以下Java代码
public String docValidate(final PO po, final int timing) throws Exception { Check.assume(isDocument(), "PO '{}' is a document", po); if (timing == ModelValidator.TIMING_AFTER_COMPLETE && !documentBL.isReversalDocument(po)) { externalSystemScriptedExportConversionService .retrieveBestMatchingConfig(AdTableAndClientId.of(AdTableId.ofRepoId(po.get_Table_ID()), ClientId.ofRepoId(getAD_Client_ID())), po.get_ID()) .ifPresent(config -> executeInvokeScriptedExportConversionAction(config, po.get_ID())); } return null; } @NonNull public AdTableId getTableId() { return adTableId; } private void executeInvokeScriptedExportConversionAction( @NonNull final ExternalSystemScriptedExportConversionConfig config, final int recordId) { final int configTableId = tableDAO.retrieveTableId(I_ExternalSystem_Config_ScriptedExportConversion.Table_Name); try { trxManager.runAfterCommit(() -> { ProcessInfo.builder() .setCtx(getCtx())
.setRecord(configTableId, config.getId().getRepoId()) .setAD_ProcessByClassname(InvokeScriptedExportConversionAction.class.getName()) .addParameter(PARAM_EXTERNAL_REQUEST, COMMAND_CONVERT_MESSAGE_FROM_METASFRESH) .addParameter(PARAM_CHILD_CONFIG_ID, config.getId().getRepoId()) .addParameter(PARAM_Record_ID, recordId) .buildAndPrepareExecution() .executeSync(); }); } catch (final Exception e) { log.warn(InvokeScriptedExportConversionAction.class.getName() + " process failed for Config ID {}, Record ID: {}", config.getId(), recordId, e); } } private String getTableName() { return tableName; } private boolean isDocument() { return isDocument; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystemScriptedExportConversionInterceptor.java
1
请完成以下Java代码
public List<User> getAll() { return new ArrayList<>(users.values()); } @Override public void save(User user) { user.setId(UUID.randomUUID().toString()); users.put(user.getId(), user); } @Override public void save(Role role) { role.setId(UUID.randomUUID().toString()); roles.put(role.getId(), role); } @Override public Role getRoleById(String id) { return roles.get(id); }
@Override public Role getRoleByName(String name) { return roles.values() .stream() .filter(role -> role.getName().equalsIgnoreCase(name)) .findFirst() .orElse(null); } @Override public void deleteAll() { users.clear(); roles.clear(); } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\dtopattern\domain\InMemoryRepository.java
1
请完成以下Java代码
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 class Employee { private Integer employeeNumber; private String name; private Integer departmentId; public Employee(Integer employeeNumber, String name, Integer departmentId) { this.employeeNumber = employeeNumber; this.name = name; this.departmentId = departmentId; } public Integer getEmployeeNumber() { return employeeNumber; } public void setEmployeeNumber(Integer employeeNumber) { this.employeeNumber = employeeNumber; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\collection\filtering\Employee.java
1
请完成以下Java代码
public Object homemadeMatrixMultiplication(MatrixProvider matrixProvider) { return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix()); } @Benchmark public Object ejmlMatrixMultiplication(MatrixProvider matrixProvider) { SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix()); SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix()); return firstMatrix.mult(secondMatrix); } @Benchmark public Object apacheCommonsMatrixMultiplication(MatrixProvider matrixProvider) { RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix()); RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix()); return firstMatrix.multiply(secondMatrix); } @Benchmark public Object la4jMatrixMultiplication(MatrixProvider matrixProvider) { Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix()); Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix()); return firstMatrix.multiply(secondMatrix); }
@Benchmark public Object nd4jMatrixMultiplication(MatrixProvider matrixProvider) { INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix()); INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix()); return firstMatrix.mmul(secondMatrix); } @Benchmark public Object coltMatrixMultiplication(MatrixProvider matrixProvider) { DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense; DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix()); DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix()); Algebra algebra = new Algebra(); return algebra.mult(firstMatrix, secondMatrix); } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\matrices\benchmark\MatrixMultiplicationBenchmarking.java
1
请在Spring Boot框架中完成以下Java代码
public String audit(Model model, DwzAjax dwz, @RequestParam("userNo") String userNo , @RequestParam("auditStatus") String auditStatus) { rpUserPayConfigService.audit(userNo, auditStatus); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 :跳转编辑银行卡信息 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:config:edit") @RequestMapping(value = "/editBankUI", method = RequestMethod.GET) public String editBankUI(Model model, @RequestParam("userNo") String userNo) { RpUserBankAccount rpUserBankAccount = rpUserBankAccountService.getByUserNo(userNo); RpUserInfo rpUserInfo = rpUserInfoService.getDataByMerchentNo(userNo); model.addAttribute("BankCodeEnums", BankCodeEnum.toList()); model.addAttribute("BankAccountTypeEnums", BankAccountTypeEnum.toList()); model.addAttribute("CardTypeEnums", CardTypeEnum.toList()); model.addAttribute("rpUserBankAccount", rpUserBankAccount); model.addAttribute("rpUserInfo", rpUserInfo); return "pay/config/editBank"; }
/** * 函数功能说明 : 更新银行卡信息 * * @参数: @return * @return String * @throws */ @RequiresPermissions("pay:config:edit") @RequestMapping(value = "/editBank", method = RequestMethod.POST) public String editBank(Model model, RpUserBankAccount rpUserBankAccount, DwzAjax dwz) { rpUserBankAccountService.createOrUpdate(rpUserBankAccount); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\UserPayConfigController.java
2
请完成以下Java代码
public ProcessDialogBuilder setAD_Process_ID(final int AD_Process_ID) { this.AD_Process_ID = AD_Process_ID; return this; } int getAD_Process_ID() { return AD_Process_ID; } public ProcessDialogBuilder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } boolean isSOTrx() { return isSOTrx; } public ProcessDialogBuilder setWhereClause(final String whereClause) { this.whereClause = whereClause; return this; } String getWhereClause() { return whereClause; } public ProcessDialogBuilder setTableAndRecord(final int AD_Table_ID, final int Record_ID) { this.AD_Table_ID = AD_Table_ID; this.Record_ID = Record_ID; return this; } int getAD_Table_ID() { return AD_Table_ID; } int getRecord_ID() { return Record_ID; } /** * @param showHelp * @see X_AD_Process#SHOWHELP_AD_Reference_ID */ public ProcessDialogBuilder setShowHelp(final String showHelp) { this.showHelp = showHelp; return this; } String getShowHelp(final Supplier<String> defaultValueSupplier) { return showHelp != null ? showHelp : defaultValueSupplier.get(); } ProcessDialogBuilder skipResultsPanel() { skipResultsPanel = true; return this; } boolean isSkipResultsPanel() { return skipResultsPanel; } public ProcessDialogBuilder setAllowProcessReRun(final Boolean allowProcessReRun) { this.allowProcessReRun = allowProcessReRun; return this; } boolean isAllowProcessReRun(final Supplier<Boolean> defaultValueSupplier) { return allowProcessReRun != null ? allowProcessReRun : defaultValueSupplier.get(); }
public ProcessDialogBuilder setFromGridTab(GridTab gridTab) { final int windowNo = gridTab.getWindowNo(); final int tabNo = gridTab.getTabNo(); setWindowAndTabNo(windowNo, tabNo); setAdWindowId(gridTab.getAdWindowId()); setIsSOTrx(Env.isSOTrx(gridTab.getCtx(), windowNo)); setTableAndRecord(gridTab.getAD_Table_ID(), gridTab.getRecord_ID()); setWhereClause(gridTab.getTableModel().getSelectWhereClauseFinal()); skipResultsPanel(); return this; } public ProcessDialogBuilder setProcessExecutionListener(final IProcessExecutionListener processExecutionListener) { this.processExecutionListener = processExecutionListener; return this; } IProcessExecutionListener getProcessExecutionListener() { return processExecutionListener; } public ProcessDialogBuilder setPrintPreview(final boolean printPreview) { this._printPreview = printPreview; return this; } boolean isPrintPreview() { if (_printPreview != null) { return _printPreview; } return Ini.isPropertyBool(Ini.P_PRINTPREVIEW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessDialogBuilder.java
1
请完成以下Java代码
public ITabCallout build() { if (tabCalloutsAll.isEmpty()) { return ITabCallout.NULL; } else if (tabCalloutsAll.size() == 1) { return tabCalloutsAll.get(0); } else { return new CompositeTabCallout(tabCalloutsAll); } }
public Builder addTabCallout(final ITabCallout tabCallout) { Check.assumeNotNull(tabCallout, "tabCallout not null"); if (tabCalloutsAll.contains(tabCallout)) { return this; } tabCalloutsAll.add(tabCallout); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\impl\CompositeTabCallout.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class); } @Override public void setPP_Product_BOM(final org.eevolution.model.I_PP_Product_BOM PP_Product_BOM) { set_ValueFromPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class, PP_Product_BOM); } @Override public void setPP_Product_BOM_ID (final int PP_Product_BOM_ID) { if (PP_Product_BOM_ID < 1) set_Value (COLUMNNAME_PP_Product_BOM_ID, null); else set_Value (COLUMNNAME_PP_Product_BOM_ID, PP_Product_BOM_ID); } @Override public int getPP_Product_BOM_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOM_ID); } @Override public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class); } @Override public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine); } @Override public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) { if (PP_Product_BOMLine_ID < 1) set_Value (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_Value (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
} @Override public void setQtyBOM (final @Nullable BigDecimal QtyBOM) { set_Value (COLUMNNAME_QtyBOM, QtyBOM); } @Override public BigDecimal getQtyBOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSel_Product_ID (final int Sel_Product_ID) { if (Sel_Product_ID < 1) set_Value (COLUMNNAME_Sel_Product_ID, null); else set_Value (COLUMNNAME_Sel_Product_ID, Sel_Product_ID); } @Override public int getSel_Product_ID() { return get_ValueAsInt(COLUMNNAME_Sel_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setT_BOMLine_ID (final int T_BOMLine_ID) { if (T_BOMLine_ID < 1) set_ValueNoCheck (COLUMNNAME_T_BOMLine_ID, null); else set_ValueNoCheck (COLUMNNAME_T_BOMLine_ID, T_BOMLine_ID); } @Override public int getT_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_T_BOMLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_T_BOMLine.java
1
请在Spring Boot框架中完成以下Java代码
public Job dataSourceItemReaderJob() throws Exception { return jobBuilderFactory.get("dataSourceItemReaderJob") .start(step()) .build(); } private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(dataSourceItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> dataSourceItemReader() throws Exception { JdbcPagingItemReader<TestData> reader = new JdbcPagingItemReader<>(); reader.setDataSource(dataSource); // 设置数据源 reader.setFetchSize(5); // 每次取多少条记录 reader.setPageSize(5); // 设置每页数据量 // 指定sql查询语句 select id,field1,field2,field3 from TEST MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider(); provider.setSelectClause("id,field1,field2,field3"); //设置查询字段 provider.setFromClause("from TEST"); // 设置从哪张表查询 // 将读取到的数据转换为TestData对象 reader.setRowMapper((resultSet, rowNum) -> { TestData data = new TestData(); data.setId(resultSet.getInt(1));
data.setField1(resultSet.getString(2)); // 读取第一个字段,类型为String data.setField2(resultSet.getString(3)); data.setField3(resultSet.getString(4)); return data; }); Map<String, Order> sort = new HashMap<>(1); sort.put("id", Order.ASCENDING); provider.setSortKeys(sort); // 设置排序,通过id 升序 reader.setQueryProvider(provider); // 设置namedParameterJdbcTemplate等属性 reader.afterPropertiesSet(); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\DataSourceItemReaderDemo.java
2
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = -3258839839160856613L; private String id; private String userName; private String passWord; public User(String userName, String passWord) { this.userName = userName; this.passWord = passWord; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 4-7 课:Spring Boot 简单集成 MongoDB\spring-boot-multi-mongodb\src\main\java\com\neo\model\User.java
1
请完成以下Java代码
public String getStrackTrace(String trxName) { return Services.get(IOpenTrxBL.class).getCreationStackTrace(trxName); } @ManagedOperation public String[] getServerContext() { final Properties ctx = Env.getCtx(); String[] context = Env.getEntireContext(ctx); Arrays.sort(context); return context; } @ManagedOperation public void setLogLevel(String levelName) { LogManager.setLevel(levelName); } @ManagedOperation public String getLogLevel()
{ final Level level = LogManager.getLevel(); return level == null ? null : level.toString(); } @ManagedOperation public void runFinalization() { System.runFinalization(); } @ManagedOperation public void resetLocalCache() { CacheMgt.get().reset(); } @ManagedOperation public void rotateMigrationScriptFile() { MigrationScriptFileLoggerHolder.closeMigrationScriptFiles(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\jmx\Metasfresh.java
1
请完成以下Java代码
public ValueMapperException cannotSerializeVariable(String variableName, Throwable e) { return new ValueMapperException(exceptionMessage("025", "Cannot serialize variable '{}'", variableName), e); } public void logDataFormats(Collection<DataFormat> formats) { if (isInfoEnabled()) { for (DataFormat format : formats) { logDataFormat(format); } } } protected void logDataFormat(DataFormat dataFormat) { logInfo("025", "Discovered data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName()); } public void logDataFormatProvider(DataFormatProvider provider) { if (isInfoEnabled()) { logInfo("026", "Discovered data format provider: {}[name = {}]", provider.getClass().getName(), provider.getDataFormatName()); } }
@SuppressWarnings("rawtypes") public void logDataFormatConfigurator(DataFormatConfigurator configurator) { if (isInfoEnabled()) { logInfo("027", "Discovered data format configurator: {}[dataformat = {}]", configurator.getClass(), configurator.getDataFormatClass().getName()); } } public ExternalTaskClientException multipleProvidersForDataformat(String dataFormatName) { return new ExternalTaskClientException(exceptionMessage("028", "Multiple providers found for dataformat '{}'", dataFormatName)); } public ExternalTaskClientException passNullValueParameter(String parameterName) { return new ExternalTaskClientException(exceptionMessage( "030", "Null value is not allowed as '{}'", parameterName)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientLogger.java
1
请完成以下Java代码
class WorkflowNodeModel { private final IADWorkflowDAO workflowDAO = Services.get(IADWorkflowDAO.class); @NonNull private final WorkflowModel workflowModel; @NonNull private final WFNode node; private Integer xPosition; private Integer yPosition; public WorkflowNodeModel( @NonNull final WorkflowModel workflowModel, @NonNull final WFNode node) { this.workflowModel = workflowModel; this.node = node; } @Override public String toString() { final ImmutableList<String> nextNodeNames = getTransitions(ClientId.SYSTEM) .stream() .map(transition -> transition.getNextNode().getName().getDefaultValue()) .collect(ImmutableList.toImmutableList()); return MoreObjects.toStringHelper(this) .add("name", getName().getDefaultValue()) .add("next", nextNodeNames) .toString(); } public WFNode unbox() { return node; } public @NonNull WFNodeId getId() {return node.getId();} public @NonNull WorkflowId getWorkflowId() { return workflowModel.getId(); } public @NonNull ClientId getClientId() {return node.getClientId();}
public @NonNull WFNodeAction getAction() {return node.getAction();} public @NonNull ITranslatableString getName() {return node.getName();} @NonNull public ITranslatableString getDescription() {return node.getDescription();} @NonNull public ITranslatableString getHelp() {return node.getHelp();} public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();} public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();} public void setXPosition(final int x) { this.xPosition = x; } public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();} public void setYPosition(final int y) { this.yPosition = y; } public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId) { return node.getTransitions(clientId) .stream() .map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition)) .collect(ImmutableList.toImmutableList()); } public void saveEx() { workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder() .nodeId(getId()) .xPosition(getXPosition()) .yPosition(getYPosition()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
1
请完成以下Java代码
public static BPartnerCompositeLookupKey ofIdentifierString(@NonNull final IdentifierString bpartnerIdentifier) { switch (bpartnerIdentifier.getType()) { case EXTERNAL_ID: return BPartnerCompositeLookupKey.ofJsonExternalId(bpartnerIdentifier.asJsonExternalId()); case VALUE: return BPartnerCompositeLookupKey.ofCode(bpartnerIdentifier.asValue()); case GLN: return BPartnerCompositeLookupKey.ofGln(bpartnerIdentifier.asGLN()); case GLN_WITH_LABEL: return BPartnerCompositeLookupKey.ofGlnWithLabel(bpartnerIdentifier.asGlnWithLabel()); case METASFRESH_ID: return BPartnerCompositeLookupKey.ofMetasfreshId(bpartnerIdentifier.asMetasfreshId()); default: throw new AdempiereException("Unexpected type=" + bpartnerIdentifier.getType()); } } MetasfreshId metasfreshId; JsonExternalId jsonExternalId;
String code; GLN gln; GlnWithLabel glnWithLabel; private BPartnerCompositeLookupKey( @Nullable final MetasfreshId metasfreshId, @Nullable final JsonExternalId jsonExternalId, @Nullable final String code, @Nullable final GLN gln, @Nullable final GlnWithLabel glnWithLabel) { this.metasfreshId = metasfreshId; this.jsonExternalId = jsonExternalId; this.code = code; this.gln = gln; this.glnWithLabel = glnWithLabel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerCompositeLookupKey.java
1
请完成以下Java代码
public void onMessage(List<ConsumerRecord<K, V>> records, @Nullable Acknowledgment acknowledgment, @Nullable Consumer<?, ?> consumer) { final RecordFilterStrategy<K, V> recordFilterStrategy = getRecordFilterStrategy(); final List<ConsumerRecord<K, V>> consumerRecords = recordFilterStrategy.filterBatch(records); Assert.state(consumerRecords != null, "filter returned null from filterBatch"); if (recordFilterStrategy.ignoreEmptyBatch() && consumerRecords.isEmpty() && acknowledgment != null) { acknowledgment.acknowledge(); } else if (!consumerRecords.isEmpty() || this.consumerAware || (!this.ackDiscarded && this.delegateType.equals(ListenerType.ACKNOWLEDGING))) { invokeDelegate(consumerRecords, acknowledgment, consumer); } else { if (this.ackDiscarded && acknowledgment != null) { acknowledgment.acknowledge(); } } } private void invokeDelegate(List<ConsumerRecord<K, V>> consumerRecords, @Nullable Acknowledgment acknowledgment, @Nullable Consumer<?, ?> consumer) { switch (this.delegateType) { case ACKNOWLEDGING_CONSUMER_AWARE: this.delegate.onMessage(consumerRecords, acknowledgment, consumer); break; case ACKNOWLEDGING: this.delegate.onMessage(consumerRecords, acknowledgment); break; case CONSUMER_AWARE: this.delegate.onMessage(consumerRecords, consumer); break;
case SIMPLE: this.delegate.onMessage(consumerRecords); } } /* * Since the container uses the delegate's type to determine which method to call, we * must implement them all. */ @Override public void onMessage(List<ConsumerRecord<K, V>> data) { onMessage(data, null, null); // NOSONAR } @Override public void onMessage(List<ConsumerRecord<K, V>> data, @Nullable Acknowledgment acknowledgment) { onMessage(data, acknowledgment, null); // NOSONAR } @Override public void onMessage(List<ConsumerRecord<K, V>> data, @Nullable Consumer<?, ?> consumer) { onMessage(data, null, consumer); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\FilteringBatchMessageListenerAdapter.java
1
请完成以下Java代码
public AccountId getOrCreateWithinTrx(@NonNull final AccountDimension dimension) { return getOrCreate(dimension, () -> InterfaceWrapperHelper.newInstance(I_C_ValidCombination.class)); } @Override @NonNull public AccountId getOrCreateOutOfTrx(@NonNull final AccountDimension dimension) { return getOrCreate(dimension, () -> InterfaceWrapperHelper.newInstanceOutOfTrx(I_C_ValidCombination.class)); } @NonNull private AccountId getOrCreate( @NonNull final AccountDimension dimension, @NonNull final Supplier<I_C_ValidCombination> newInstanceSupplier) { return Optional.ofNullable(retrieveAccount(Env.getCtx(), dimension)) .map(existingAccount -> AccountId.ofRepoId(existingAccount.getC_ValidCombination_ID())) .orElseGet(() -> { final I_C_ValidCombination vc = newInstanceSupplier.get(); return setValuesAndSave(vc, dimension); }); } @NonNull private static AccountId setValuesAndSave( @NonNull final I_C_ValidCombination vc, @NonNull final AccountDimension dimension)
{ vc.setAD_Org_ID(dimension.getAD_Org_ID()); vc.setC_AcctSchema_ID(AcctSchemaId.toRepoId(dimension.getAcctSchemaId())); vc.setAccount_ID(dimension.getC_ElementValue_ID()); vc.setC_SubAcct_ID(dimension.getC_SubAcct_ID()); vc.setM_Product_ID(dimension.getM_Product_ID()); vc.setC_BPartner_ID(dimension.getC_BPartner_ID()); vc.setAD_OrgTrx_ID(dimension.getAD_OrgTrx_ID()); vc.setC_LocFrom_ID(dimension.getC_LocFrom_ID()); vc.setC_LocTo_ID(dimension.getC_LocTo_ID()); vc.setC_SalesRegion_ID(dimension.getC_SalesRegion_ID()); vc.setC_Project_ID(dimension.getC_Project_ID()); vc.setC_Campaign_ID(dimension.getC_Campaign_ID()); vc.setC_Activity_ID(dimension.getC_Activity_ID()); vc.setUser1_ID(dimension.getUser1_ID()); vc.setUser2_ID(dimension.getUser2_ID()); vc.setUserElement1_ID(dimension.getUserElement1_ID()); vc.setUserElement2_ID(dimension.getUserElement2_ID()); vc.setUserElementString1(dimension.getUserElementString1()); vc.setUserElementString2(dimension.getUserElementString2()); vc.setUserElementString3(dimension.getUserElementString3()); vc.setUserElementString4(dimension.getUserElementString4()); vc.setUserElementString5(dimension.getUserElementString5()); vc.setUserElementString6(dimension.getUserElementString6()); vc.setUserElementString7(dimension.getUserElementString7()); InterfaceWrapperHelper.save(vc); return AccountId.ofRepoId(vc.getC_ValidCombination_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AccountDAO.java
1
请完成以下Java代码
public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{ // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Java代码
public BigDecimal retrievePriceStd( final @NonNull OrgId orgId, final int productId, final int partnerId, final int priceListId, @Nullable final CountryId countryId, final BigDecimal qty, final boolean soTrx) { final MProductPricing pricing = new MProductPricing( orgId, productId, partnerId, countryId, qty, soTrx); pricing.setM_PriceList_ID(priceListId); final BigDecimal priceStd = pricing.getPriceStd(); if (priceStd.signum() == 0) { pricing.throwProductNotOnPriceListException(); } return priceStd; } @Override public Collection<I_M_ProductScalePrice> retrieveScalePrices(final int productPriceId, final String trxName) { return new Query(Env.getCtx(), I_M_ProductScalePrice.Table_Name, WHERE_PRODUCT_SCALE_PRICE, trxName) .setParameters(productPriceId) .setClient_ID() .setOnlyActiveRecords(true) .list(I_M_ProductScalePrice.class); } private I_M_ProductScalePrice createScalePrice(final String trxName) { return InterfaceWrapperHelper.newInstance(I_M_ProductScalePrice.class, PlainContextAware.newWithTrxName(Env.getCtx(), trxName)); } /** * Returns an existing scale price or (if <code>createNew</code> is true) creates a new one. */ @Nullable @Override public I_M_ProductScalePrice retrieveOrCreateScalePrices( final int productPriceId, final BigDecimal qty, final boolean createNew, final String trxName) { final PreparedStatement pstmt = DB.prepareStatement( SQL_SCALEPRICE_FOR_QTY, trxName);
ResultSet rs = null; try { pstmt.setInt(1, productPriceId); pstmt.setBigDecimal(2, qty); pstmt.setMaxRows(1); rs = pstmt.executeQuery(); if (rs.next()) { logger.debug("Returning existing instance for M_ProductPrice " + productPriceId + " and quantity " + qty); return new X_M_ProductScalePrice(Env.getCtx(), rs, trxName); } if (createNew) { logger.debug("Returning new instance for M_ProductPrice " + productPriceId + " and quantity " + qty); final I_M_ProductScalePrice newInstance = createScalePrice(trxName); newInstance.setM_ProductPrice_ID(productPriceId); newInstance.setQty(qty); return newInstance; } return null; } catch (final SQLException e) { throw new DBException(e, SQL_SCALEPRICE_FOR_QTY); } finally { DB.close(rs, pstmt); } } @Override public I_M_ProductScalePrice retrieveScalePrices(final int productPriceId, final BigDecimal qty, final String trxName) { return retrieveOrCreateScalePrices(productPriceId, qty, false, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\ProductPA.java
1
请在Spring Boot框架中完成以下Java代码
public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Saml2LogoutRequest.Builder} for further configurations * @since 5.8 */
public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutResponse} * @return a constructed {@link Saml2LogoutResponse} */ public Saml2LogoutResponse build() { return new Saml2LogoutResponse(this.location, this.binding, this.parameters, this.encoder); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutResponse.java
2
请完成以下Spring Boot application配置
spring: security: saml2: relyingparty: registration: okta: signing: credentials: - private-key-location: classpath:local.key certificate-location: classpath:local.crt singlelogout: url: https://dev-56617222.okta.com/app/dev-56617222_springbootsaml_1/exk8b5jr6vYQqVXp45d7/slo/saml
binding: POST response-url: "{baseUrl}/logout/saml2/slo" assertingparty: metadata-uri: "classpath:metadata/metadata-idp-okta.xml"
repos\tutorials-master\spring-security-modules\spring-security-saml2\src\main\resources\application.yml
2
请完成以下Java代码
public class ProxyIpFilter extends ChannelInboundHandlerAdapter { private MqttTransportContext context; public ProxyIpFilter(MqttTransportContext context) { this.context = context; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.trace("[{}] Received msg: {}", ctx.channel().id(), msg); if (msg instanceof HAProxyMessage) { HAProxyMessage proxyMsg = (HAProxyMessage) msg; if (proxyMsg.sourceAddress() != null && proxyMsg.sourcePort() > 0) { InetSocketAddress address = new InetSocketAddress(proxyMsg.sourceAddress(), proxyMsg.sourcePort()); if (!context.checkAddress(address)) { closeChannel(ctx); } else { log.trace("[{}] Setting address: {}", ctx.channel().id(), address); ctx.channel().attr(MqttTransportService.ADDRESS).set(address); // We no longer need this channel in the pipeline. Similar to HAProxyMessageDecoder ctx.pipeline().remove(this); } } else { log.trace("Received local health-check connection message: {}", proxyMsg); closeChannel(ctx); } } }
private void closeChannel(ChannelHandlerContext ctx) { while (ctx.pipeline().last() != this) { ChannelHandler handler = ctx.pipeline().removeLast(); if (handler instanceof ChannelInboundHandlerAdapter) { try { ((ChannelInboundHandlerAdapter) handler).channelUnregistered(ctx); } catch (Exception e) { log.error("Failed to unregister channel: [{}]", ctx, e); } } } ctx.pipeline().remove(this); ctx.close(); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\limits\ProxyIpFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class PurchaseDemand { PurchaseDemandId id = PurchaseDemandId.createNew(); @NonNull OrgId orgId; /** might be needed when creating new purchase candidates. */ @NonNull WarehouseId warehouseId; @NonNull ProductId productId; @NonNull AttributeSetInstanceId attributeSetInstanceId; @NonNull Quantity qtyToDeliver; @Nullable CurrencyId currencyIdOrNull;
@NonNull ZonedDateTime salesPreparationDate; @Nullable OrderAndLineId salesOrderAndLineIdOrNull; /** * A demand instance might be (partially) backed by already existing purchase candidates. * We need to hold their IDs to sync with them later. */ @Singular List<PurchaseCandidateId> existingPurchaseCandidateIds; public int getUOMId() { return qtyToDeliver.getUOMId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseDemand.java
2
请在Spring Boot框架中完成以下Java代码
public ArticleMapping updateInsuranceContract(String albertaApiKey, String tenant, String id, Article body) throws ApiException { ApiResponse<ArticleMapping> resp = updateInsuranceContractWithHttpInfo(albertaApiKey, tenant, id, body); return resp.getData(); } /** * Krankenkassenvertrag in Alberta ändern * ändert einen Krankenkassenvertrag in Alberta * @param albertaApiKey (required) * @param tenant (required) * @param id (required) * @param body article to update (optional) * @return ApiResponse&lt;ArticleMapping&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<ArticleMapping> updateInsuranceContractWithHttpInfo(String albertaApiKey, String tenant, String id, Article body) throws ApiException { com.squareup.okhttp.Call call = updateInsuranceContractValidateBeforeCall(albertaApiKey, tenant, id, body, null, null); Type localVarReturnType = new TypeToken<ArticleMapping>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Krankenkassenvertrag in Alberta ändern (asynchronously) * ändert einen Krankenkassenvertrag in Alberta * @param albertaApiKey (required) * @param tenant (required) * @param id (required) * @param body article to update (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call updateInsuranceContractAsync(String albertaApiKey, String tenant, String id, Article body, final ApiCallback<ArticleMapping> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = updateInsuranceContractValidateBeforeCall(albertaApiKey, tenant, id, body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<ArticleMapping>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\api\DefaultApi.java
2
请在Spring Boot框架中完成以下Java代码
public class HistoricProcessInstanceCommentCollectionResource extends HistoricProcessInstanceBaseResource { @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected HistoryService historyService; @Autowired protected TaskService taskService; @ApiOperation(value = "List comments on a historic process instance", nickname="listHistoricProcessInstanceComments", tags = { "History Process" }, notes = "") @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the process instance was found and the comments are returned."), @ApiResponse(code = 404, message = "Indicates that the historic process instance could not be found.") }) @GetMapping(value = "/history/historic-process-instances/{processInstanceId}/comments", produces = "application/json") public List<CommentResponse> getComments(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId) { HistoricProcessInstance instance = getHistoricProcessInstanceFromRequest(processInstanceId); return restResponseFactory.createRestCommentList(taskService.getProcessInstanceComments(instance.getId())); }
@ApiOperation(value = "Create a new comment on a historic process instance", tags = { "History Process" }, notes = "Parameter saveProcessInstanceId is optional, if true save process instance id of task with comment.", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the comment was created and the result is returned."), @ApiResponse(code = 400, message = "Indicates the comment is missing from the request."), @ApiResponse(code = 404, message = "Indicates that the historic process instance could not be found.") }) @PostMapping(value = "/history/historic-process-instances/{processInstanceId}/comments", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public CommentResponse createComment(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId, @RequestBody CommentResponse comment) { HistoricProcessInstance instance = getHistoricProcessInstanceFromRequest(processInstanceId); if (comment.getMessage() == null) { throw new FlowableIllegalArgumentException("Comment text is required."); } Comment createdComment = taskService.addComment(null, instance.getId(), comment.getMessage()); return restResponseFactory.createRestComment(createdComment); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricProcessInstanceCommentCollectionResource.java
2
请完成以下Java代码
public class Authentication { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); client.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { String credential = Credentials.basic("user", "password"); return response.request().newBuilder() .header("Authorization", credential) .build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null; } }); Request request = new Request.Builder() .url("http://www.baidu.com") .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("服务器端错误: " + response); } System.out.println(response.body().string()); } }
repos\spring-boot-quick-master\quick-okhttp\src\main\java\com\quick\okhttp\Authentication.java
1
请完成以下Java代码
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID) { if (ES_FTS_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID); } @Override public int getES_FTS_Config_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID); } @Override public void setES_Index (final java.lang.String ES_Index) { set_Value (COLUMNNAME_ES_Index, ES_Index); }
@Override public java.lang.String getES_Index() { return get_ValueAsString(COLUMNNAME_ES_Index); } @Override public void setES_QueryCommand (final java.lang.String ES_QueryCommand) { set_Value (COLUMNNAME_ES_QueryCommand, ES_QueryCommand); } @Override public java.lang.String getES_QueryCommand() { return get_ValueAsString(COLUMNNAME_ES_QueryCommand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config.java
1
请完成以下Java代码
public static DocumentFilter createFilter(@NonNull final IHUQueryBuilder huQuery) { final HUIdsFilterData filterData = HUIdsFilterData.ofHUQuery(huQuery); return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } public static DocumentFilter createFilter(@NonNull final HUIdsFilterData filterData) { return DocumentFilter.singleParameterFilter(FILTER_ID, FILTER_PARAM_Data, Operator.EQUAL, filterData); } static HUIdsFilterData extractFilterData(@NonNull final DocumentFilter huIdsFilter) { if (isNotHUIdsFilter(huIdsFilter)) { throw new AdempiereException("Not an HUIds filter: " + huIdsFilter); } final HUIdsFilterData huIdsFilterData = (HUIdsFilterData)huIdsFilter.getParameter(FILTER_PARAM_Data).getValue(); if (huIdsFilterData == null)
{ throw new AdempiereException("No " + HUIdsFilterData.class + " found for " + huIdsFilter); } return huIdsFilterData; } public static Optional<HUIdsFilterData> extractFilterData(@Nullable final DocumentFilterList filters) { return findExisting(filters).map(HUIdsFilterHelper::extractFilterData); } public static boolean isNotHUIdsFilter(final DocumentFilter filter) { return !FILTER_ID.equals(filter.getFilterId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class FilterChainBeanDefinitionParser implements BeanDefinitionParser { private static final String ATT_REQUEST_MATCHER_REF = "request-matcher-ref"; @Override public BeanDefinition parse(Element elt, ParserContext pc) { MatcherType matcherType = MatcherType.fromElementOrMvc(elt); String path = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); String requestMatcher = elt.getAttribute(ATT_REQUEST_MATCHER_REF); String filters = elt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS); BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DefaultSecurityFilterChain.class); if (StringUtils.hasText(path)) { Assert.isTrue(!StringUtils.hasText(requestMatcher), ""); builder.addConstructorArgValue(matcherType.createMatcher(pc, path, null)); } else { Assert.isTrue(StringUtils.hasText(requestMatcher), ""); builder.addConstructorArgReference(requestMatcher); }
if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) { builder.addConstructorArgValue(Collections.EMPTY_LIST); } else { String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, ","); ManagedList<RuntimeBeanReference> filterChain = new ManagedList<>(filterBeanNames.length); for (String name : filterBeanNames) { filterChain.add(new RuntimeBeanReference(name)); } builder.addConstructorArgValue(filterChain); } return builder.getBeanDefinition(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\FilterChainBeanDefinitionParser.java
2
请完成以下Java代码
public Map<Integer, List<String>> streamCollectByStringLength(List<String> source, Supplier<Map<Integer, List<String>>> mapSupplier, Supplier<List<String>> listSupplier) { BiConsumer<Map<Integer, List<String>>, String> accumulator = (response, element) -> { Integer key = element.length(); List<String> values = response.getOrDefault(key, listSupplier.get()); values.add(element); response.put(key, values); }; BiConsumer<Map<Integer, List<String>>, Map<Integer, List<String>>> combiner = (res1, res2) -> { res1.putAll(res2); }; return source.stream() .collect(mapSupplier, accumulator, combiner); } public Map<Integer, List<String>> collectorToMapByStringLength(List<String> source, Supplier<Map<Integer, List<String>>> mapSupplier, Supplier<List<String>> listSupplier) { Function<String, Integer> keyMapper = String::length; Function<String, List<String>> valueMapper = (element) -> {
List<String> collection = listSupplier.get(); collection.add(element); return collection; }; BinaryOperator<List<String>> mergeFunction = (existing, replacement) -> { existing.addAll(replacement); return existing; }; return source.stream() .collect(Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier)); } }
repos\tutorials-master\core-java-modules\core-java-collections-conversions-4\src\main\java\com\baeldung\convertlisttomap\ListToMapConverter.java
1
请完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public long getValue() { return value; } public void setValue(long value) { this.value = value; }
public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "Order [orderId=" + orderId + ", desc=" + desc + ", value=" + value + "]"; } }
repos\tutorials-master\core-java-modules\core-java-string-operations-12\src\main\java\com\baeldung\tostring\Order.java
1
请在Spring Boot框架中完成以下Java代码
public class PrintingClientStandaloneService { private final transient Logger logger = Logger.getLogger(getClass().getName()); public static void main(final String[] args) { new PrintingClientStandaloneService().run(); } /** * Thanks to http://stackoverflow.com/questions/3777055/reading-manifest-mf-file-from-jar-file-using-java */ private void logVersionInfo() { try { final Enumeration<URL> resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME); while (resEnum.hasMoreElements()) { try { final URL url = resEnum.nextElement(); final InputStream is = url.openStream(); if (is != null) { final Manifest manifest = new Manifest(is); final Attributes mainAttribs = manifest.getMainAttributes(); final String version = mainAttribs.getValue("Implementation-Version"); if (version != null) { logger.info("Resource " + url + " has version " + version); } } } catch (final Exception e) { // Silently ignore wrong manifests on classpath? } } }
catch (final IOException e1) { // Silently ignore wrong manifests on classpath? } } private void run() { final Context context = Context.getContext(); context.addSource(new ConfigFileContext()); logVersionInfo(); // // Start the client final PrintingClient client = new PrintingClient(); client.start(); final Thread clientThread = client.getDaemonThread(); try { clientThread.join(); } catch (final InterruptedException e) { logger.log(Level.INFO, "Interrupted. Exiting.", e); client.stop(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\PrintingClientStandaloneService.java
2
请完成以下Java代码
public static Result addOne(String desformCode, JSONObject formData, String token) { return addOrEditOne(desformCode, formData, token, HttpMethod.POST); } /** * 修改数据 * * @param desformCode * @param formData * @param token * @return */ public static Result editOne(String desformCode, JSONObject formData, String token) { return addOrEditOne(desformCode, formData, token, HttpMethod.PUT); } private static Result addOrEditOne(String desformCode, JSONObject formData, String token, HttpMethod method) { String url = getBaseUrl(desformCode).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, method, headers, null, formData, JSONObject.class); return packageReturn(result); } /** * 删除数据 * * @param desformCode * @param dataId * @param token * @return */ public static Result removeOne(String desformCode, String dataId, String token) { String url = getBaseUrl(desformCode, dataId).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class); return packageReturn(result); } private static Result packageReturn(ResponseEntity<JSONObject> result) { if (result.getBody() != null) { return result.getBody().toJavaObject(Result.class); } return Result.error("操作失败"); } private static StringBuilder getBaseUrl() { StringBuilder builder = new StringBuilder(domain).append(path); builder.append("/desform/api");
return builder; } private static StringBuilder getBaseUrl(String desformCode, String dataId) { StringBuilder builder = getBaseUrl(); builder.append("/").append(desformCode); if (dataId != null) { builder.append("/").append(dataId); } return builder; } private static StringBuilder getBaseUrl(String desformCode) { return getBaseUrl(desformCode, null); } private static HttpHeaders getHeaders(String token) { HttpHeaders headers = new HttpHeaders(); String mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE; headers.setContentType(MediaType.parseMediaType(mediaType)); headers.set("Accept", mediaType); headers.set("X-Access-Token", token); return headers; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\RestDesformUtil.java
1
请完成以下Java代码
public class TaskCompletedListenerDelegate implements ActivitiEventListener { private List<TaskRuntimeEventListener<TaskCompletedEvent>> listeners; private ToTaskCompletedConverter taskCompletedConverter; public TaskCompletedListenerDelegate( List<TaskRuntimeEventListener<TaskCompletedEvent>> listeners, ToTaskCompletedConverter taskCompletedConverter ) { this.listeners = listeners; this.taskCompletedConverter = taskCompletedConverter; } @Override public void onEvent(ActivitiEvent event) {
if (event instanceof ActivitiEntityEvent) { taskCompletedConverter .from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (TaskRuntimeEventListener<TaskCompletedEvent> listener : listeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskCompletedListenerDelegate.java
1
请完成以下Java代码
private void setValueForField(Class clazz, Field field, List<BaseComponent> componentList) throws IllegalAccessException { // 获取Processor对象 Object processor = applicationContext.getBean(clazz); // 将field设为public field.setAccessible(true); // 赋值 field.set(processor, componentList); System.out.println(processor); System.out.println(componentList); System.out.println("---------------"); } /** * 初始化componentList * @param injectComponents componentList上的注解 */ private List<BaseComponent> initComponentList(InjectComponents injectComponents) throws IllegalAccessException, InstantiationException { List<BaseComponent> componentList = Lists.newArrayList(); // 获取Components Class[] componentClassList = injectComponents.value(); if (componentClassList == null || componentClassList.length <= 0) { return componentList;
} // 遍历components for (Class<BaseComponent> componentClass : componentClassList) { // 获取IOC容器中的Component对象 BaseComponent componentInstance = applicationContext.getBean(componentClass); // 加入容器 componentList.add(componentInstance); } return componentList; } /** * 获取需要扫描的包名 */ private String getPackage() { PackageScan packageScan = AnnotationUtil.getAnnotationValueByClass(this.getClass(), PackageScan.class); return packageScan.value(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\init\InitComponentList.java
1
请完成以下Java代码
protected void resolveProcessDefinitionInfo() { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(); if (processEngineConfiguration == null) { // We are outside of a command context so do not try to resolve anything return; } ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(processDefinitionId, false, processEngineConfiguration); if (processDefinition == null) { throw new FlowableException("Cannot get process definition for id " + processDefinitionId + " for " + this); } this.processDefinitionKey = processDefinition.getKey(); this.processDefinitionName = processDefinition.getName(); this.processDefinitionVersion = processDefinition.getVersion(); this.processDefinitionCategory = processDefinition.getCategory(); this.deploymentId = processDefinition.getDeploymentId(); } // toString ///////////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder strb; if (isProcessInstanceType()) { strb = new StringBuilder("ProcessInstance[" + getId() + "] - definition '" + getProcessDefinitionId() + "'"); } else { strb = new StringBuilder(); if (isScope) { strb.append("Scoped execution[ id '").append(getId()); } else if (isMultiInstanceRoot) { strb.append("Multi instance root execution[ id '").append(getId()); } else { strb.append("Execution[ id '").append(getId()); } strb.append("' ]"); strb.append(" - definition '").append(getProcessDefinitionId()).append("'"); if (activityId != null) { strb.append(" - activity '").append(activityId).append("'");
} if (parentId != null) { strb.append(" - parent '").append(parentId).append("'"); } } if (StringUtils.isNotEmpty(tenantId)) { strb.append(" - tenantId '").append(tenantId).append("'"); } return strb.toString(); } @Override protected VariableServiceConfiguration getVariableServiceConfiguration() { return CommandContextUtil.getProcessEngineConfiguration().getVariableServiceConfiguration(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ExecutionEntityImpl.java
1
请完成以下Java代码
public void setCarrier_Service_ID (final int Carrier_Service_ID) { if (Carrier_Service_ID < 1) set_Value (COLUMNNAME_Carrier_Service_ID, null); else set_Value (COLUMNNAME_Carrier_Service_ID, Carrier_Service_ID); } @Override public int getCarrier_Service_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_Service_ID); } @Override public void setCarrier_ShipmentOrder_ID (final int Carrier_ShipmentOrder_ID) { if (Carrier_ShipmentOrder_ID < 1) set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, null); else set_Value (COLUMNNAME_Carrier_ShipmentOrder_ID, Carrier_ShipmentOrder_ID); } @Override public int getCarrier_ShipmentOrder_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_ID);
} @Override public void setCarrier_ShipmentOrder_Service_ID (final int Carrier_ShipmentOrder_Service_ID) { if (Carrier_ShipmentOrder_Service_ID < 1) set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Service_ID, null); else set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Service_ID, Carrier_ShipmentOrder_Service_ID); } @Override public int getCarrier_ShipmentOrder_Service_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Service_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Service.java
1
请完成以下Java代码
private void dbUpdateSubProducer(@NonNull final ImportRecordsSelection selection) { // Set M_Warehouse_ID final StringBuilder sql = new StringBuilder("UPDATE I_Inventory i ") .append("SET SubProducer_BPartner_ID=(SELECT C_BPartner_ID FROM C_BPartner bp WHERE i.SubProducerBPartner_Value=bp.value) ") .append("WHERE SubProducer_BPartner_ID IS NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause("i")); DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); } public int countRecordsWithErrors(@NonNull final ImportRecordsSelection selection) { final String sql = "SELECT COUNT(1) FROM I_Inventory " + " WHERE I_IsImported='E' " + selection.toSqlWhereClause(); return DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql); } private void dbUpdateErrorMessages(@NonNull final ImportRecordsSelection selection) { // // No Locator { final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ") .append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Locator, ' ") .append(" WHERE M_Locator_ID IS NULL ") .append(" AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No Locator = {}", no); } } // // No Warehouse { final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ") .append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Warehouse, ' ") .append(" WHERE M_Warehouse_ID IS NULL ") .append(" AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No Warehouse = {}", no);
} } // // No Product { final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ") .append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Product, ' ") .append(" WHERE M_Product_ID IS NULL ") .append(" AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No Product = {}", no); } } // No QtyCount { final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ") .append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No qtycount, ' ") .append(" WHERE qtycount IS NULL ") .append(" AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No qtycount = {}", no); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\impexp\MInventoryImportTableSqlUpdater.java
1
请完成以下Java代码
public void setTaskExecutor(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) { try { taskExecutor.execute(getExecuteJobsRunnable(jobIds, processEngine)); } catch (RejectedExecutionException e) { logRejectedExecution(processEngine, jobIds.size()); rejectedJobsHandler.jobsRejected(jobIds, processEngine, this); } finally { if (taskExecutor instanceof ThreadPoolTaskExecutor) { logJobExecutionInfo(processEngine, ((ThreadPoolTaskExecutor) taskExecutor).getQueueSize(), ((ThreadPoolTaskExecutor) taskExecutor).getQueueCapacity(), ((ThreadPoolTaskExecutor) taskExecutor).getMaxPoolSize(),
((ThreadPoolTaskExecutor) taskExecutor).getActiveCount()); } } } @Override protected void startExecutingJobs() { startJobAcquisitionThread(); } @Override protected void stopExecutingJobs() { stopJobAcquisitionThread(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\jobexecutor\SpringJobExecutor.java
1
请完成以下Java代码
public void setUrl(String url) { this.url = url; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; }
public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysPermission.java
1
请完成以下Java代码
public boolean isSystemLanguage () { Object oo = get_Value(COLUMNNAME_IsSystemLanguage); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ISO Language Code. @param LanguageISO Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public void setLanguageISO (String LanguageISO) { set_Value (COLUMNNAME_LanguageISO, LanguageISO); } /** Get ISO Language Code. @return Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public String getLanguageISO () { return (String)get_Value(COLUMNNAME_LanguageISO); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); }
/** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Time Pattern. @param TimePattern Java Time Pattern */ public void setTimePattern (String TimePattern) { set_Value (COLUMNNAME_TimePattern, TimePattern); } /** Get Time Pattern. @return Java Time Pattern */ public String getTimePattern () { return (String)get_Value(COLUMNNAME_TimePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isCachable() { return true; } @Override public Object getValue(ValueFields valueFields) { if (valueFields.getLongValue() != null) { return Integer.valueOf(valueFields.getLongValue().intValue()); } return null; } @Override public void setValue(Object value, ValueFields valueFields) { if (value != null) { valueFields.setLongValue(((Integer) value).longValue());
valueFields.setTextValue(value.toString()); } else { valueFields.setLongValue(null); valueFields.setTextValue(null); } } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return Integer.class.isAssignableFrom(value.getClass()) || int.class.isAssignableFrom(value.getClass()); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\IntegerType.java
2
请完成以下Java代码
public void addBankAccount(@NonNull final BPartnerBankAccount bankAccount) { bankAccounts.add(bankAccount); } public Optional<BPartnerBankAccount> getBankAccountByIBAN(@NonNull final String iban) { Check.assumeNotEmpty(iban, "iban is not empty"); return bankAccounts.stream() .filter(bankAccount -> iban.equals(bankAccount.getIban())) .findFirst(); } public void addCreditLimit(@NonNull final BPartnerCreditLimit creditLimit) {
creditLimits.add(creditLimit); } @NonNull public Stream<BPartnerContactId> streamContactIds() { return this.getContacts().stream().map(BPartnerContact::getId); } @NonNull public Stream<BPartnerLocationId> streamBPartnerLocationIds() { return this.getLocations().stream().map(BPartnerLocation::getId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerComposite.java
1
请完成以下Java代码
public java.lang.String getStorageAttributesKey () { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } /** Set Transfert Time. @param TransfertTime Transfert Time */ @Override public void setTransfertTime (java.math.BigDecimal TransfertTime) { set_Value (COLUMNNAME_TransfertTime, TransfertTime); } /** Get Transfert Time. @return Transfert Time */ @Override public java.math.BigDecimal getTransfertTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TransfertTime); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Working Time. @param WorkingTime Workflow Simulation Execution Time */ @Override public void setWorkingTime (java.math.BigDecimal WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } /** Get Working Time. @return Workflow Simulation Execution Time */ @Override public java.math.BigDecimal getWorkingTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WorkingTime); if (bd == null) return BigDecimal.ZERO; return bd; }
/** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield () { Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } @Override public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID) { if (C_Manufacturing_Aggregation_ID < 1) set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null); else set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID); } @Override public int getC_Manufacturing_Aggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_PlanningSchema.java
1
请完成以下Java代码
public Long[] projectionRowCount() { final Session session = HibernateUtil.getHibernateSession(); final CriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Long> cr = cb.createQuery(Long.class); final Root<Item> root = cr.from(Item.class); cr.select(cb.count(root)); Query<Long> query = session.createQuery(cr); final List<Long> itemProjected = query.getResultList(); // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list(); final Long projectedRowCount[] = new Long[itemProjected.size()]; for (int i = 0; i < itemProjected.size(); i++) { projectedRowCount[i] = itemProjected.get(i); } session.close(); return projectedRowCount; } // Set projections average of itemPrice
public Double[] projectionAverage() { final Session session = HibernateUtil.getHibernateSession(); final CriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Double> cr = cb.createQuery(Double.class); final Root<Item> root = cr.from(Item.class); cr.select(cb.avg(root.get("itemPrice"))); Query<Double> query = session.createQuery(cr); final List avgItemPriceList = query.getResultList(); // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list(); final Double avgItemPrice[] = new Double[avgItemPriceList.size()]; for (int i = 0; i < avgItemPriceList.size(); i++) { avgItemPrice[i] = (Double) avgItemPriceList.get(i); } session.close(); return avgItemPrice; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\view\ApplicationView.java
1
请完成以下Java代码
public boolean isAckAfterHandle() { return this.ackAfterHandle; } @Override public void setAckAfterHandle(boolean ackAfterHandle) { this.ackAfterHandle = ackAfterHandle; } /** * True to reclassify the exception if different from the previous failure. If * classified as retryable, the existing back off sequence is used; a new sequence is * not started. * @return the reclassifyOnExceptionChange * @since 2.9.7 */ protected boolean isReclassifyOnExceptionChange() { return this.reclassifyOnExceptionChange; } /** * Set to false to not reclassify the exception if different from the previous * failure. If the changed exception is classified as retryable, the existing back off * sequence is used; a new sequence is not started. Default true. * @param reclassifyOnExceptionChange false to not reclassify. * @since 2.9.7 */ public void setReclassifyOnExceptionChange(boolean reclassifyOnExceptionChange) { this.reclassifyOnExceptionChange = reclassifyOnExceptionChange; } @Override public void handleBatch(Exception thrownException, @Nullable ConsumerRecords<?, ?> records, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { if (records == null || records.count() == 0) { this.logger.error(thrownException, "Called with no records; consumer exception"); return; } this.retrying.put(Thread.currentThread(), true); try {
ErrorHandlingUtils.retryBatch(thrownException, records, consumer, container, invokeListener, this.backOff, this.seeker, this.recoverer, this.logger, getLogLevel(), this.retryListeners, getExceptionMatcher(), this.reclassifyOnExceptionChange); } finally { this.retrying.remove(Thread.currentThread()); } } @Override public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { if (Boolean.TRUE.equals(this.retrying.get(Thread.currentThread()))) { consumer.pause(consumer.assignment()); publishPause.run(); } } private final class SeekAfterRecoverFailsOrInterrupted implements CommonErrorHandler { SeekAfterRecoverFailsOrInterrupted() { } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { data.partitions() .stream() .collect( Collectors.toMap(tp -> tp, tp -> data.records(tp).get(0).offset(), (u, v) -> v, LinkedHashMap::new)) .forEach(consumer::seek); throw new KafkaException("Seek to current after exception", getLogLevel(), thrownException); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\FallbackBatchErrorHandler.java
1
请完成以下Java代码
public class Player { private int points ; final String name; public Player(String name) { this(name, 0); } private Player(String name, int points) { this.name = name; this.points = 0; } public void gainPoint() { points++; }
public boolean hasScoreBiggerThan(Score score) { return this.points > score.points(); } public int pointsDifference(Player other) { return points - other.points; } public String name() { return name; } public String score() { return Score.from(points).label(); } }
repos\tutorials-master\patterns-modules\clean-architecture\src\main\java\com\baeldung\pattern\richdomainmodel\Player.java
1
请完成以下Java代码
public void setCommittedAmt (BigDecimal CommittedAmt) { set_Value (COLUMNNAME_CommittedAmt, CommittedAmt); } /** Get Committed Amount. @return The (legal) commitment amount */ public BigDecimal getCommittedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CommittedAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_Order getC_Order() throws RuntimeException { return (I_C_Order)MTable.get(getCtx(), I_C_Order.Table_Name) .getPO(getC_Order_ID(), get_TrxName()); } /** Set Order. @param C_Order_ID Order */ public void setC_Order_ID (int C_Order_ID) { if (C_Order_ID < 1) set_Value (COLUMNNAME_C_Order_ID, null); else set_Value (COLUMNNAME_C_Order_ID, Integer.valueOf(C_Order_ID)); } /** Get Order. @return Order */ public int getC_Order_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Order_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Payment getC_Payment() throws RuntimeException { return (I_C_Payment)MTable.get(getCtx(), I_C_Payment.Table_Name) .getPO(getC_Payment_ID(), get_TrxName()); } /** Set Payment. @param C_Payment_ID Payment identifier */ public void setC_Payment_ID (int C_Payment_ID) { if (C_Payment_ID < 1) set_Value (COLUMNNAME_C_Payment_ID, null); else set_Value (COLUMNNAME_C_Payment_ID, Integer.valueOf(C_Payment_ID)); } /** Get Payment. @return Payment identifier */
public int getC_Payment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Not Committed Aount. @param NonCommittedAmt Amount not committed yet */ public void setNonCommittedAmt (BigDecimal NonCommittedAmt) { set_Value (COLUMNNAME_NonCommittedAmt, NonCommittedAmt); } /** Get Not Committed Aount. @return Amount not committed yet */ public BigDecimal getNonCommittedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_NonCommittedAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_SellerFunds.java
1
请完成以下Java代码
public float getLayoutAlignmentX(Container target) { return 0f; } // getLayoutAlignmentX /** * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. * @param target target * @return 0f */ public float getLayoutAlignmentY(Container target) { return 0f; } // getLayoutAlignmentY /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. * @param target target */ public void invalidateLayout(Container target) { } // invalidateLayout /*************************************************************************/ /** * Check target components and add components, which don't have no constraints * @param target target */ private void checkComponents (Container target) { int size = target.getComponentCount(); for (int i = 0; i < size; i++) { Component comp = target.getComponent(i); if (!m_data.containsValue(comp)) m_data.put(null, comp); } } // checkComponents /** * Get Number of Rows * @return no pf rows */ public int getRowCount() { return m_data.getMaxRow()+1; } // getRowCount /** * Get Number of Columns * @return no of cols */ public int getColCount() { return m_data.getMaxCol()+1;
} // getColCount /** * Set Horizontal Space (top, between rows, button) * @param spaceH horizontal space (top, between rows, button) */ public void setSpaceH (int spaceH) { m_spaceH = spaceH; } // setSpaceH /** * Get Horizontal Space (top, between rows, button) * @return spaceH horizontal space (top, between rows, button) */ public int getSpaceH() { return m_spaceH; } // getSpaceH /** * Set Vertical Space (left, between columns, right) * @param spaceV vertical space (left, between columns, right) */ public void setSpaceV(int spaceV) { m_spaceV = spaceV; } // setSpaceV /** * Get Vertical Space (left, between columns, right) * @return spaceV vertical space (left, between columns, right) */ public int getSpaceV() { return m_spaceV; } // getSpaceV } // ALayout
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayout.java
1
请在Spring Boot框架中完成以下Java代码
public String getProductFileEndpoint() { return getLocalFileConnectionString(fileNamePatternProduct); } @Override @NonNull public String getBPartnerFileEndpoint() { return getLocalFileConnectionString(fileNamePatternBPartner); } @Override @NonNull public String getWarehouseFileEndpoint() { return getLocalFileConnectionString(fileNamePatternWarehouse); } @Override @NonNull public String getPurchaseOrderFileEndpoint() { return getLocalFileConnectionString(fileNamePatternPurchaseOrder); } @NonNull private String getLocalFileConnectionString(@Nullable final String includeFilePattern) { final StringBuilder fileEndpoint = new StringBuilder("file://"); fileEndpoint.append(rootLocation)
.append("?") .append("charset=utf-8") .append("&") .append("delay=").append(pollingFrequency.toMillis()) .append("&") .append("move=").append(processedFilesFolder).append("/").append(seenFileRenamePattern) .append("&") .append("moveFailed=").append(errorFilesFolder).append("/").append(seenFileRenamePattern); if(Check.isNotBlank(includeFilePattern)) { fileEndpoint.append("&").append("antInclude=").append(includeFilePattern); } return fileEndpoint.toString(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\config\LocalFileConfig.java
2
请完成以下Java代码
public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); } @Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() {
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请完成以下Java代码
public static HUQRCodeUniqueId ofUUID(@NonNull final UUID uuid) { final String uuidStr = uuid.toString().replace("-", ""); // expect 32 chars final StringBuilder uuidFirstPart = new StringBuilder(32); final StringBuilder uuidLastPart = new StringBuilder(); // TO reduce the change of having duplicate displayable suffix, // we cannot just take the last 4 chars but we will pick some of them from the middle // See https://www.ietf.org/rfc/rfc4122.txt section 3, to understand the UUID v4 format. for (int i = 0; i < uuidStr.length(); i++) { final char ch = uuidStr.charAt(i); if (// from time_low (0-7): i == 5 // from: time_mid (8-11): || i == 8 || i == 11 // from: time_hi_and_version (12-15) || i == 13 // from: clock_seq_hi_and_reserved (16-17) // from: clock_seq_low (18-19) // from: node (20-31) ) { uuidLastPart.append(ch); } else { uuidFirstPart.append(ch); } } final String uuidLastPartNorm = Strings.padStart( String.valueOf(Integer.parseInt(uuidLastPart.toString(), 16)), 5, // because 4 hex digits can lead to 5 decimal digits (i.e. FFFF -> 65535) '0'); return new HUQRCodeUniqueId(uuidFirstPart.toString(), uuidLastPartNorm); } @JsonCreator public static HUQRCodeUniqueId ofJson(@NonNull final String json) { final int idx = json.indexOf('-'); if (idx <= 0) { throw new AdempiereException("Invalid ID: `" + json + "`"); }
final String idBase = json.substring(0, idx); final String displayableSuffix = json.substring(idx + 1); return new HUQRCodeUniqueId(idBase, displayableSuffix); } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return idBase + "-" + displayableSuffix; } public static boolean equals(@Nullable final HUQRCodeUniqueId id1, @Nullable final HUQRCodeUniqueId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeUniqueId.java
1
请完成以下Java代码
public TenantId getTenantId() { return this.tenantId; } @Schema(description = "JSON object with Customer Id. Use 'assignEdgeToCustomer' to change the Customer Id.", accessMode = Schema.AccessMode.READ_ONLY) @Override public CustomerId getCustomerId() { return this.customerId; } @Schema(description = "JSON object with Root Rule Chain Id. Use 'setEdgeRootRuleChain' to change the Root Rule Chain Id.", accessMode = Schema.AccessMode.READ_ONLY) public RuleChainId getRootRuleChainId() { return this.rootRuleChainId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge") @Override public String getName() { return this.name; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos") public String getType() { return this.type; }
@Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field") public String getLabel() { return this.label; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud") public String getRoutingKey() { return this.routingKey; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud") public String getSecret() { return this.secret; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java
1
请完成以下Java代码
public void clearStoredHashCode() { storedHashCode = null; } /** * 两个状态是否等价,只有状态转移函数完全一致才算相等<br> * Evaluates the equality of this node with another object. * This node is equal to obj if and only if obj is also an MDAGNode, * and the set of transitions paths from this node and obj are equivalent. * @param obj an object * @return true of {@code obj} is an MDAGNode and the set of * _transition paths from this node and obj are equivalent */ @Override public boolean equals(Object obj) { boolean areEqual = (this == obj); if(!areEqual && obj != null && obj.getClass().equals(MDAGNode.class)) { MDAGNode node = (MDAGNode)obj; areEqual = (isAcceptNode == node.isAcceptNode && haveSameTransitions(this, node)); } return areEqual; } /**
* Hashes this node using its accept state status and set of outgoing _transition paths. * This is an expensive operation, so the result is cached and only cleared when necessary. * @return an int of this node's hash code */ @Override public int hashCode() { if(storedHashCode == null) { int hash = 7; hash = 53 * hash + (this.isAcceptNode ? 1 : 0); hash = 53 * hash + (this.outgoingTransitionTreeMap != null ? this.outgoingTransitionTreeMap.hashCode() : 0); //recursively hashes the nodes in all the //_transition paths stemming from this node storedHashCode = hash; return hash; } else return storedHashCode; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MDAGNode{"); sb.append("isAcceptNode=").append(isAcceptNode); sb.append(", outgoingTransitionTreeMap=").append(outgoingTransitionTreeMap.keySet()); sb.append(", incomingTransitionCount=").append(incomingTransitionCount); // sb.append(", transitionSetBeginIndex=").append(transitionSetBeginIndex); // sb.append(", storedHashCode=").append(storedHashCode); sb.append('}'); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGNode.java
1
请完成以下Java代码
public Document getDocument() { return m_view.getDocument(); } /** * Returns the starting offset into the model for this view. * * @return the starting offset */ public int getStartOffset() { return m_view.getStartOffset(); } /** * Returns the ending offset into the model for this view. * * @return the ending offset */ public int getEndOffset() { return m_view.getEndOffset(); } /** * Gets the element that this view is mapped to. * * @return the view */ public Element getElement() { return m_view.getElement(); } /** * Sets the view size. * * @param width the width * @param height the height */ public void setSize(float width, float height) {
this.m_width = (int) width; m_view.setSize(width, height); } /** * Fetches the factory to be used for building the * various view fragments that make up the view that * represents the model. This is what determines * how the model will be represented. This is implemented * to fetch the factory provided by the associated * EditorKit. * * @return the factory */ public ViewFactory getViewFactory() { return m_factory; } } // HTMLRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLRenderer.java
1
请完成以下Java代码
public class C_Doc_Outbound_Log_Selection_Export_JSON extends C_Invoice_Selection_Export_JSON { private final IDocOutboundDAO docOutboundDAO = Services.get(IDocOutboundDAO.class); private final IADTableDAO tableDAO = Services.get(IADTableDAO.class); @Override @Nullable protected InvoiceId extractSingleSelectedInvoiceId(@NonNull final IProcessPreconditionsContext context) { final DocOutboundLogId docOutboundLogId = DocOutboundLogId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (docOutboundLogId == null) { return null; } final de.metas.document.archive.model.I_C_Doc_Outbound_Log outboundLogRecord = docOutboundDAO.retrieveLog(docOutboundLogId); final TableRecordReference reference = TableRecordReference.ofReferenced(outboundLogRecord); if (!reference.tableNameEqualsTo(I_C_Invoice.Table_Name))
{ return null; } return InvoiceId.ofRepoIdOrNull(reference.getRecord_ID()); } @Override @NonNull protected IQueryBuilder<I_C_Invoice> createSelectedInvoicesQueryBuilder() { return queryBL .createQueryBuilder(I_C_Doc_Outbound_Log.class) .filter(getProcessInfo().getQueryFilterOrElseFalse()) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Doc_Outbound_Log.COLUMNNAME_AD_Table_ID, tableDAO.retrieveTableId(I_C_Invoice.Table_Name)) .andCollect(I_C_Doc_Outbound_Log.COLUMNNAME_Record_ID, I_C_Invoice.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\json\C_Doc_Outbound_Log_Selection_Export_JSON.java
1
请在Spring Boot框架中完成以下Java代码
public class JPAEntityVariableType implements VariableType, CacheableVariable { public static final String TYPE_NAME = "jpa-entity"; private JPAEntityMappings mappings; private boolean forceCacheable; public JPAEntityVariableType() { mappings = new JPAEntityMappings(); } @Override public String getTypeName() { return TYPE_NAME; } @Override public boolean isCachable() { return forceCacheable; } @Override public boolean isAbleToStore(Object value) { if (value == null) { return true; } return mappings.isJPAEntity(value); } @Override public void setValue(Object value, ValueFields valueFields) { EntityManagerSession entityManagerSession = Context.getCommandContext().getSession(EntityManagerSession.class); if (entityManagerSession == null) { throw new FlowableException("Cannot set JPA variable: " + EntityManagerSession.class + " not configured"); } else { // Before we set the value we must flush all pending changes from // the entitymanager // If we don't do this, in some cases the primary key will not yet // be set in the object // which will cause exceptions down the road. entityManagerSession.flush();
} if (value != null) { String className = mappings.getJPAClassString(value); String idString = mappings.getJPAIdString(value); valueFields.setTextValue(className); valueFields.setTextValue2(idString); } else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } @Override public Object getValue(ValueFields valueFields) { if (valueFields.getTextValue() != null && valueFields.getTextValue2() != null) { return mappings.getJPAEntity(valueFields.getTextValue(), valueFields.getTextValue2()); } return null; } /** * Force the value to be cacheable. */ @Override public void setForceCacheable(boolean forceCachedValue) { this.forceCacheable = forceCachedValue; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JPAEntityVariableType.java
2
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStartDay (final int StartDay) { set_Value (COLUMNNAME_StartDay, StartDay); }
@Override public int getStartDay() { return get_ValueAsInt(COLUMNNAME_StartDay); } @Override public void setStartMonth (final int StartMonth) { set_Value (COLUMNNAME_StartMonth, StartMonth); } @Override public int getStartMonth() { return get_ValueAsInt(COLUMNNAME_StartMonth); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java
1
请完成以下Java代码
private String getResponsiblePerson(@NonNull final XmlBody body) { String response = ""; final XMLEmployee employee = body.getContact().getEmployee(); if (employee != null) { response += employee.getFamilyName(); if (employee.getGivenName() != null) { response += " " + employee.getGivenName(); } } if (response.isEmpty()) { return null; } return response; } @Nullable private String getExplanation(final XmlBody body) { if (body.getRejected() != null) { return body.getRejected().getExplanation();
} return null; } @NonNull private String getRecipient(@NonNull final XmlBody body) { return body.getContact().getCompany().getCompanyName(); } @SuppressWarnings("UnstableApiUsage") private ImmutableList<RejectedError> getErrors(@NonNull final XmlBody body) { if (body.getRejected() != null) { return body.getRejected().getErrors() .stream() .map(it -> new RejectedError(it.getCode(), it.getText())) .collect(ImmutableList.toImmutableList()); } return ImmutableList.of(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\invoice\InvoiceImportClientImpl.java
1
请在Spring Boot框架中完成以下Java代码
private Path getSchemaUpdateFile(String version) { return Paths.get(installScripts.getDataDir(), "upgrade", version, SCHEMA_UPDATE_SQL); } private void loadSql(Path sqlFile) { String sql; try { sql = Files.readString(sqlFile); } catch (IOException e) { throw new UncheckedIOException(e); } jdbcTemplate.execute((StatementCallback<Object>) stmt -> { stmt.execute(sql); printWarnings(stmt.getWarnings()); return null; }); } private void execute(@Language("sql") String... statements) { for (String statement : statements) { execute(statement, true); } }
private void execute(@Language("sql") String statement, boolean ignoreErrors) { try { jdbcTemplate.execute(statement); } catch (Exception e) { if (!ignoreErrors) { throw e; } } } private void printWarnings(SQLWarning warnings) { if (warnings != null) { log.info("{}", warnings.getMessage()); SQLWarning nextWarning = warnings.getNextWarning(); while (nextWarning != null) { log.info("{}", nextWarning.getMessage()); nextWarning = nextWarning.getNextWarning(); } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\SqlDatabaseUpgradeService.java
2
请完成以下Java代码
public boolean isSpecific() { return !isAll() && !isOther() && !isNone(); } public String getSqlLikeString() { String sqlLikeString = _sqlLikeString; if (sqlLikeString == null) { sqlLikeString = _sqlLikeString = computeSqlLikeString(); } return sqlLikeString; } private String computeSqlLikeString() { final StringBuilder sb = new StringBuilder(); sb.append("%"); boolean lastCharIsWildcard = true; for (final AttributesKeyPartPattern partPattern : partPatterns) { final String partSqlLike = partPattern.getSqlLikePart(); if (lastCharIsWildcard) { if (partSqlLike.startsWith("%")) { sb.append(partSqlLike.substring(1)); } else { sb.append(partSqlLike); } } else { if (partSqlLike.startsWith("%")) { sb.append(partSqlLike); } else { sb.append("%").append(partSqlLike); } } lastCharIsWildcard = partSqlLike.endsWith("%"); } if (!lastCharIsWildcard) { sb.append("%"); } return sb.toString(); } public boolean matches(@NonNull final AttributesKey attributesKey) { for (final AttributesKeyPartPattern partPattern : partPatterns) {
boolean partPatternMatched = false; if (AttributesKey.NONE.getAsString().equals(attributesKey.getAsString())) { partPatternMatched = partPattern.matches(AttributesKeyPart.NONE); } else { for (final AttributesKeyPart part : attributesKey.getParts()) { if (partPattern.matches(part)) { partPatternMatched = true; break; } } } if (!partPatternMatched) { return false; } } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPattern.java
1
请在Spring Boot框架中完成以下Java代码
static class JsonbJsonpMapperConfiguration { @Bean JsonbJsonpMapper jsonbJsonpMapper(Jsonb jsonb) { return new JsonbJsonpMapper(JsonProvider.provider(), jsonb); } } @ConditionalOnMissingBean(JsonpMapper.class) @Configuration(proxyBeanMethods = false) static class SimpleJsonpMapperConfiguration { @Bean SimpleJsonpMapper simpleJsonpMapper() { return new SimpleJsonpMapper(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(ElasticsearchTransport.class) static class ElasticsearchTransportConfiguration { @Bean Rest5ClientTransport restClientTransport(Rest5Client restClient, JsonpMapper jsonMapper, ObjectProvider<Rest5ClientOptions> restClientOptions) { return new Rest5ClientTransport(restClient, jsonMapper, restClientOptions.getIfAvailable()); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnBean(ElasticsearchTransport.class) static class ElasticsearchClientConfiguration { @Bean @ConditionalOnMissingBean ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) { return new ElasticsearchClient(transport); } } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchClientConfigurations.java
2
请完成以下Java代码
public static final CacheIntrospectionException wrapIfNeeded(final Throwable e) { if (e == null) { return new CacheIntrospectionException("Unknown cache exception"); } else if (e instanceof CacheIntrospectionException) { return (CacheIntrospectionException)e; } else if ((e instanceof InvocationTargetException) && (e.getCause() != null)) { return wrapIfNeeded(e.getCause()); } else if ((e instanceof UncheckedExecutionException) && (e.getCause() != null)) { return wrapIfNeeded(e.getCause()); } else { return new CacheIntrospectionException(e); } } private Method method = null; private int parameterIndex; private Class<?> parameterType; private boolean parameterSet; private Set<String> hintsToFix = null; public CacheIntrospectionException(final String message) { super(message); } public CacheIntrospectionException(final Throwable cause) { super(cause); } public CacheIntrospectionException setMethod(final Method method) { this.method = method; resetMessageBuilt(); return this; } public CacheIntrospectionException setParameter(final int parameterIndex, final Class<?> parameterType) { this.parameterIndex = parameterIndex; this.parameterType = parameterType; this.parameterSet = true; resetMessageBuilt(); return this; } public CacheIntrospectionException addHintToFix(final String hintToFix) { if (Check.isEmpty(hintToFix, true)) {
return this; } if (this.hintsToFix == null) { this.hintsToFix = new HashSet<>(); } this.hintsToFix.add(hintToFix); resetMessageBuilt(); return this; } @Override protected ITranslatableString buildMessage() { final TranslatableStringBuilder message = TranslatableStrings.builder(); message.append(super.buildMessage()); if (method != null) { message.append("\n Method: ").appendObj(method); } if (parameterSet) { message.append("\n Invalid parameter at index ").append(parameterIndex).append(": ").appendObj(parameterType); } if (!Check.isEmpty(hintsToFix)) { for (final String hint : hintsToFix) { message.append("\n Hint to fix: ").append(hint); } } return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheIntrospectionException.java
1
请在Spring Boot框架中完成以下Java代码
public class ProcessDefinitionDto { protected String id; protected String key; protected String category; protected String description; protected String name; protected int version; protected String resource; protected String deploymentId; protected String diagram; protected boolean suspended; protected String tenantId; protected String versionTag; protected Integer historyTimeToLive; protected boolean isStartableInTasklist; public String getId() { return id; } public String getKey() { return key; } public String getCategory() { return category; } public String getDescription() { return description; } public String getName() { return name; } public int getVersion() { return version; } public String getResource() { return resource; } public String getDeploymentId() { return deploymentId; } public String getDiagram() { return diagram; } public boolean isSuspended() { return suspended; } public String getTenantId() { return tenantId; } public String getVersionTag() { return versionTag;
} public Integer getHistoryTimeToLive() { return historyTimeToLive; } public boolean isStartableInTasklist() { return isStartableInTasklist; } public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) { ProcessDefinitionDto dto = new ProcessDefinitionDto(); dto.id = definition.getId(); dto.key = definition.getKey(); dto.category = definition.getCategory(); dto.description = definition.getDescription(); dto.name = definition.getName(); dto.version = definition.getVersion(); dto.resource = definition.getResourceName(); dto.deploymentId = definition.getDeploymentId(); dto.diagram = definition.getDiagramResourceName(); dto.suspended = definition.isSuspended(); dto.tenantId = definition.getTenantId(); dto.versionTag = definition.getVersionTag(); dto.historyTimeToLive = definition.getHistoryTimeToLive(); dto.isStartableInTasklist = definition.isStartableInTasklist(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionDto.java
2
请完成以下Java代码
public long countByCriteria(HistoricPlanItemInstanceQueryImpl query) { setSafeInValueLists(query); return (Long) getDbSqlSession().selectOne("selectHistoricPlanItemInstancesCountByQueryCriteria", query); } @Override public void deleteByCaseDefinitionId(String caseDefinitionId) { getDbSqlSession().delete("deleteHistoricPlanItemInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass()); } @Override public void bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(Collection<String> caseInstanceIds) { getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesByCaseInstanceIds", createSafeInValuesList(caseInstanceIds), getManagedEntityClass()); } @Override public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesForNonExistingCaseInstances", null, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) { setSafeInValueLists(historicPlanItemInstanceQuery); return getDbSqlSession().selectList("selectHistoricPlanItemInstancesWithLocalVariablesByQueryCriteria", historicPlanItemInstanceQuery, getManagedEntityClass()); } @Override public Class<? extends HistoricPlanItemInstanceEntity> getManagedEntityClass() { return HistoricPlanItemInstanceEntityImpl.class; } @Override
public HistoricPlanItemInstanceEntity create() { return new HistoricPlanItemInstanceEntityImpl(); } @Override public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) { return new HistoricPlanItemInstanceEntityImpl(planItemInstance); } protected void setSafeInValueLists(HistoricPlanItemInstanceQueryImpl planItemInstanceQuery) { if (planItemInstanceQuery.getInvolvedGroups() != null) { planItemInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(planItemInstanceQuery.getInvolvedGroups())); } if(planItemInstanceQuery.getCaseInstanceIds() != null) { planItemInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(planItemInstanceQuery.getCaseInstanceIds())); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricPlanItemInstanceDataManager.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { // 创建线程安全的Map,模拟users信息的存储 static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); /** * 处理"/users/"的GET请求,用来获取用户列表 * * @return */ @GetMapping("/") public List<User> getUserList() { // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 List<User> r = new ArrayList<User>(users.values()); return r; } /** * 处理"/users/"的POST请求,用来创建User * * @param user * @return */ @PostMapping("/") public String postUser(@RequestBody User user) { // @RequestBody注解用来绑定通过http请求中application/json类型上传的数据 users.put(user.getId(), user); return "success"; } /** * 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 * * @param id * @return
*/ @GetMapping("/{id}") public User getUser(@PathVariable Long id) { // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id); } /** * 处理"/users/{id}"的PUT请求,用来更新User信息 * * @param id * @param user * @return */ @PutMapping("/{id}") public String putUser(@PathVariable Long id, @RequestBody User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } /** * 处理"/users/{id}"的DELETE请求,用来删除User * * @param id * @return */ @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; } }
repos\SpringBoot-Learning-master\2.x\chapter2-1\src\main\java\com\didispace\chapter21\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public long countFeed(long userId) { return assemblyRepository.countFeed(userId); } @Mapper(config = MappingConfig.class) interface ArticleMapper { @Mapping(target = "tagList", source = "tags") @Mapping(target = "tagIds", source = "tags") ArticleJdbcEntity fromDomain(Article source); @Mapping(target = "tag", ignore = true) @Mapping(target = "tags", source = "source") Article toDomain(ArticleJdbcEntity source); @Mapping(target = "author", source = "source") ArticleAssembly toDomain(ArticleAssemblyJdbcEntity source); default Profile profile(ArticleAssemblyJdbcEntity source) { return new Profile(source.authorUsername(), source.authorBio(), source.authorImage(), source.authorFollowing()); } default List<String> tagList(String source) { if (source == null) { return null; } return Arrays.stream(source.split(",")).toList(); } default String tagList(List<Tag> source) { if (source == null || source.isEmpty()) { return null; }
return source.stream().map(Tag::name).collect(Collectors.joining(",")); } default List<ArticleTagJdbcEntity> tagIds(List<Tag> source) { return source.stream().map(t -> new ArticleTagJdbcEntity(t.id())).toList(); } default List<Tag> tags(ArticleJdbcEntity source) { var tagIds = source.tagIds(); if (tagIds != null) { var tagList = source.tagList(); if (tagList != null) { var tagNames = tagList.split(","); if (tagNames.length == tagIds.size()) { List<Tag> tags = new ArrayList<>(); for (var i = 0; i < tagIds.size(); i++) { var tag = new Tag(tagIds.get(i).tagId(), tagNames[i]); tags.add(tag); } return tags; } } } return List.of(); } } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\ArticleJdbcRepositoryAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public ImmutableSet<Integer> getExternalSystemConfigIds(@NonNull final DataExportAuditId dataExportAuditId) { return queryBL.createQueryBuilder(I_Data_Export_Audit_Log.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_Data_Export_Audit_Log.COLUMNNAME_Data_Export_Audit_ID, dataExportAuditId.getRepoId()) .addNotEqualsFilter(I_Data_Export_Audit_Log.COLUMNNAME_ExternalSystem_Config_ID, null) .create() .listDistinct(I_Data_Export_Audit_Log.COLUMNNAME_ExternalSystem_Config_ID, Integer.class) .stream() .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @NonNull public ImmutableList<DataExportAuditLog> getByDataExportAuditId(@NonNull final DataExportAuditId dataExportAuditId) { return queryBL.createQueryBuilder(I_Data_Export_Audit_Log.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_Data_Export_Audit_Log.COLUMNNAME_Data_Export_Audit_ID, dataExportAuditId.getRepoId()) .create() .stream()
.map(DataExportAuditLogRepository::toDataExportAuditLog) .collect(ImmutableList.toImmutableList()); } @NonNull private static DataExportAuditLog toDataExportAuditLog(@NonNull final I_Data_Export_Audit_Log record) { return DataExportAuditLog.builder() .dataExportAuditLogId(DataExportAuditLogId.ofRepoId(DataExportAuditId.ofRepoId(record.getData_Export_Audit_ID()), record.getData_Export_Audit_Log_ID())) .action(Action.ofCode(record.getData_Export_Action())) .externalSystemConfigId(ExternalSystemParentConfigId.ofRepoIdOrNull(record.getExternalSystem_Config_ID())) .adPInstanceId(PInstanceId.ofRepoIdOrNull(record.getAD_PInstance_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\data\repository\DataExportAuditLogRepository.java
2
请完成以下Java代码
public final class PayPalOrderStatus { @JsonCreator public static PayPalOrderStatus ofCode(@NonNull final String code) { final PayPalOrderStatus status = cacheByCode.get(code); return status != null ? status : new PayPalOrderStatus(code); } public static final PayPalOrderStatus UNKNOWN = new PayPalOrderStatus("-"); public static final PayPalOrderStatus CREATED = new PayPalOrderStatus("CREATED"); public static final PayPalOrderStatus APPROVED = new PayPalOrderStatus("APPROVED"); public static final PayPalOrderStatus COMPLETED = new PayPalOrderStatus("COMPLETED"); public static final PayPalOrderStatus REMOTE_DELETED = new PayPalOrderStatus("MF_REMOTE_DELETED"); private static final ImmutableMap<String, PayPalOrderStatus> cacheByCode = Maps.uniqueIndex( Arrays.asList(UNKNOWN, CREATED, APPROVED, COMPLETED, REMOTE_DELETED), PayPalOrderStatus::getCode); private final String code; private PayPalOrderStatus(@NonNull final String code) { this.code = code; } @Override @Deprecated public String toString() { return getCode(); } @JsonValue public String getCode() { return code; } public boolean isApproved() { return APPROVED.equals(this); } public PaymentReservationStatus toPaymentReservationStatus()
{ if (this == CREATED) { return PaymentReservationStatus.WAITING_PAYER_APPROVAL; } else if (this == APPROVED) { return PaymentReservationStatus.APPROVED_BY_PAYER; } else if (this == COMPLETED) { return PaymentReservationStatus.COMPLETED; } else if (this == REMOTE_DELETED) { return PaymentReservationStatus.WAITING_PAYER_APPROVAL; } else { throw new AdempiereException("Cannot convert " + this + " to " + PaymentReservationStatus.class); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderStatus.java
1
请完成以下Spring Boot application配置
spring: jms: cache: enabled: true # 默认 true session-cache-size: 5 # 默认 1 artemis: mode: native broker-url: tcp://localhost:61616 user: admin password: 123456 pool: enabled: true # 默认 false m
ax-connections: 50 # 默认 1 idle-timeout: 5s # 默认 30s max-sessions-per-connection: 100 # 默认 500
repos\spring-boot-best-practice-master\spring-boot-activemq\src\main\resources\application.yml
2
请完成以下Java代码
public class Category { private final @Id Long id; private String name, description; private LocalDateTime created; private Long inserted; public Category(String name, String description) { this.id = null; this.name = name; this.description = description; this.created = LocalDateTime.now(); } @PersistenceCreator Category(Long id, String name, String description, LocalDateTime created, Long inserted) { this.id = id; this.name = name; this.description = description; this.created = created; this.inserted = inserted; } public void timeStamp() { if (inserted == 0) { inserted = System.currentTimeMillis(); } } public Long getId() { return this.id; } public String getName() { return this.name; }
public String getDescription() { return this.description; } public LocalDateTime getCreated() { return this.created; } public Long getInserted() { return this.inserted; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public void setCreated(LocalDateTime created) { this.created = created; } public void setInserted(Long inserted) { this.inserted = inserted; } public Category withId(Long id) { return this.id == id ? this : new Category(id, this.name, this.description, this.created, this.inserted); } @Override public String toString() { return "Category(id=" + this.getId() + ", name=" + this.getName() + ", description=" + this.getDescription() + ", created=" + this.getCreated() + ", inserted=" + this.getInserted() + ")"; } }
repos\spring-data-examples-main\jdbc\aot-optimization\src\main\java\example\springdata\aot\Category.java
1
请完成以下Java代码
public static long daysBetween(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { assertSameOrg(d2, d2); return ChronoUnit.DAYS.between(d1.toLocalDate(), d2.toLocalDate()); } private static void assertSameOrg(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { Check.assumeEquals(d1.getOrgId(), d2.getOrgId(), "Dates have the same org: {}, {}", d1, d2); } public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant(); } public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; }
public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) { return compareToByLocalDate(o); } /** * In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请完成以下Java代码
public JobManager getJobManager() { return processEngineConfiguration.getJobManager(); } // Involved executions //////////////////////////////////////////////////////// public void addInvolvedExecution(ExecutionEntity executionEntity) { if (executionEntity.getId() != null) { involvedExecutions.put(executionEntity.getId(), executionEntity); } } public boolean hasInvolvedExecutions() { return involvedExecutions.size() > 0; } public Collection<ExecutionEntity> getInvolvedExecutions() { return involvedExecutions.values(); } // getters and setters // ////////////////////////////////////////////////////// public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public ActivitiEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher();
} public ActivitiEngineAgenda getAgenda() { return agenda; } public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public boolean isReused() { return reused; } public void setReused(boolean reused) { this.reused = reused; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; 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 int getAge() {
return age; } public void setAge(int age) { this.age = age; } public Employee(String name, int age) { super(); this.name = name; this.age = age; } public Employee() { super(); } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\jpa\subtypes\entity\Employee.java
2
请完成以下Java代码
public class HashMapBenchmark { @State(Scope.Thread) public static class MyState { Map<Long, Employee> employeeMap = new HashMap<>(); //LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>(); //IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>(); //WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>(); //ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>(); //ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>(); // TreeMap long iterations = 100000; Employee employee = new Employee(100L, "Harry"); int employeeIndex = -1; @Setup(Level.Trial) public void setUp() { for (long i = 0; i < iterations; i++) { employeeMap.put(i, new Employee(i, "John")); } //employeeMap.put(iterations, employee); } } @Benchmark public Employee testGet(MyState state) { return state.employeeMap.get(state.iterations); } @Benchmark public Employee testRemove(MyState state) { return state.employeeMap.remove(state.iterations); } @Benchmark
public Employee testPut(MyState state) { return state.employeeMap.put(state.employee.getId(), state.employee); } @Benchmark public Boolean testContainsKey(MyState state) { return state.employeeMap.containsKey(state.employee.getId()); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(HashMapBenchmark.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\performance\HashMapBenchmark.java
1
请完成以下Java代码
protected @NonNull String decorate(@NonNull PdxInstance pdxInstance, @NonNull String json) { if (isDecorationRequired(pdxInstance, json)) { try { ObjectMapper objectMapper = newObjectMapper(json); JsonNode jsonNode = objectMapper.readTree(json); if (isMissingObjectTypeMetadata(jsonNode)) { ((ObjectNode) jsonNode).put(AT_TYPE_METADATA_PROPERTY_NAME, pdxInstance.getClassName()); json = objectMapper.writeValueAsString(jsonNode); } return json; } catch (JsonProcessingException cause) { if (hasValidClassName(pdxInstance)) { return convertPojoToJson(pdxInstance.getObject()); } String message = String.format("Failed to parse JSON [%s]", json); throw new DataRetrievalFailureException(message, cause); } } return json; } /** * Null-safe method to determine whether the given {@link PdxInstance} * has a valid {@link Class#getName() Class Name}. * * @param pdxInstance {@link PdxInstance} to evaluate; * @return a boolean value indicating whether the {@link PdxInstance} * has a valid {@link Class#getName() Class Name}. * @see org.apache.geode.pdx.PdxInstance */ boolean hasValidClassName(@Nullable PdxInstance pdxInstance) { return Optional.ofNullable(pdxInstance) .map(PdxInstance::getClassName)
.filter(StringUtils::hasText) .filter(className -> !JSONFormatter.JSON_CLASSNAME.equals(className)) .isPresent(); } private boolean isDecorationRequired(@Nullable PdxInstance pdxInstance, @Nullable String json) { return isMissingObjectTypeMetadata(pdxInstance) && isValidJson(json); } private boolean isMissingObjectTypeMetadata(@Nullable JsonNode node) { return isObjectNode(node) && !node.has(AT_TYPE_METADATA_PROPERTY_NAME); } private boolean isMissingObjectTypeMetadata(@Nullable PdxInstance pdxInstance) { return pdxInstance != null && !pdxInstance.hasField(AT_TYPE_METADATA_PROPERTY_NAME); } /** * Null-safe method to determine if the given {@link JsonNode} represents a valid {@link String JSON} object. * * @param node {@link JsonNode} to evaluate. * @return a boolean valued indicating whether the given {@link JsonNode} is a valid {@link ObjectNode}. * @see com.fasterxml.jackson.databind.node.ObjectNode * @see com.fasterxml.jackson.databind.JsonNode */ boolean isObjectNode(@Nullable JsonNode node) { return node != null && (node.isObject() || node instanceof ObjectNode); } /** * Null-safe method to determine whether the given {@link String JSON} is valid. * * @param json {@link String} containing JSON to evaluate. * @return a boolean value indicating whether the given {@link String JSON} is valid. */ boolean isValidJson(@Nullable String json) { return StringUtils.hasText(json); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JSONFormatterPdxToJsonConverter.java
1
请完成以下Java代码
public boolean registerCallout( @NonNull final String tableName, @NonNull final String columnName, @NonNull final ICalloutInstance callout) { final String tableNameToUse = tableName.toLowerCase(); // // Add the new callout to our internal map final AtomicBoolean registered = new AtomicBoolean(false); registeredCalloutsByTableId.compute(tableNameToUse, (tableNameKey, currentTabCalloutsMap) -> { if (currentTabCalloutsMap == null) { registered.set(true); return TableCalloutsMap.of(columnName, callout); } else { final TableCalloutsMap newTabCalloutsMap = currentTabCalloutsMap.compose(columnName, callout); registered.set(newTabCalloutsMap != currentTabCalloutsMap); return newTabCalloutsMap; } }); // Stop here if it was not registered if (!registered.get()) { return false; } logger.debug("Registered callout for {}.{}: {}", tableNameToUse, columnName, callout); // Make sure this provider is registered to ICalloutFactory. // We assume the factory won't register it twice. Services.get(ICalloutFactory.class).registerCalloutProvider(this); return true; } @Override public boolean registerAnnotatedCallout(final Object annotatedCalloutObj) { final List<AnnotatedCalloutInstance> calloutInstances = new AnnotatedCalloutInstanceFactory() .setAnnotatedCalloutObject(annotatedCalloutObj) .create();
if (calloutInstances.isEmpty()) { throw new AdempiereException("No binding columns found for " + annotatedCalloutObj + " (class=" + annotatedCalloutObj.getClass() + ")"); } boolean registered = false; for (final AnnotatedCalloutInstance calloutInstance : calloutInstances) { final String tableName = calloutInstance.getTableName(); for (final String columnName : calloutInstance.getColumnNames()) { final boolean columNameRegistered = registerCallout(tableName, columnName, calloutInstance); if (columNameRegistered) { registered = true; } } } return registered; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\ProgramaticCalloutProvider.java
1
请完成以下Java代码
public InputStream getProcessModel(String processDefinitionId) { return commandExecutor.execute(new GetDeploymentProcessModelCmd(processDefinitionId)); } public Model newModel() { return commandExecutor.execute(new CreateModelCmd()); } public void saveModel(Model model) { commandExecutor.execute(new SaveModelCmd((ModelEntity) model)); } public void deleteModel(String modelId) { commandExecutor.execute(new DeleteModelCmd(modelId)); } public void addModelEditorSource(String modelId, byte[] bytes) { commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes)); } public void addModelEditorSourceExtra(String modelId, byte[] bytes) { commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes)); } public ModelQuery createModelQuery() { return new ModelQueryImpl(commandExecutor); } @Override public NativeModelQuery createNativeModelQuery() { return new NativeModelQueryImpl(commandExecutor); } public Model getModel(String modelId) { return commandExecutor.execute(new GetModelCmd(modelId));
} public byte[] getModelEditorSource(String modelId) { return commandExecutor.execute(new GetModelEditorSourceCmd(modelId)); } public byte[] getModelEditorSourceExtra(String modelId) { return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId)); } public void addCandidateStarterUser(String processDefinitionId, String userId) { commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null)); } public void addCandidateStarterGroup(String processDefinitionId, String groupId) { commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId)); } public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) { commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId)); } public void deleteCandidateStarterUser(String processDefinitionId, String userId) { commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null)); } public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) { return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId)); } public List<ValidationError> validateProcess(BpmnModel bpmnModel) { return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RepositoryServiceImpl.java
1
请完成以下Java代码
public void setAD_Scheduler_ID (final int AD_Scheduler_ID) { if (AD_Scheduler_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, AD_Scheduler_ID); } @Override public int getAD_Scheduler_ID() { return get_ValueAsInt(COLUMNNAME_AD_Scheduler_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public org.compiere.model.I_AD_Window getAD_Window() { return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setAD_Window(final org.compiere.model.I_AD_Window AD_Window) { set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window); } @Override public void setAD_Window_ID (final int AD_Window_ID) { if (AD_Window_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Window_ID, AD_Window_ID); } @Override public int getAD_Window_ID() { return get_ValueAsInt(COLUMNNAME_AD_Window_ID); } @Override public void setErrorMsg (final @Nullable java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override
public java.lang.String getErrorMsg() { return get_ValueAsString(COLUMNNAME_ErrorMsg); } @Override public void setIsProcessing (final boolean IsProcessing) { set_Value (COLUMNNAME_IsProcessing, IsProcessing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_IsProcessing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setResult (final int Result) { set_Value (COLUMNNAME_Result, Result); } @Override public int getResult() { return get_ValueAsInt(COLUMNNAME_Result); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
1
请在Spring Boot框架中完成以下Java代码
protected void createDefaultStructures(Element rootTypes) { NodeList complexTypes = rootTypes.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "complexType"); for (int i = 0; i < complexTypes.getLength(); i++) { Element element = (Element) complexTypes.item(i); String structureName = this.namespace + element.getAttribute("name"); SimpleStructureDefinition structure = new SimpleStructureDefinition(structureName); this.structures.put(structure.getId(), structure); } } protected Element getRootTypes() { try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(this.wsdlLocation); Element root = (Element) doc.getFirstChild(); Element typesElement = (Element) root.getElementsByTagName("wsdl:types").item(0); return (Element) typesElement.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "schema").item(0); } catch (SAXException | IOException | ParserConfigurationException e) { throw new FlowableException(e.getMessage(), e);
} } @Override public Map<String, StructureDefinition> getStructures() { return this.structures; } @Override public Map<String, WSService> getServices() { return this.wsServices; } @Override public Map<String, WSOperation> getOperations() { return this.wsOperations; } }
repos\flowable-engine-main\modules\flowable-cxf\src\main\java\org\flowable\engine\impl\webservice\WSDLImporter.java
2
请完成以下Java代码
public Duration getDelay() { return this.delay; } /** * Specify the base delay after the initial invocation. * <p> * If a {@linkplain #getMultiplier() multiplier} is specified, this serves as the * initial delay to multiply from. * @param delay the base delay (must be greater than or equal to zero) */ public void setDelay(Duration delay) { this.delay = delay; } /** * Return the jitter period to enable random retry attempts. * @return the jitter value */ public @Nullable Duration getJitter() { return this.jitter; } /** * Specify a jitter period for the base retry attempt, randomly subtracted or added to * the calculated delay, resulting in a value between {@code delay - jitter} and * {@code delay + jitter} but never below the {@linkplain #getDelay() base delay} or * above the {@linkplain #getMaxDelay() max delay}. * <p> * If a {@linkplain #getMultiplier() multiplier} is specified, it is applied to the * jitter value as well. * @param jitter the jitter value (must be positive) */ public void setJitter(@Nullable Duration jitter) { this.jitter = jitter; } /** * Return the value to multiply the current interval by for each attempt. The default * value, {@code 1.0}, effectively results in a fixed delay. * @return the value to multiply the current interval by for each attempt * @see #DEFAULT_MULTIPLIER */ public Double getMultiplier() { return this.multiplier; } /** * Specify a multiplier for a delay for the next retry attempt. * @param multiplier value to multiply the current interval by for each attempt (must * be greater than or equal to 1) */ public void setMultiplier(Double multiplier) { this.multiplier = multiplier;
} /** * Return the maximum delay for any retry attempt. * @return the maximum delay */ public Duration getMaxDelay() { return this.maxDelay; } /** * Specify the maximum delay for any retry attempt, limiting how far * {@linkplain #getJitter() jitter} and the {@linkplain #getMultiplier() multiplier} * can increase the {@linkplain #getDelay() delay}. * <p> * The default is unlimited. * @param maxDelay the maximum delay (must be positive) * @see #DEFAULT_MAX_DELAY */ public void setMaxDelay(Duration maxDelay) { this.maxDelay = maxDelay; } /** * Set the factory to use to create the {@link RetryPolicy}, or {@code null} to use * the default. The function takes a {@link Builder RetryPolicy.Builder} initialized * with the state of this instance that can be further configured, or ignored to * restart from scratch. * @param factory a factory to customize the retry policy. */ public void setFactory(@Nullable Function<RetryPolicy.Builder, RetryPolicy> factory) { this.factory = factory; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\retry\RetryPolicySettings.java
1