instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { final JsonQRCode pickFromHU = getPickingJob(wfProcess) .getPickFromHU() .map(SetPickFromHUWFActivityHandler::toJsonQRCode) .orElse(null); return SetScannedBarcodeSupportHelper.uiComponent() .currentValue(pickFromHU) .alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser()) .build(); } public static JsonQRCode toJsonQRCode(final HUInfo pickFromHU) { final HUQRCode qrCode = pickFromHU.getQrCode(); return JsonQRCode.builder() .qrCode(qrCode.toGlobalQRCodeString()) .caption(qrCode.toDisplayableQRCode()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { final PickingJob pickingJob = getPickingJob(wfProcess); return computeActivityState(pickingJob); }
public static WFActivityStatus computeActivityState(final PickingJob pickingJob) { return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request) { final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode()); final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode); final HUInfo pickFromHU = HUInfo.builder() .id(huId) .qrCode(qrCode) .build(); return PickingMobileApplication.mapPickingJob( request.getWfProcess(), pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU) ); } private HUQRCode parseHUQRCode(final String scannedCode) { final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode); if (huQRCode instanceof HUQRCode) { return (HUQRCode)huQRCode; } else { throw new AdempiereException("Invalid HU QR code: " + scannedCode); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() throws Exception { final List<HUToReport> topLevelHus = new ArrayList<>(); final ImmutableList<HUToReport> hus = handlingUnitsDAO.streamByQuery(retrieveSelectedRecordsQueryBuilder(I_M_HU.class), HUToReportWrapper::of) .filter(hu -> hu.getHUUnitType() != VHU) .peek(topLevelHus::add) .flatMap(hu -> { if (hu.getHUUnitType() == LU) { return Stream.concat(Stream.of(hu), hu.getIncludedHUs().stream()); } else { return Stream.of(hu); } }) .filter(hu -> hu.getHUUnitType() != VHU) .collect(ImmutableList.toImmutableList());
final Set<HuId> huIdSet = hus.stream().map(HUToReport::getHUId).collect(ImmutableSet.toImmutableSet()); huqrCodesService.generateForExistingHUs(huIdSet); topLevelHus.stream() .sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId())) .forEach(topLevelHu -> { labelService.printNow(HULabelDirectPrintRequest.builder() .onlyOneHUPerPrint(true) .printCopies(PrintCopies.ofIntOrOne(p_PrintCopies)) .printFormatProcessId(p_AD_Process_ID) .hu(topLevelHu) .build()); if (topLevelHu.getHUUnitType() == LU && !topLevelHu.getIncludedHUs().isEmpty()) { final List<HUToReport> sortedIncludedHUs = topLevelHu.getIncludedHUs() .stream() .sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId())) .collect(ImmutableList.toImmutableList()); labelService.printNow(HULabelDirectPrintRequest.builder() .onlyOneHUPerPrint(true) .printCopies(PrintCopies.ofIntOrOne(p_PrintCopies)) .printFormatProcessId(p_AD_Process_ID) .hus(sortedIncludedHUs) .build()); } }); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_MultipleSelection_Report_Print_Label.java
1
请完成以下Java代码
public int getIntMinimumAge() { return toInt(this.minimumAge); } public void setIntMinimumAge(int years) { minimumAge = toPeriod(years); } @Column("MAX_AGE") public int getIntMaximumAge() { return toInt(this.maximumAge); } public void setIntMaximumAge(int years) { maximumAge = toPeriod(years);
} private static int toInt(Period period) { return (int) (period == null ? 0 : period.get(ChronoUnit.YEARS)); } private static Period toPeriod(int years) { return Period.ofYears(years); } public void addModel(String name, String description) { var model = new Model(name, description); models.put(name, model); } }
repos\spring-data-examples-main\jdbc\basics\src\main\java\example\springdata\jdbc\basics\aggregate\LegoSet.java
1
请完成以下Java代码
public String getDescriptionURL () { return (String)get_Value(COLUMNNAME_DescriptionURL); } /** Set Knowledge Source. @param K_Source_ID Source of a Knowledge Entry */ public void setK_Source_ID (int K_Source_ID) { if (K_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID)); } /** Get Knowledge Source. @return Source of a Knowledge Entry */ public int getK_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Source.java
1
请完成以下Java代码
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // nothing to do return null; } @Override public String docValidate(final PO po, final int timing) { // nothing to do return null; } @Override public String modelChange(final PO po, int type) { assert po instanceof MInvoiceLine : po; if (type == TYPE_BEFORE_CHANGE || type == TYPE_BEFORE_NEW) { final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class); final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class); if (!il.isProcessed()) { logger.debug("Reevaluating tax for " + il); invoiceLineBL.setTaxBasedOnShipment(il, po.get_TrxName()); logger.debug("Setting TaxAmtInfo for " + il); invoiceLineBL.setTaxAmtInfo(po.getCtx(), il, po.get_TrxName()); } // Introduced by US1184, because having the same price on Order and Invoice is enforced by German Law if (invoiceLineBL.isPriceLocked(il)) { assertOrderInvoicePricesMatch(il); } } else if (type == TYPE_BEFORE_DELETE) { final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class); beforeDelete(il); } return null; } void beforeDelete(final org.compiere.model.I_C_InvoiceLine invoiceLine) { final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class);
final InvoiceAndLineId invoiceAndLineId = InvoiceAndLineId.ofRepoId(invoiceLine.getC_Invoice_ID(), invoiceLine.getC_InvoiceLine_ID()); for (final I_C_InvoiceLine refInvoiceLine : invoiceDAO.retrieveReferringLines(invoiceAndLineId)) { refInvoiceLine.setRef_InvoiceLine_ID(0); invoiceDAO.save(refInvoiceLine); } } public static void assertOrderInvoicePricesMatch(final I_C_InvoiceLine invoiceLine) { final I_C_OrderLine oline = invoiceLine.getC_OrderLine(); if (invoiceLine.getPriceActual().compareTo(oline.getPriceActual()) != 0) { throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceActual, oline.getPriceActual(), invoiceLine.getPriceActual()); } if (invoiceLine.getPriceList().compareTo(oline.getPriceList()) != 0) { throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceList, oline.getPriceList(), invoiceLine.getPriceList()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\InvoiceLine.java
1
请完成以下Java代码
public I_W_ClickCount getW_ClickCount() throws RuntimeException { return (I_W_ClickCount)MTable.get(getCtx(), I_W_ClickCount.Table_Name) .getPO(getW_ClickCount_ID(), get_TrxName()); } /** Set Click Count. @param W_ClickCount_ID Web Click Management */ public void setW_ClickCount_ID (int W_ClickCount_ID) { if (W_ClickCount_ID < 1) set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_ClickCount_ID, Integer.valueOf(W_ClickCount_ID)); } /** Get Click Count. @return Web Click Management */ public int getW_ClickCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_ClickCount_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Web Click. @param W_Click_ID Individual Web Click */ public void setW_Click_ID (int W_Click_ID) {
if (W_Click_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Click_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Click_ID, Integer.valueOf(W_Click_ID)); } /** Get Web Click. @return Individual Web Click */ public int getW_Click_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Click_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Click.java
1
请完成以下Java代码
protected final Builder tokens(Map<Class<? extends OAuth2Token>, Token<?>> tokens) { this.tokens = new HashMap<>(tokens); return this; } /** * Adds an attribute associated to the authorization. * @param name the name of the attribute * @param value the value of the attribute * @return the {@link Builder} */ public Builder attribute(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.attributes.put(name, value); return this; } /** * A {@code Consumer} of the attributes {@code Map} allowing the ability to add, * replace, or remove. * @param attributesConsumer a {@link Consumer} of the attributes {@code Map} * @return the {@link Builder} */ public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) { attributesConsumer.accept(this.attributes); return this; } /** * Builds a new {@link OAuth2Authorization}. * @return the {@link OAuth2Authorization} */ public OAuth2Authorization build() { Assert.hasText(this.principalName, "principalName cannot be empty");
Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null"); OAuth2Authorization authorization = new OAuth2Authorization(); if (!StringUtils.hasText(this.id)) { this.id = UUID.randomUUID().toString(); } authorization.id = this.id; authorization.registeredClientId = this.registeredClientId; authorization.principalName = this.principalName; authorization.authorizationGrantType = this.authorizationGrantType; authorization.authorizedScopes = Collections.unmodifiableSet(!CollectionUtils.isEmpty(this.authorizedScopes) ? new HashSet<>(this.authorizedScopes) : new HashSet<>()); authorization.tokens = Collections.unmodifiableMap(this.tokens); authorization.attributes = Collections.unmodifiableMap(this.attributes); return authorization; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2Authorization.java
1
请完成以下Java代码
public Optional<String> getAllPackagesContentDescription() { final String description = packageInfos.stream() .map(PackageInfo::getDescription) .map(StringUtils::trimBlankToNull) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); return StringUtils.trimBlankToOptional(description); } @Value @Builder public static class PackageInfo { @NonNull PackageId packageId; @Nullable String poReference; @Nullable String description; @Nullable BigDecimal weightInKg; @NonNull PackageDimensions packageDimension; public BigDecimal getWeightInKgOr(final BigDecimal minValue) {return weightInKg != null ? weightInKg.max(minValue) : minValue;} } } @Value @EqualsAndHashCode(exclude = "carrierServices") class DeliveryOrderKey { @NonNull ShipperId shipperId; @NonNull ShipperTransportationId shipperTransportationId; int fromOrgId; int deliverToBPartnerId; int deliverToBPartnerLocationId; @NonNull LocalDate pickupDate; @NonNull LocalTime timeFrom; @NonNull LocalTime timeTo; @Nullable CarrierProductId carrierProductId; @Nullable CarrierGoodsTypeId carrierGoodsTypeId; @Nullable Set<CarrierServiceId> carrierServices; AsyncBatchId asyncBatchId; @Builder
public DeliveryOrderKey( @NonNull final ShipperId shipperId, @NonNull final ShipperTransportationId shipperTransportationId, final int fromOrgId, final int deliverToBPartnerId, final int deliverToBPartnerLocationId, @NonNull final LocalDate pickupDate, @NonNull final LocalTime timeFrom, @NonNull final LocalTime timeTo, @Nullable final CarrierProductId carrierProductId, @Nullable final CarrierGoodsTypeId carrierGoodsTypeId, @Nullable final Set<CarrierServiceId> carrierServices, @Nullable final AsyncBatchId asyncBatchId) { Check.assume(fromOrgId > 0, "fromOrgId > 0"); Check.assume(deliverToBPartnerId > 0, "deliverToBPartnerId > 0"); Check.assume(deliverToBPartnerLocationId > 0, "deliverToBPartnerLocationId > 0"); this.shipperId = shipperId; this.shipperTransportationId = shipperTransportationId; this.fromOrgId = fromOrgId; this.deliverToBPartnerId = deliverToBPartnerId; this.deliverToBPartnerLocationId = deliverToBPartnerLocationId; this.pickupDate = pickupDate; this.timeFrom = timeFrom; this.timeTo = timeTo; this.carrierProductId = carrierProductId; this.carrierGoodsTypeId = carrierGoodsTypeId; this.carrierServices = carrierServices; this.asyncBatchId = asyncBatchId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\DraftDeliveryOrderCreator.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getHelpCount() { return helpCount; } public void setHelpCount(Integer helpCount) { this.helpCount = helpCount; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; }
public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", icon=").append(icon); sb.append(", helpCount=").append(helpCount); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpCategory.java
1
请完成以下Java代码
public int getAD_PrinterHW_MediaTray_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID); } @Override public void setCalX (int CalX) { set_Value (COLUMNNAME_CalX, Integer.valueOf(CalX)); } @Override public int getCalX() { return get_ValueAsInt(COLUMNNAME_CalX); } @Override public void setCalY (int CalY) { set_Value (COLUMNNAME_CalY, Integer.valueOf(CalY)); } @Override public int getCalY() { return get_ValueAsInt(COLUMNNAME_CalY); } @Override public de.metas.printing.model.I_C_Print_Package getC_Print_Package() { return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class); } @Override public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package) { set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package); } @Override public void setC_Print_Package_ID (int C_Print_Package_ID) { if (C_Print_Package_ID < 1) set_Value (COLUMNNAME_C_Print_Package_ID, null); else set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID)); } @Override public int getC_Print_Package_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID); } @Override public void setC_Print_PackageInfo_ID (int C_Print_PackageInfo_ID) { if (C_Print_PackageInfo_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Print_PackageInfo_ID, Integer.valueOf(C_Print_PackageInfo_ID)); } @Override public int getC_Print_PackageInfo_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_PackageInfo_ID); } @Override public void setName (java.lang.String Name) { throw new IllegalArgumentException ("Name is virtual column"); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name);
} @Override public void setPageFrom (int PageFrom) { set_Value (COLUMNNAME_PageFrom, Integer.valueOf(PageFrom)); } @Override public int getPageFrom() { return get_ValueAsInt(COLUMNNAME_PageFrom); } @Override public void setPageTo (int PageTo) { set_Value (COLUMNNAME_PageTo, Integer.valueOf(PageTo)); } @Override public int getPageTo() { return get_ValueAsInt(COLUMNNAME_PageTo); } @Override public void setPrintServiceName (java.lang.String PrintServiceName) { throw new IllegalArgumentException ("PrintServiceName is virtual column"); } @Override public java.lang.String getPrintServiceName() { return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName); } @Override public void setTrayNumber (int TrayNumber) { throw new IllegalArgumentException ("TrayNumber is virtual column"); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_PackageInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class WeekDaysHolder { @Value("${monday}") private WeekDays monday; @Value("${tuesday}") private WeekDays tuesday; @Value("${wednesday}") private WeekDays wednesday; @Value("${thursday}") private WeekDays thursday; @Value("${friday}") private WeekDays friday; @Value("${saturday}") private WeekDays saturday; @Value("${sunday}") private WeekDays sunday; public WeekDays getMonday() { return monday; } public void setMonday(final WeekDays monday) { this.monday = monday; } public WeekDays getTuesday() { return tuesday; } public void setTuesday(final WeekDays tuesday) { this.tuesday = tuesday; } public WeekDays getWednesday() {
return wednesday; } public void setWednesday(final WeekDays wednesday) { this.wednesday = wednesday; } public WeekDays getThursday() { return thursday; } public void setThursday(final WeekDays thursday) { this.thursday = thursday; } public WeekDays getFriday() { return friday; } public void setFriday(final WeekDays friday) { this.friday = friday; } public WeekDays getSaturday() { return saturday; } public void setSaturday(final WeekDays saturday) { this.saturday = saturday; } public WeekDays getSunday() { return sunday; } public void setSunday(final WeekDays sunday) { this.sunday = sunday; } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-4\src\main\java\com\baeldung\caseinsensitiveenum\week\WeekDaysHolder.java
2
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Privilege> getPrivileges() { return privileges; } public void setPrivileges(Set<Privilege> privileges) { this.privileges = privileges; } public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((id == null) ? 0 : id.hashCode()); result = (prime * result) + ((organization == null) ? 0 : organization.hashCode()); result = (prime * result) + ((password == null) ? 0 : password.hashCode()); result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode()); result = (prime * result) + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if (id == null) {
if (other.id != null) { return false; } } else if (!id.equals(other.id)) { return false; } if (organization == null) { if (other.organization != null) { return false; } } else if (!organization.equals(other.organization)) { return false; } if (password == null) { if (other.password != null) { return false; } } else if (!password.equals(other.password)) { return false; } if (privileges == null) { if (other.privileges != null) { return false; } } else if (!privileges.equals(other.privileges)) { return false; } if (username == null) { if (other.username != null) { return false; } } else if (!username.equals(other.username)) { return false; } return true; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\User.java
1
请完成以下Java代码
public int getMKTG_CleverReach_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_CleverReach_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MKTG_Platform. @param MKTG_Platform_ID MKTG_Platform */ @Override public void setMKTG_Platform_ID (int MKTG_Platform_ID) { if (MKTG_Platform_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID)); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password);
} /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java-gen\de\metas\marketing\cleverreach\model\X_MKTG_CleverReach_Config.java
1
请完成以下Java代码
public int getAD_Org_ID() { return adOrgId; } @Override public I_M_Warehouse getM_Warehouse() { return warehouse; } @Override public int getM_Warehouse_ID() { return warehouseId; } @Override public IMRPSegment setM_Warehouse(final I_M_Warehouse warehouse) { final int warehouseIdNew; if (warehouse == null || warehouse.getM_Warehouse_ID() <= 0) { warehouseIdNew = -1; } else { warehouseIdNew = warehouse.getM_Warehouse_ID(); } // No change => return this if (warehouseIdNew == this.warehouseId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.warehouseId = warehouseIdNew; mrpSegmentNew.warehouse = warehouse; return mrpSegmentNew; } @Override public I_S_Resource getPlant() { return plant; } @Override public int getPlant_ID() { return plantId; } @Override public IMRPSegment setPlant(final I_S_Resource plant) { final int plantIdNew; if (plant == null || plant.getS_Resource_ID() <= 0) { plantIdNew = -1; } else { plantIdNew = plant.getS_Resource_ID(); } // No change => return this if (plantIdNew == this.plantId) { return this;
} final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.plantId = plantIdNew; mrpSegmentNew.plant = plant; return mrpSegmentNew; } @Override public I_M_Product getM_Product() { return product; } @Override public int getM_Product_ID() { return productId; } @Override public IMRPSegment setM_Product(final I_M_Product product) { final int productIdNew; if (product == null || product.getM_Product_ID() <= 0) { productIdNew = -1; } else { productIdNew = product.getM_Product_ID(); } // No change => return this if (productIdNew == this.productId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.productId = productIdNew; mrpSegmentNew.product = product; return mrpSegmentNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPSegment.java
1
请完成以下Java代码
public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getYear() { return year; } public void setYear(int year) { this.year = year;
} public String getEngine() { return engine; } public void setEngine(String engine) { this.engine = engine; } public Manufacturer getManufacturer() { return manufacturer; } public void setManufacturer(Manufacturer manufacturer) { this.manufacturer = manufacturer; } }
repos\tutorials-master\spring-jinq\src\main\java\com\baeldung\spring\jinq\entities\Car.java
1
请完成以下Java代码
public ResponseEntity<JsonRRequestUpsertResponse> createRequest(@RequestBody @NonNull final JsonRRequestUpsertRequest request) { try { return ResponseEntity.status(HttpStatus.CREATED) .body(requestRestService.upsert(request)); } catch (final Exception ex) { logger.error("Create request failed for {}", request, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.unprocessableEntity() .body(JsonRRequestUpsertResponse.builder() .error(JsonErrors.ofThrowable(ex, adLanguage)) .build()); } } @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully created or updated request"), @ApiResponse(code = 400, message = "The provided requestId is not a number"), @ApiResponse(code = 401, message = "You are not authorized to get the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 404, message = "The request entity could not be found") }) @GetMapping("/{requestId}") public ResponseEntity getById(@PathVariable(name = "requestId") @NonNull final String requestIdStr) { try {
final RequestId requestId = RequestId.ofRepoId(Integer.parseInt(requestIdStr)); final JsonRRequest response = requestRestService.getByIdOrNull(requestId); return response == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(response); } catch (final NumberFormatException ex) { logger.error("Invalid requestId: {}", requestIdStr); return ResponseEntity.badRequest().build(); } catch (final Exception ex) { logger.error("Get request failed for {}", requestIdStr, ex); final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.unprocessableEntity() .body(JsonErrors.ofThrowable(ex, adLanguage)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\request\RequestRestController.java
1
请完成以下Java代码
public class CatSpanBuilder implements Tracer.SpanBuilder { private List<cn.iocoder.springboot.lab61.cat.opentracing.Tag> tags = new LinkedList<>(); private String operationName; public CatSpanBuilder(String operationName) { this.operationName = operationName; } public Tracer.SpanBuilder asChildOf(SpanContext parent) { return null; } public Tracer.SpanBuilder asChildOf(Span parent) { return null; } public Tracer.SpanBuilder addReference(String referenceType, SpanContext referencedContext) { return null; } public Tracer.SpanBuilder ignoreActiveSpan() { return null; } public Tracer.SpanBuilder withTag(String key, String value) {
tags.add(new cn.iocoder.springboot.lab61.cat.opentracing.Tag(key, value)); return this; } public Tracer.SpanBuilder withTag(String key, boolean value) { return null; } public Tracer.SpanBuilder withTag(String key, Number value) { return null; } public <T> Tracer.SpanBuilder withTag(Tag<T> tag, T value) { return null; } public Tracer.SpanBuilder withStartTimestamp(long microseconds) { return null; } public Span start() { Transaction transaction = Cat.newTransaction("Opentracing", operationName); // TODO tag 的处理 return new CatSpan(transaction); } }
repos\SpringBoot-Labs-master\lab-61\lab-61-cat-opentracing\src\main\java\cn\iocoder\springboot\lab61\cat\opentracing\CatSpanBuilder.java
1
请完成以下Java代码
protected void closeGroup(final I_C_OrderLine purchaseOrderLine) { final List<I_C_OrderLine> salesOrderLines = purchaseOrderLine2saleOrderLines.get(purchaseOrderLine); final Set<OrderId> salesOrdersToBeClosed = new HashSet<>(); final OrderId singleSalesOrderId = extractSingleOrderIdOrNull(salesOrderLines); purchaseOrderLine.setC_OrderSO_ID(OrderId.toRepoId(singleSalesOrderId)); InterfaceWrapperHelper.save(purchaseOrderLine); for (final I_C_OrderLine salesOrderLine : purchaseOrderLine2saleOrderLines.get(purchaseOrderLine)) { orderDAO.allocatePOLineToSOLine( OrderLineId.ofRepoId(purchaseOrderLine.getC_OrderLine_ID()), OrderLineId.ofRepoId(salesOrderLine.getC_OrderLine_ID())); salesOrdersToBeClosed.add(OrderId.ofRepoId(salesOrderLine.getC_Order_ID())); } if (PurchaseTypeEnum.MEDIATED.equals(purchaseType)) { salesOrdersToBeClosed.forEach(orderBL::closeOrder); } } @Override protected void addItemToGroup(final I_C_OrderLine purchaseOrderLine, final I_C_OrderLine salesOrderLine) { final BigDecimal oldQtyEntered = purchaseOrderLine.getQtyEntered(); // the purchase order line's UOM is the internal stocking UOM, so we don't need to convert from qtyOrdered/qtyReserved to qtyEntered. final BigDecimal purchaseQty; if (I_C_OrderLine.COLUMNNAME_QtyOrdered.equals(purchaseQtySource)) { purchaseQty = PurchaseTypeEnum.MEDIATED.equals(purchaseType) ? salesOrderLine.getQtyOrdered().subtract(salesOrderLine.getQtyDelivered()) : salesOrderLine.getQtyOrdered(); } else if (I_C_OrderLine.COLUMNNAME_QtyReserved.equals(purchaseQtySource)) {
purchaseQty = salesOrderLine.getQtyReserved(); } else { Check.errorIf(true, "Unsupported purchaseQtySource={}", purchaseQtySource); purchaseQty = null; // won't be reached } final BigDecimal newQtyEntered = oldQtyEntered.add(purchaseQty); // setting QtyEntered, because qtyOrdered will be set from qtyEntered by a model interceptor purchaseOrderLine.setQtyEntered(newQtyEntered); purchaseOrderLine2saleOrderLines.get(purchaseOrderLine).add(salesOrderLine); // no NPE, because the list for this key was added in createGroup() } I_C_Order getPurchaseOrder() { return purchaseOrder; } @Override public String toString() { return ObjectUtils.toString(this); } @Nullable private static OrderId extractSingleOrderIdOrNull(final List<I_C_OrderLine> orderLines) { return CollectionUtils.extractSingleElementOrDefault( orderLines, orderLine -> OrderId.ofRepoId(orderLine.getC_Order_ID()), null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\po_from_so\impl\CreatePOLineFromSOLinesAggregator.java
1
请在Spring Boot框架中完成以下Java代码
public class RouteToRecipientsExample { @MessagingGateway public interface NumbersClassifier { @Gateway(requestChannel = "classify.input") void classify(Collection<Integer> numbers); } @Bean QueueChannel multipleofThreeChannel() { return new QueueChannel(); } @Bean QueueChannel remainderIsOneChannel() { return new QueueChannel(); } @Bean QueueChannel remainderIsTwoChannel() { return new QueueChannel(); } boolean isMultipleOfThree(Integer number) { return number % 3 == 0;
} boolean isRemainderOne(Integer number) { return number % 3 == 1; } boolean isRemainderTwo(Integer number) { return number % 3 == 2; } @Bean public IntegrationFlow classify() { return flow -> flow.split() .routeToRecipients(route -> route .recipientFlow(subflow -> subflow .<Integer> filter(this::isMultipleOfThree) .channel("multipleofThreeChannel")) .<Integer> recipient("remainderIsOneChannel",this::isRemainderOne) .<Integer> recipient("remainderIsTwoChannel",this::isRemainderTwo)); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\routetorecipients\RouteToRecipientsExample.java
2
请完成以下Java代码
public static void apply(@Nullable final LUPickingTarget target, @NonNull final CaseConsumer consumer) { if (target == null) { consumer.noLU(); } else if (target.isNewLU()) { consumer.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { consumer.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); } else { throw new AdempiereException("Unsupported target type: " + target); } } public static <T> T apply(@Nullable final LUPickingTarget target, @NonNull final CaseMapper<T> mapper) {
if (target == null) { return mapper.noLU(); } else if (target.isNewLU()) { return mapper.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { return mapper.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); } else { throw new AdempiereException("Unsupported target type: " + target); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUPickingTarget.java
1
请完成以下Java代码
public void windowOpened(WindowEvent e) { // NOTE: we need to do this for AMenu which is created before login windowHeaderNotice.load(); } }); } // frameInit /** * Cleanedup Title * @param title title * @return title w/o mn */ private static String cleanup (String title) { if (title != null) { int pos = title.indexOf('&'); if (pos != -1 && title.length() > pos) // We have a mnemonic { int mnemonic = title.toUpperCase().charAt(pos+1); if (mnemonic != ' ') { title = title.substring(0, pos) + title.substring(pos+1); }
} } return title; } // getTitle /** * Set Title * @param title title */ @Override public void setTitle(String title) { super.setTitle(cleanup(title)); } // setTitle public AdWindowId getAdWindowId() { return adWindowId; } // getAD_Window_ID public void setAdWindowId(@Nullable final AdWindowId adWindowId) { this.adWindowId = adWindowId; } } // CFrame
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CFrame.java
1
请完成以下Java代码
protected Class<?> getProcessDomainObjectClass() { return this.processDomainObjectClass; } protected boolean hasPermission(Authentication authentication, Object domainObject) { // Obtain the OID applicable to the domain object ObjectIdentity objectIdentity = this.objectIdentityRetrievalStrategy.getObjectIdentity(domainObject); // Obtain the SIDs applicable to the principal List<Sid> sids = this.sidRetrievalStrategy.getSids(authentication); try { // Lookup only ACLs for SIDs we're interested in Acl acl = this.aclService.readAclById(objectIdentity, sids); return acl.isGranted(this.requirePermission, sids, false); } catch (NotFoundException ex) { return false; } } public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) { Assert.notNull(objectIdentityRetrievalStrategy, "ObjectIdentityRetrievalStrategy required"); this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy; } protected void setProcessConfigAttribute(String processConfigAttribute) { Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory"); this.processConfigAttribute = processConfigAttribute; } public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) { Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null"); this.processDomainObjectClass = processDomainObjectClass; }
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) { Assert.notNull(sidRetrievalStrategy, "SidRetrievalStrategy required"); this.sidRetrievalStrategy = sidRetrievalStrategy; } @Override public boolean supports(ConfigAttribute attribute) { return this.processConfigAttribute.equals(attribute.getAttribute()); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\acls\afterinvocation\AbstractAclProvider.java
1
请完成以下Java代码
public boolean isOpen() { return !this.closed; } @Override public void close() throws IOException { if (this.closed) { return; } this.closed = true; try { this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } @Override public int read(ByteBuffer dst) throws IOException { assertNotClosed(); int total = 0; while (dst.remaining() > 0) { int count = this.resources.getData().read(dst, this.position); if (count <= 0) { return (total != 0) ? 0 : count; } total += count; this.position += count; } return total; } @Override public int write(ByteBuffer src) throws IOException { throw new NonWritableChannelException(); } @Override public long position() throws IOException { assertNotClosed(); return this.position; } @Override public SeekableByteChannel position(long position) throws IOException { assertNotClosed(); if (position < 0 || position >= this.size) { throw new IllegalArgumentException("Position must be in bounds"); } this.position = position; return this; } @Override public long size() throws IOException { assertNotClosed(); return this.size; } @Override public SeekableByteChannel truncate(long size) throws IOException { throw new NonWritableChannelException(); } private void assertNotClosed() throws ClosedChannelException { if (this.closed) { throw new ClosedChannelException(); } } /** * Resources used by the channel and suitable for registration with a {@link Cleaner}. */ static class Resources implements Runnable {
private final ZipContent zipContent; private final CloseableDataBlock data; Resources(Path path, String nestedEntryName) throws IOException { this.zipContent = ZipContent.open(path, nestedEntryName); this.data = this.zipContent.openRawZipData(); } DataBlock getData() { return this.data; } @Override public void run() { releaseAll(); } private void releaseAll() { IOException exception = null; try { this.data.close(); } catch (IOException ex) { exception = ex; } try { this.zipContent.close(); } catch (IOException ex) { if (exception != null) { ex.addSuppressed(exception); } exception = ex; } if (exception != null) { throw new UncheckedIOException(exception); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
1
请完成以下Java代码
public Class<? extends ObservationConvention<? extends Context>> getDefaultConvention() { return DefaultRabbitListenerObservationConvention.class; } @Override public KeyName[] getLowCardinalityKeyNames() { return ListenerLowCardinalityTags.values(); } @Override public KeyName[] getHighCardinalityKeyNames() { return ListenerHighCardinalityTags.values(); } }; /** * Low cardinality tags. */ public enum ListenerLowCardinalityTags implements KeyName { /** * Listener id. */ LISTENER_ID { @Override public String asString() { return "spring.rabbit.listener.id"; } }, /** * The queue the listener is plugged to. * * @since 3.2 */ DESTINATION_NAME { @Override public String asString() { return "messaging.destination.name"; } } } /** * High cardinality tags. * * @since 3.2.1 */ public enum ListenerHighCardinalityTags implements KeyName { /** * The delivery tag. */ DELIVERY_TAG { @Override public String asString() { return "messaging.rabbitmq.message.delivery_tag"; }
} } /** * Default {@link RabbitListenerObservationConvention} for Rabbit listener key values. */ public static class DefaultRabbitListenerObservationConvention implements RabbitListenerObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultRabbitListenerObservationConvention INSTANCE = new DefaultRabbitListenerObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(RabbitMessageReceiverContext context) { MessageProperties messageProperties = context.getCarrier().getMessageProperties(); String consumerQueue = Objects.requireNonNullElse(messageProperties.getConsumerQueue(), ""); return KeyValues.of( RabbitListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(), context.getListenerId(), RabbitListenerObservation.ListenerLowCardinalityTags.DESTINATION_NAME.asString(), consumerQueue); } @Override public KeyValues getHighCardinalityKeyValues(RabbitMessageReceiverContext context) { return KeyValues.of(RabbitListenerObservation.ListenerHighCardinalityTags.DELIVERY_TAG.asString(), String.valueOf(context.getCarrier().getMessageProperties().getDeliveryTag())); } @Override public String getContextualName(RabbitMessageReceiverContext context) { return context.getSource() + " receive"; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitListenerObservation.java
1
请在Spring Boot框架中完成以下Java代码
static class IgnoredCloudFoundryPathsWebSecurityConfiguration { private static final int FILTER_CHAIN_ORDER = -1; @Bean @Order(FILTER_CHAIN_ORDER) SecurityFilterChain cloudFoundrySecurityFilterChain(HttpSecurity http, CloudFoundryWebEndpointServletHandlerMapping handlerMapping) { RequestMatcher cloudFoundryRequest = getRequestMatcher(handlerMapping); http.csrf((csrf) -> csrf.ignoringRequestMatchers(cloudFoundryRequest)); http.securityMatchers((matches) -> matches.requestMatchers(cloudFoundryRequest)) .authorizeHttpRequests((authorize) -> authorize.anyRequest().permitAll()); return http.build(); } private RequestMatcher getRequestMatcher(CloudFoundryWebEndpointServletHandlerMapping handlerMapping) {
PathMappedEndpoints endpoints = new PathMappedEndpoints(BASE_PATH, handlerMapping::getAllEndpoints); List<RequestMatcher> matchers = new ArrayList<>(); endpoints.getAllPaths().forEach((path) -> matchers.add(pathMatcher(path + "/**"))); matchers.add(pathMatcher(BASE_PATH)); matchers.add(pathMatcher(BASE_PATH + "/")); return new OrRequestMatcher(matchers); } private PathPatternRequestMatcher pathMatcher(String path) { return PathPatternRequestMatcher.withDefaults().matcher(path); } } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\CloudFoundryActuatorAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public Integer getSocketPort() { return socketPort; } public void setSocketPort(Integer socketPort) { this.socketPort = socketPort; } public Integer getPingInterval() { return pingInterval; } public void setPingInterval(Integer pingInterval) { this.pingInterval = pingInterval; } public Integer getPingTimeout() { return pingTimeout; } public void setPingTimeout(Integer pingTimeout) { this.pingTimeout = pingTimeout; } public String getImageDir() { return imageDir; } public void setImageDir(String imageDir) {
this.imageDir = imageDir; } public String getLoadJs() { return loadJs; } public void setLoadJs(String loadJs) { this.loadJs = loadJs; } public String getIndexHtml() { return indexHtml; } public void setIndexHtml(String indexHtml) { this.indexHtml = indexHtml; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\config\properties\MyProperties.java
2
请完成以下Java代码
public ShortcutType shortcutType() { return ShortcutType.GATHER_LIST; } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { HttpMethod requestMethod = exchange.getRequest().getMethod(); return stream(config.getMethods()).anyMatch(httpMethod -> httpMethod == requestMethod); } @Override public String toString() { return String.format("Methods: %s", Arrays.toString(config.getMethods())); } };
} public static class Config { private HttpMethod[] methods = new HttpMethod[0]; public HttpMethod[] getMethods() { return methods; } public void setMethods(HttpMethod... methods) { this.methods = methods; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\MethodRoutePredicateFactory.java
1
请完成以下Java代码
static String replaceForbiddenChars(@Nullable final String input) { if (input == null) { return null; } return input.replaceAll(FORBIDDEN_CHARS, "_"); } private String getBPartnerNameById(final int bpartnerRepoId) { final IBPartnerBL bpartnerService = Services.get(IBPartnerBL.class); return bpartnerService.getBPartnerName(BPartnerId.ofRepoIdOrNull(bpartnerRepoId)); } @NonNull private PartyIdentification32CHName convertPartyIdentification32CHName( @NonNull final I_SEPA_Export_Line line, @Nullable final BankAccount bankAccount, @NonNull final String paymentType) { final PartyIdentification32CHName cdtr = objectFactory.createPartyIdentification32CHName(); if (bankAccount == null) { cdtr.setNm(SepaUtils.replaceForbiddenChars(getFirstNonEmpty( line::getSEPA_MandateRefNo, () -> getBPartnerNameById(line.getC_BPartner_ID())))); } else { cdtr.setNm(SepaUtils.replaceForbiddenChars(getFirstNonEmpty( bankAccount::getAccountName, line::getSEPA_MandateRefNo, () -> getBPartnerNameById(line.getC_BPartner_ID())))); } final Properties ctx = InterfaceWrapperHelper.getCtx(line); final I_C_BPartner_Location billToLocation = partnerDAO.retrieveBillToLocation(ctx, line.getC_BPartner_ID(), true, ITrx.TRXNAME_None); if ((bankAccount == null || !bankAccount.isAddressComplete()) && billToLocation == null) { return cdtr; }
final I_C_Location location = locationDAO.getById(LocationId.ofRepoId(billToLocation.getC_Location_ID())); final PostalAddress6CH pstlAdr; if (Objects.equals(paymentType, PAYMENT_TYPE_5) || Objects.equals(paymentType, PAYMENT_TYPE_6)) { pstlAdr = createUnstructuredPstlAdr(bankAccount, location); } else { pstlAdr = createStructuredPstlAdr(bankAccount, location); } cdtr.setPstlAdr(pstlAdr); return cdtr; } @VisibleForTesting static boolean isInvalidQRReference(@NonNull final String reference) { if (reference.length() != 27) { return true; } final int[] checkSequence = { 0, 9, 4, 6, 8, 2, 7, 1, 3, 5 }; int carryOver = 0; for (int i = 1; i <= reference.length() - 1; i++) { final int idx = ((carryOver + Integer.parseInt(reference.substring(i - 1, i))) % 10); carryOver = checkSequence[idx]; } return !(Integer.parseInt(reference.substring(26)) == (10 - carryOver) % 10); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\sepamarshaller\impl\SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02.java
1
请完成以下Java代码
public void setSelectedItem(Object anItem) { } @Override public Object getSelectedItem() { return null; } @Override public void removeElementAt(int index) { } @Override public void removeElement(Object obj) { } @Override public void insertElementAt(Object obj, int index) { } @Override public void addElement(Object obj) { } }; public MutableComboBoxModelProxy() { super(); } public MutableComboBoxModelProxy(final MutableComboBoxModel delegate) { super(); setDelegate(delegate); } private final MutableComboBoxModel getDelegateToUse() { if (delegate == null) { return COMBOBOXMODEL_NULL; } return delegate; } public void setDelegate(final MutableComboBoxModel delegateNew) { if (this.delegate == delegateNew) { // nothing changed return; } // Unregister listeners on old lookup final MutableComboBoxModel delegateOld = this.delegate; if (delegateOld != null) { for (ListDataListener l : listenerList.getListeners(ListDataListener.class)) { delegateOld.removeListDataListener(l); } } // // Setup new Lookup this.delegate = delegateNew; // Register listeners on new lookup if (this.delegate != null) { for (ListDataListener l : listenerList.getListeners(ListDataListener.class)) { this.delegate.addListDataListener(l); } } } @Override public void addListDataListener(final ListDataListener l) { listenerList.add(ListDataListener.class, l); if (delegate != null) { delegate.addListDataListener(l); } } @Override public void removeListDataListener(final ListDataListener l) { listenerList.remove(ListDataListener.class, l); if (delegate != null) { delegate.removeListDataListener(l); } }
@Override public int getSize() { return getDelegateToUse().getSize(); } @Override public Object getElementAt(int index) { return getDelegateToUse().getElementAt(index); } @Override public void setSelectedItem(Object anItem) { getDelegateToUse().setSelectedItem(anItem); } @Override public Object getSelectedItem() { return getDelegateToUse().getSelectedItem(); } @Override public void addElement(Object obj) { getDelegateToUse().addElement(obj); } @Override public void removeElement(Object obj) { getDelegateToUse().removeElement(obj); } @Override public void insertElementAt(Object obj, int index) { getDelegateToUse().insertElementAt(obj, index); } @Override public void removeElementAt(int index) { getDelegateToUse().removeElementAt(index); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\MutableComboBoxModelProxy.java
1
请完成以下Java代码
public void setExtensionElements(Map<String, List<ExtensionElement>> extensionElements) { this.extensionElements = extensionElements; } @Override public Map<String, List<ExtensionAttribute>> getAttributes() { return attributes; } @Override public String getAttributeValue(String namespace, String name) { return Optional.ofNullable(getAttributes()) .map(map -> map.get(name)) .orElse(Collections.emptyList()) .stream() .filter(e -> this.isNamespaceMatching(namespace, e)) .findFirst() .map(ExtensionAttribute::getValue) .orElse(null); } private boolean isNamespaceMatching(String namespace, ExtensionAttribute attribute) { return ( (namespace == null && attribute.getNamespace() == null) || (namespace != null && namespace.equals(attribute.getNamespace())) ); } @Override public void addAttribute(ExtensionAttribute attribute) { if (attribute != null && isNotEmpty(attribute.getName())) { attributes.computeIfAbsent(attribute.getName(), key -> new ArrayList<>()); attributes.get(attribute.getName()).add(attribute); } } @Override public void setAttributes(Map<String, List<ExtensionAttribute>> attributes) { this.attributes = attributes; } public void setValues(BaseElement otherElement) { setId(otherElement.getId()); if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) { Map<String, List<ExtensionElement>> validExtensionElements = otherElement .getExtensionElements()
.entrySet() .stream() .filter(e -> hasElements(e.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); extensionElements.putAll(validExtensionElements); } if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) { Map<String, List<ExtensionAttribute>> validAttributes = otherElement .getAttributes() .entrySet() .stream() .filter(e -> hasElements(e.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); attributes.putAll(validAttributes); } } private boolean hasElements(List<?> listOfElements) { return listOfElements != null && !listOfElements.isEmpty(); } public abstract BaseElement clone(); }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BaseElement.java
1
请完成以下Java代码
public StockQtyAndUOMQty min(@NonNull final StockQtyAndUOMQty other) { if (this.getStockQty().compareTo(other.getStockQty()) <= 0) { return this; } return other; } /** * @return the minimum by looking at both stock and uom quantities. * Important: if this instance's stock and uom quantities are equal to {@code other}'s stock and uom quantities, then return {@code this}. */ public StockQtyAndUOMQty minStockAndUom(@NonNull final StockQtyAndUOMQty other) { if (this.getUOMQty() == null && other.getUOMQty() == null) { if (this.getStockQty().compareTo(other.getStockQty()) <= 0) { return this; } return other; } // If only one UOM quantity is null, it's an inconsistent state if (this.getUOMQty() == null || other.getUOMQty() == null) { throw new AdempiereException("UOM quantity is missing for only one quantity !"); } if (this.getStockQty().compareTo(other.getStockQty()) <= 0 && this.getUOMQty().compareTo(other.getUOMQty()) <= 0) { return this; } return other; } @Nullable @JsonIgnore public BigDecimal getUOMToStockRatio() { return Optional.ofNullable(uomQty) .map(uomQuantity -> { if (uomQuantity.isZero() || stockQty.isZero()) { return BigDecimal.ZERO; } final UOMPrecision uomPrecision = UOMPrecision.ofInt(uomQuantity.getUOM().getStdPrecision()); return uomQuantity.toBigDecimal().setScale(uomPrecision.toInt(), uomPrecision.getRoundingMode()) .divide(stockQty.toBigDecimal(), uomPrecision.getRoundingMode()); }) .orElse(null); } @NonNull public static StockQtyAndUOMQty toZeroIfNegative(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() < 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty;
} @NonNull public static StockQtyAndUOMQty toZeroIfPositive(@NonNull final StockQtyAndUOMQty stockQtyAndUOMQty) { return stockQtyAndUOMQty.signum() > 0 ? stockQtyAndUOMQty.toZero() : stockQtyAndUOMQty; } public Quantity getQtyInUOM(@NonNull final UomId uomId, @NonNull final QuantityUOMConverter converter) { if (uomQty != null) { if (UomId.equals(uomQty.getUomId(), uomId)) { return uomQty; } else if (UomId.equals(uomQty.getSourceUomId(), uomId)) { return uomQty.switchToSource(); } } if (UomId.equals(stockQty.getUomId(), uomId)) { return stockQty; } else if (UomId.equals(stockQty.getSourceUomId(), uomId)) { return stockQty.switchToSource(); } return converter.convertQuantityTo(stockQty, productId, uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\StockQtyAndUOMQty.java
1
请完成以下Java代码
public List<SondertagBestellfenster> getBestellfenster() { if (bestellfenster == null) { bestellfenster = new ArrayList<SondertagBestellfenster>(); } return this.bestellfenster; } /** * Gets the value of the datum property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDatum() {
return datum; } /** * Sets the value of the datum property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDatum(XMLGregorianCalendar value) { this.datum = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\TypSondertag.java
1
请完成以下Java代码
public I_C_Flatrate_Term getC_Flatrate_Term() { if (_flatrateTerm == null) { _flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID()); // shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term. Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking); } return _flatrateTerm; } @Override public String getInvoiceRule() { if (!_invoiceRuleSet) { // // Try getting the InvoiceRule from Flatrate Term final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term(); final String invoiceRule = flatrateTerm
.getC_Flatrate_Conditions() .getInvoiceRule(); Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking); _invoiceRule = invoiceRule; _invoiceRuleSet = true; } return _invoiceRule; } /* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion) { _priceListVersion = priceListVersion; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final BookNaturalRepository bookNaturalRepository; private final BookRepository bookRepository; public BookstoreService(BookNaturalRepository bookNaturalRepository, BookRepository bookRepository) { this.bookNaturalRepository = bookNaturalRepository; this.bookRepository = bookRepository; } @Transactional public void persistTwoBooks() { Book ar = new Book(); ar.setIsbn("001-AR"); ar.setTitle("Ancient Rome"); ar.setPrice(25); // ar.setSku(1L); Book rh = new Book(); rh.setIsbn("001-RH"); rh.setTitle("Rush Hour"); rh.setPrice(31); // rh.setSku(2L); bookRepository.save(ar); bookRepository.save(rh); }
public Book fetchFirstBookByNaturalId() { // find the first book by a single natural id Optional<Book> foundArBook = bookNaturalRepository.findBySimpleNaturalId("001-AR"); // find first book by two natural ids (for running this code simply // uncomment the "sku" field in the Book entity and the below lines; comment lines 44 and 45) // Map<String, Object> ids = new HashMap<>(); // ids.put("sku", 1L); // ids.put("isbn", "001-AR"); // Optional<Book> foundArBook = bookNaturalRepository.findByNaturalId(ids); return foundArBook.orElseThrow(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalId\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getQueryTimeout() { return this.queryTimeout; } public void setQueryTimeout(@Nullable Duration queryTimeout) { this.queryTimeout = queryTimeout; } public boolean isSkipResultsProcessing() { return this.skipResultsProcessing; } public void setSkipResultsProcessing(boolean skipResultsProcessing) { this.skipResultsProcessing = skipResultsProcessing; } public boolean isSkipUndeclaredResults() { return this.skipUndeclaredResults; }
public void setSkipUndeclaredResults(boolean skipUndeclaredResults) { this.skipUndeclaredResults = skipUndeclaredResults; } public boolean isResultsMapCaseInsensitive() { return this.resultsMapCaseInsensitive; } public void setResultsMapCaseInsensitive(boolean resultsMapCaseInsensitive) { this.resultsMapCaseInsensitive = resultsMapCaseInsensitive; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\JdbcProperties.java
2
请完成以下Java代码
public Set<String> getAlternativeNamespaces(String actualNs) { return actualNsToAlternative.get(actualNs); } @Override public String getAlternativeNamespace(String actualNs) { Set<String> alternatives = getAlternativeNamespaces(actualNs); if (alternatives == null || alternatives.size() == 0) { return null; } else if (alternatives.size() == 1) { return alternatives.iterator().next(); } else { throw new ModelException("There is more than one alternative namespace registered"); } } public String getActualNamespace(String alternativeNs) { return alternativeNsToActual.get(alternativeNs); } public Collection<ModelElementType> getTypes() { return new ArrayList<ModelElementType>(typesByName.values()); } public ModelElementType getType(Class<? extends ModelElementInstance> instanceClass) { return typesByClass.get(instanceClass); } public ModelElementType getTypeForName(String typeName) { return getTypeForName(null, typeName); } public ModelElementType getTypeForName(String namespaceUri, String typeName) { return typesByName.get(ModelUtil.getQName(namespaceUri, typeName)); } /** * Registers a {@link ModelElementType} in this {@link Model}. * * @param modelElementType the element type to register * @param instanceType the instance class of the type to register */ public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) { QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName()); typesByName.put(qName, modelElementType); typesByClass.put(instanceType, modelElementType); }
public String getModelName() { return modelName; } @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((modelName == null) ? 0 : modelName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ModelImpl other = (ModelImpl) obj; if (modelName == null) { if (other.modelName != null) { return false; } } else if (!modelName.equals(other.modelName)) { return false; } return true; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected TbResource deepCopy(TbResource resource) { return new TbResource(resource); } @Override protected void cleanupForComparison(TbResource resource) { super.cleanupForComparison(resource); resource.setSearchText(null); if (resource.getDescriptor() != null && resource.getDescriptor().isNull()) { resource.setDescriptor(null); } } @Override protected TbResource saveOrUpdate(EntitiesImportCtx ctx, TbResource resource, EntityExportData<TbResource> exportData, IdProvider idProvider, CompareResult compareResult) { if (resource.getResourceType() == ResourceType.IMAGE) { return new TbResource(imageService.saveImage(resource)); } else { if (compareResult.isExternalIdChangedOnly()) { resource = resourceService.saveResource(resource, false); } else {
resource = resourceService.saveResource(resource); } resource.setData(null); resource.setPreview(null); return resource; } } @Override protected void onEntitySaved(User user, TbResource savedResource, TbResource oldResource) throws ThingsboardException { super.onEntitySaved(user, savedResource, oldResource); clusterService.onResourceChange(savedResource, null); } @Override public EntityType getEntityType() { return EntityType.TB_RESOURCE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\ResourceImportService.java
2
请在Spring Boot框架中完成以下Java代码
public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getFeeType() { return feeType; } public void setFeeType(String feeType) { this.feeType = feeType; } public Integer getTotalFee() { return totalFee; } public void setTotalFee(Integer totalFee) { this.totalFee = totalFee; } public String getSpbillCreateIp() { return spbillCreateIp; } public void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl;
} public WeiXinTradeTypeEnum getTradeType() { return tradeType; } public void setTradeType(WeiXinTradeTypeEnum tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } public void setLimitPay(String limitPay) { this.limitPay = limitPay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java
2
请完成以下Java代码
public int getCS_Creditpass_Config_PaymentRule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_Config_PaymentRule_ID); if (ii == null) { return 0; } return ii.intValue(); } /** Set Zahlungsart ID. @param CS_Creditpass_Config_PaymentRule_ID Zahlungsart ID */ @Override public void setCS_Creditpass_Config_PaymentRule_ID (int CS_Creditpass_Config_PaymentRule_ID) { if (CS_Creditpass_Config_PaymentRule_ID < 1) { set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_PaymentRule_ID, null); } else { set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_PaymentRule_ID, Integer.valueOf(CS_Creditpass_Config_PaymentRule_ID)); } } // /** // * PaymentRule AD_Reference_ID=195 // * Reference name: _Payment Rule // */ // public static final int PAYMENTRULE_AD_Reference_ID=195; // /** Cash = B */ // public static final String PAYMENTRULE_Cash = "B"; // /** CreditCard = K */ // public static final String PAYMENTRULE_CreditCard = "K"; // /** DirectDeposit = T */ // public static final String PAYMENTRULE_DirectDeposit = "T"; // /** Check = S */ // public static final String PAYMENTRULE_Check = "S"; // /** OnCredit = P */ // public static final String PAYMENTRULE_OnCredit = "P"; // /** DirectDebit = D */ // public static final String PAYMENTRULE_DirectDebit = "D"; // /** Mixed = M */ // public static final String PAYMENTRULE_Mixed = "M"; /** Set Zahlungsweise. @param PaymentRule Wie die Rechnung bezahlt wird */ @Override public void setPaymentRule (java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } /** Get Zahlungsweise. @return Wie die Rechnung bezahlt wird */ @Override
public java.lang.String getPaymentRule () { return (java.lang.String)get_Value(COLUMNNAME_PaymentRule); } /** Set Kaufstyp. @param PurchaseType Kaufstyp */ @Override public void setPurchaseType (java.math.BigDecimal PurchaseType) { set_Value (COLUMNNAME_PurchaseType, PurchaseType); } /** Get Kaufstyp. @return Kaufstyp */ @Override public java.math.BigDecimal getPurchaseType () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PurchaseType); if (bd == null) { return BigDecimal.ZERO; } return bd; } /** Get Preis per Überprüfung. @return Preis per Überprüfung */ @Override public java.math.BigDecimal getRequestPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RequestPrice); if (bd == null) { return BigDecimal.ZERO; } return bd; } /** Set Preis per Überprüfung. @param RequestPrice Preis per Überprüfung */ @Override public void setRequestPrice (java.math.BigDecimal RequestPrice) { set_Value (COLUMNNAME_RequestPrice, RequestPrice); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config_PaymentRule.java
1
请完成以下Java代码
public class DataEntryDetailsRow implements IViewRow { public static final String FIELD_Department = I_C_Flatrate_DataEntry_Detail.COLUMNNAME_C_BPartner_Department_ID; @ViewColumn(seqNo = 10, fieldName = FIELD_Department, captionKey = FIELD_Department, widgetType = DocumentFieldWidgetType.Lookup, editor = ViewEditorRenderMode.NEVER) @Getter private final LookupValue department; public static final String FIELD_ASI = I_C_Flatrate_DataEntry_Detail.COLUMNNAME_M_AttributeSetInstance_ID; @ViewColumn(seqNo = 20, fieldName = FIELD_ASI, captionKey = FIELD_ASI, widgetType = DocumentFieldWidgetType.ProductAttributes, editor = ViewEditorRenderMode.NEVER) @Getter private final ProductASIDescription asi; /** I don't know how to make the field read-only if the entry is processed */ public static final String FIELD_Qty = I_C_Flatrate_DataEntry_Detail.COLUMNNAME_Qty_Reported; @ViewColumn(seqNo = 30, fieldName = FIELD_Qty, captionKey = FIELD_Qty, widgetType = DocumentFieldWidgetType.Quantity, editor = ViewEditorRenderMode.ALWAYS) @Getter private final BigDecimal qty; public static final String FIELD_UOM = I_C_Flatrate_DataEntry_Detail.COLUMNNAME_C_UOM_ID; @ViewColumn(seqNo = 60, fieldName = FIELD_UOM, captionKey = FIELD_UOM, widgetType = DocumentFieldWidgetType.Lookup, editor = ViewEditorRenderMode.NEVER) private final LookupValue uom; @Getter private final DocumentId id; private final boolean processed; private final ViewRowFieldNameAndJsonValuesHolder<DataEntryDetailsRow> values; private static final ImmutableMap<String, ViewEditorRenderMode> EDITOR_RENDER_MODES = ImmutableMap.<String, ViewEditorRenderMode> builder() .put(FIELD_Qty, ViewEditorRenderMode.ALWAYS) .build(); @Builder(toBuilder = true) public DataEntryDetailsRow( final boolean processed, @NonNull final ProductASIDescription asi, @Nullable final LookupValue department, @NonNull final DocumentId id, @Nullable final BigDecimal qty, @NonNull final LookupValue uom) { this.processed = processed; this.asi = asi; this.department = department; this.id = id; this.qty = qty; this.uom = uom; this.values = ViewRowFieldNameAndJsonValuesHolder.builder(DataEntryDetailsRow.class) .viewEditorRenderModeByFieldName(EDITOR_RENDER_MODES) .build(); }
@Override public boolean isProcessed() { return processed; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\model\DataEntryDetailsRow.java
1
请完成以下Java代码
public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Letzter Wareneingang. @param LastReceiptDate Letzter Wareneingang */ @Override public void setLastReceiptDate (java.sql.Timestamp LastReceiptDate) { set_ValueNoCheck (COLUMNNAME_LastReceiptDate, LastReceiptDate); } /** Get Letzter Wareneingang. @return Letzter Wareneingang */ @Override public java.sql.Timestamp getLastReceiptDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_LastReceiptDate); } /** Set Letzte Lieferung. @param LastShipDate Letzte Lieferung */ @Override public void setLastShipDate (java.sql.Timestamp LastShipDate) { set_ValueNoCheck (COLUMNNAME_LastShipDate, LastShipDate); } /** Get Letzte Lieferung.
@return Letzte Lieferung */ @Override public java.sql.Timestamp getLastShipDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_InOut_Online_v.java
1
请完成以下Java代码
private BeanProperty get(String name) { return this.properties.get(name); } private Class<?> getType() { return type; } } abstract static class BeanProperty { private final Class<?> type; private final Class<?> owner; private Method read; private Method write; BeanProperty(Class<?> owner, Class<?> type) { this.owner = owner; this.type = type; } public Class<?> getPropertyType() { return this.type; } public boolean isReadOnly(Object base) { return write(base) == null; } private Method write(Object base) { if (this.write == null) { this.write = Util.getMethod(this.owner, base, getWriteMethod()); } return this.write; } private Method read(Object base) { if (this.read == null) { this.read = Util.getMethod(this.owner, base, getReadMethod()); } return this.read; } abstract Method getWriteMethod(); abstract Method getReadMethod(); abstract String getName(); }
private BeanProperty property(Object base, Object property) { Class<?> type = base.getClass(); String prop = property.toString(); BeanProperties props = this.cache.get(type.getName()); if (props == null || type != props.getType()) { props = BeanSupport.getInstance().getBeanProperties(type); this.cache.put(type.getName(), props); } return props.get(prop); } private static final class ConcurrentCache<K, V> { private final int size; private final Map<K, V> eden; private final Map<K, V> longterm; ConcurrentCache(int size) { this.size = size; this.eden = new ConcurrentHashMap<>(size); this.longterm = new WeakHashMap<>(size); } public V get(K key) { V value = this.eden.get(key); if (value == null) { synchronized (longterm) { value = this.longterm.get(key); } if (value != null) { this.eden.put(key, value); } } return value; } public void put(K key, V value) { if (this.eden.size() >= this.size) { synchronized (longterm) { this.longterm.putAll(this.eden); } this.eden.clear(); } this.eden.put(key, value); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanELResolver.java
1
请在Spring Boot框架中完成以下Java代码
public DmnDeploymentResponse uploadDeployment(@ApiParam(name = "tenantId") @RequestParam(value = "tenantId", required = false) String tenantId, HttpServletRequest request) { if (!(request instanceof MultipartHttpServletRequest)) { throw new FlowableIllegalArgumentException("Multipart request is required"); } if (restApiInterceptor != null) { restApiInterceptor.executeNewDeploymentForTenantId(tenantId); } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; if (multipartRequest.getFileMap().size() == 0) { throw new FlowableIllegalArgumentException("Multipart request with file content is required"); } MultipartFile file = multipartRequest.getFileMap().values().iterator().next(); try { DmnDeploymentBuilder deploymentBuilder = dmnRepositoryService.createDeployment(); String fileName = file.getOriginalFilename(); if (StringUtils.isEmpty(fileName) || !DmnResourceUtil.isDmnResource(fileName)) { fileName = file.getName(); } if (DmnResourceUtil.isDmnResource(fileName)) { try (final InputStream fileInputStream = file.getInputStream()) { deploymentBuilder.addInputStream(fileName, fileInputStream); }
} else { throw new FlowableIllegalArgumentException("File must be of type .dmn"); } deploymentBuilder.name(fileName); if (tenantId != null) { deploymentBuilder.tenantId(tenantId); } if (restApiInterceptor != null) { restApiInterceptor.enhanceDeployment(deploymentBuilder); } DmnDeployment deployment = deploymentBuilder.deploy(); return dmnRestResponseFactory.createDmnDeploymentResponse(deployment); } catch (Exception e) { if (e instanceof FlowableException) { throw (FlowableException) e; } throw new FlowableException(e.getMessage(), e); } } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DmnDeploymentCollectionResource.java
2
请完成以下Java代码
public java.lang.String getTargetFieldName() { return get_ValueAsString(COLUMNNAME_TargetFieldName); } /** * TargetFieldType AD_Reference_ID=541611 * Reference name: AttributeTypeList */ public static final int TARGETFIELDTYPE_AD_Reference_ID=541611; /** textArea = textArea */ public static final String TARGETFIELDTYPE_TextArea = "textArea"; /** EAN13 = EAN13 */ public static final String TARGETFIELDTYPE_EAN13 = "EAN13"; /** EAN128 = EAN128 */ public static final String TARGETFIELDTYPE_EAN128 = "EAN128"; /** numberField = numberField */ public static final String TARGETFIELDTYPE_NumberField = "numberField"; /** date = date */ public static final String TARGETFIELDTYPE_Date = "date";
/** unitChar = unitChar */ public static final String TARGETFIELDTYPE_UnitChar = "unitChar"; /** graphic = graphic */ public static final String TARGETFIELDTYPE_Graphic = "graphic"; @Override public void setTargetFieldType (final java.lang.String TargetFieldType) { set_Value (COLUMNNAME_TargetFieldType, TargetFieldType); } @Override public java.lang.String getTargetFieldType() { return get_ValueAsString(COLUMNNAME_TargetFieldType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java
1
请完成以下Java代码
public static ProcessEngineDetails parseProcessEngineVersion(boolean trimSuffixEE) { String version = ProductPropertiesUtil.getProductVersion(); return parseProcessEngineVersion(version, trimSuffixEE); } public static ProcessEngineDetails parseProcessEngineVersion(String version, boolean trimSuffixEE) { String edition = ProcessEngineDetails.EDITION_COMMUNITY; if (version.contains("-ee")) { edition = ProcessEngineDetails.EDITION_ENTERPRISE; if (trimSuffixEE) { version = version.replace("-ee", ""); // trim `-ee` suffix } } return new ProcessEngineDetails(version, edition); } public static String parseServerVendor(String applicationServerInfo) { String serverVendor = ""; Pattern pattern = Pattern.compile("[\\sA-Za-z]+"); Matcher matcher = pattern.matcher(applicationServerInfo); if (matcher.find()) { try { serverVendor = matcher.group(); } catch (IllegalStateException ignored) { } serverVendor = serverVendor.trim(); if (serverVendor.contains("WildFly")) { return "WildFly"; }
} return serverVendor; } public static JdkImpl parseJdkDetails() { String jdkVendor = System.getProperty("java.vm.vendor"); if (jdkVendor != null && jdkVendor.contains("Oracle") && System.getProperty("java.vm.name").contains("OpenJDK")) { jdkVendor = "OpenJDK"; } String jdkVersion = System.getProperty("java.version"); JdkImpl jdk = new JdkImpl(jdkVersion, jdkVendor); return jdk; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ParseUtil.java
1
请完成以下Java代码
public void setAD_Column_ID (final int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID); } @Override public int getAD_Column_ID() { return get_ValueAsInt(COLUMNNAME_AD_Column_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 setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID) { if (WEBUI_Board_CardField_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID); } @Override public int getWEBUI_Board_CardField_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID);
} @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java
1
请完成以下Java代码
public List<EnableActivityContainer> getEnableActivityContainers() { return enableActivityContainers; } public ProcessInstanceChangeState setEnableActivityContainers(List<EnableActivityContainer> enableActivityContainers) { this.enableActivityContainers = enableActivityContainers; return this; } public List<MoveExecutionEntityContainer> getMoveExecutionEntityContainers() { return moveExecutionEntityContainers; } public ProcessInstanceChangeState setMoveExecutionEntityContainers(List<MoveExecutionEntityContainer> moveExecutionEntityContainers) { this.moveExecutionEntityContainers = moveExecutionEntityContainers; return this; } public HashMap<String, ExecutionEntity> getCreatedEmbeddedSubProcesses() { return createdEmbeddedSubProcess; } public Optional<ExecutionEntity> getCreatedEmbeddedSubProcessByKey(String key) { return Optional.ofNullable(createdEmbeddedSubProcess.get(key)); } public void addCreatedEmbeddedSubProcess(String key, ExecutionEntity executionEntity) { this.createdEmbeddedSubProcess.put(key, executionEntity); } public HashMap<String, ExecutionEntity> getCreatedMultiInstanceRootExecution() { return createdMultiInstanceRootExecution; } public void setCreatedMultiInstanceRootExecution(HashMap<String, ExecutionEntity> createdMultiInstanceRootExecution) { this.createdMultiInstanceRootExecution = createdMultiInstanceRootExecution; }
public void addCreatedMultiInstanceRootExecution(String key, ExecutionEntity executionEntity) { this.createdMultiInstanceRootExecution.put(key, executionEntity); } public Map<String, List<ExecutionEntity>> getProcessInstanceActiveEmbeddedExecutions() { return processInstanceActiveEmbeddedExecutions; } public ProcessInstanceChangeState setProcessInstanceActiveEmbeddedExecutions(Map<String, List<ExecutionEntity>> processInstanceActiveEmbeddedExecutions) { this.processInstanceActiveEmbeddedExecutions = processInstanceActiveEmbeddedExecutions; return this; } public HashMap<StartEvent, ExecutionEntity> getPendingEventSubProcessesStartEvents() { return pendingEventSubProcessesStartEvents; } public void addPendingEventSubProcessStartEvent(StartEvent startEvent, ExecutionEntity eventSubProcessParent) { this.pendingEventSubProcessesStartEvents.put(startEvent, eventSubProcessParent); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\ProcessInstanceChangeState.java
1
请完成以下Java代码
public boolean hasListener(final IHUTrxListener listener) { return listeners.contains(listener); } public List<IHUTrxListener> asList() { return new ArrayList<>(listeners); } public CompositeHUTrxListener copy() { final CompositeHUTrxListener copy = new CompositeHUTrxListener(); copy.listeners.addAll(listeners); return copy; } @Override public void trxLineProcessed(final IHUContext huContext, final I_M_HU_Trx_Line trxLine) { for (final IHUTrxListener listener : listeners) { listener.trxLineProcessed(huContext, trxLine); } } @Override public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { for (final IHUTrxListener listener : listeners) { listener.huParentChanged(hu, parentHUItemOld); } } @Override public void afterTrxProcessed(final IReference<I_M_HU_Trx_Hdr> trxHdrRef, final List<I_M_HU_Trx_Line> trxLines) { for (final IHUTrxListener listener : listeners) { listener.afterTrxProcessed(trxHdrRef, trxLines); }
} @Override public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } } @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<ProductRequestProducerResult> run() { if(articles.isEmpty()) { return Optional.empty(); } final JsonRequestProductUpsert jsonRequestProductUpsert = JsonRequestProductUpsert.builder() .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .requestItems(getProductItems()) .build(); resultBuilder.jsonRequestProductUpsert(jsonRequestProductUpsert); return Optional.of(resultBuilder.build()); } @NonNull private List<JsonRequestProductUpsertItem> getProductItems() { return articles.stream() .map(this::mapArticleToProductRequestItem) .collect(Collectors.toList()); }
@NonNull private JsonRequestProductUpsertItem mapArticleToProductRequestItem(@NonNull final LineItem article) { final String externalIdentifier = EbayUtils.formatExternalId(article.getSku()); final JsonRequestProduct jsonRequestProduct = new JsonRequestProduct(); jsonRequestProduct.setCode(article.getSku()); jsonRequestProduct.setName(article.getTitle()); jsonRequestProduct.setType(JsonRequestProduct.Type.ITEM); jsonRequestProduct.setUomCode(EbayConstants.DEFAULT_PRODUCT_UOM); return JsonRequestProductUpsertItem.builder() .productIdentifier(externalIdentifier) .requestProduct(jsonRequestProduct) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\product\ProductUpsertRequestProducer.java
2
请完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { /* http .formLogin() .loginPage("/login.html").loginProcessingUrl("/login").permitAll(); http .logout() .logoutUrl("/logout"); http .csrf().disable(); http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .and() .httpBasic(); */
http .authorizeRequests() .antMatchers("/index").permitAll() .antMatchers("/admin/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\9.PosilkaAdmin\src\main\java\posilka\admin\security\PosilkaSecurity.java
1
请完成以下Java代码
public void setMaxWeight(final BigDecimal MaxWeight) { set_Value(COLUMNNAME_MaxWeight, MaxWeight); } @Override public BigDecimal getMaxWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID) { if (M_PackagingContainer_ID < 1) set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null); else set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID); } @Override public int getM_PackagingContainer_ID() { return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID); } @Override public void setM_Product_ID(final int M_Product_ID) { if (M_Product_ID < 1) set_Value(COLUMNNAME_M_Product_ID, null); else set_Value(COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName(final java.lang.String Name)
{ set_Value(COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue(final @Nullable java.lang.String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWidth(final @Nullable BigDecimal Width) { set_Value(COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
public String getName() { return activityName; } public String[] getIncidentIds() { return incidentIds; } public ActivityInstanceIncidentDto[] getIncidents() { return incidents; } public static ActivityInstanceDto fromActivityInstance(ActivityInstance instance) { ActivityInstanceDto result = new ActivityInstanceDto(); result.id = instance.getId(); result.parentActivityInstanceId = instance.getParentActivityInstanceId(); result.activityId = instance.getActivityId(); result.activityType = instance.getActivityType(); result.processInstanceId = instance.getProcessInstanceId(); result.processDefinitionId = instance.getProcessDefinitionId(); result.childActivityInstances = fromListOfActivityInstance(instance.getChildActivityInstances());
result.childTransitionInstances = TransitionInstanceDto.fromListOfTransitionInstance(instance.getChildTransitionInstances()); result.executionIds = instance.getExecutionIds(); result.activityName = instance.getActivityName(); result.incidentIds = instance.getIncidentIds(); result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents()); return result; } public static ActivityInstanceDto[] fromListOfActivityInstance(ActivityInstance[] instances) { ActivityInstanceDto[] result = new ActivityInstanceDto[instances.length]; for (int i = 0; i < result.length; i++) { result[i] = fromActivityInstance(instances[i]); } return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ActivityInstanceDto.java
1
请完成以下Java代码
public class C_Invoice_Fix_DocumentLocations { private final IDocumentLocationBL documentLocationBL = SpringContextHolder.instance.getBean(IDocumentLocationBL.class); protected void doItWithTrxRunner() { final String trxName = Trx.createTrxName("C_Invoice_Fix_DocumentLocations"); final Properties ctx = Env.getCtx(); Trx.get(trxName, true); final ITrxRunConfig trxRunConfig = Services.get(ITrxManager.class).createTrxRunConfig(TrxPropagation.NESTED, OnRunnableSuccess.COMMIT, OnRunnableFail.ASK_RUNNABLE); Services.get(ITrxManager.class).run( trxName, trxRunConfig, trxName1 -> { List<I_C_Invoice> invoicesToFix = retrieveInvoices(ctx, trxName1); int counter = 0; final int commitSize = 100; while (!invoicesToFix.isEmpty()) { for (final I_C_Invoice invoiceToFix : invoicesToFix) { documentLocationBL.updateRenderedAddressAndCapturedLocation(InvoiceDocumentLocationAdapterFactory.locationAdapter(invoiceToFix)); InterfaceWrapperHelper.save(invoiceToFix); counter++; if (counter % commitSize == 0) { Check.assume(Trx.get(trxName1, false).commit(), "Commit of Trx '" + trxName1 + " returns true"); } } invoicesToFix = retrieveInvoices(ctx, trxName1); } }); } private List<I_C_Invoice> retrieveInvoices(final Properties ctx, final String trxName) { return new Query(ctx, I_C_Invoice.Table_Name, "DocStatus='CO' AND COALESCE(BPartnerAddress,'')=''", trxName) .setOnlyActiveRecords(true)
.setLimit(50) // .setOrderBy(I_C_Invoice.COLUMNNAME_C_Invoice_ID) .list(I_C_Invoice.class); } public static void main(String[] args) { AdempiereToolsHelper.getInstance().startupMinimal(); LogManager.setLevel(Level.WARN); C_Invoice_Fix_DocumentLocations process = new C_Invoice_Fix_DocumentLocations(); try { process.doItWithTrxRunner(); } catch (Exception e) { e.printStackTrace(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\C_Invoice_Fix_DocumentLocations.java
1
请完成以下Java代码
public static String readExcel(String filePath) throws IOException { File file = new File(filePath); FileInputStream inputStream = null; StringBuilder toReturn = new StringBuilder(); try { inputStream = new FileInputStream(file); Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream); for (Sheet sheet : baeuldungWorkBook) { toReturn.append("--------------------------------------------------------------------") .append(ENDLINE); toReturn.append("Worksheet :") .append(sheet.getSheetName()) .append(ENDLINE); toReturn.append("--------------------------------------------------------------------") .append(ENDLINE); int firstRow = sheet.getFirstRowNum(); int lastRow = sheet.getLastRowNum(); for (int index = firstRow + 1; index <= lastRow; index++) { Row row = sheet.getRow(index); toReturn.append("|| "); for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) { Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); printCellValue(cell, toReturn); } toReturn.append(" ||") .append(ENDLINE); } } inputStream.close(); baeuldungWorkBook.close(); } catch (IOException e) { throw e; }
return toReturn.toString(); } public static void printCellValue(Cell cell, StringBuilder toReturn) { CellType cellType = cell.getCellType() .equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType(); if (cellType.equals(CellType.STRING)) { toReturn.append(cell.getStringCellValue()) .append(" | "); } if (cellType.equals(CellType.NUMERIC)) { if (DateUtil.isCellDateFormatted(cell)) { toReturn.append(cell.getDateCellValue()) .append(" | "); } else { toReturn.append(cell.getNumericCellValue()) .append(" | "); } } if (cellType.equals(CellType.BOOLEAN)) { toReturn.append(cell.getBooleanCellValue()) .append(" | "); } } }
repos\tutorials-master\apache-poi\src\main\java\com\baeldung\poi\excel\ExcelUtility.java
1
请在Spring Boot框架中完成以下Java代码
public class RabbitMQAuditService { private static final Logger logger = LogManager.getLogger(RabbitMQAuditService.class); public void log(@NonNull final RabbitMQAuditEntry entry) { try { final I_RabbitMQ_Message_Audit record = InterfaceWrapperHelper.newInstance(I_RabbitMQ_Message_Audit.class); record.setRabbitMQ_QueueName(entry.getQueueName()); record.setDirection(entry.getDirection().getCode()); record.setContent(convertContentToString(entry.getContent())); record.setEvent_UUID(entry.getEventUUID()); record.setRelated_Event_UUID(entry.getRelatedEventUUID()); record.setHost(entry.getHost() != null ? entry.getHost().toString() : null); InterfaceWrapperHelper.save(record); } catch (final Exception ex)
{ logger.warn("Failed logging `{}`. Skip logging.", entry, ex); } } private String convertContentToString(final @NonNull Object content) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(content); } catch (final JsonProcessingException e) { logger.warn("Failed converting `{}` to JSON. Returning toString().", content, e); return content.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rabbitmq\RabbitMQAuditService.java
2
请完成以下Java代码
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID) { if (PP_Product_BOMVersions_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID); } @Override public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setPP_Product_Planning_ID (final int PP_Product_Planning_ID) { if (PP_Product_Planning_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_Planning_ID, PP_Product_Planning_ID); } @Override
public int getPP_Product_Planning_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_Planning_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Maturing_Candidates_v.java
1
请完成以下Java代码
public class BpmnDiEdge { protected GraphicInfo sourceDockerInfo; protected GraphicInfo targetDockerInfo; protected List<GraphicInfo> waypoints; public BpmnDiEdge() {} public GraphicInfo getSourceDockerInfo() { return sourceDockerInfo; } public void setSourceDockerInfo(GraphicInfo sourceDockerInfo) { this.sourceDockerInfo = sourceDockerInfo; } public GraphicInfo getTargetDockerInfo() {
return targetDockerInfo; } public void setTargetDockerInfo(GraphicInfo targetDockerInfo) { this.targetDockerInfo = targetDockerInfo; } public List<GraphicInfo> getWaypoints() { return waypoints; } public void setWaypoints(List<GraphicInfo> waypoints) { this.waypoints = waypoints; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\BpmnDiEdge.java
1
请完成以下Java代码
public class DataObjectImpl implements DataObject { protected String id; protected String processInstanceId; protected String executionId; protected String name; protected Object value; protected String description; protected String localizedName; protected String localizedDescription; protected String dataObjectDefinitionKey; private String type; public DataObjectImpl(String id, String processInstanceId, String executionId, String name, Object value, String description, String type, String localizedName, String localizedDescription, String dataObjectDefinitionKey) { this.id = id; this.processInstanceId = processInstanceId; this.executionId = executionId; this.name = name; this.value = value; this.type = type; this.description = description; this.localizedName = localizedName; this.localizedDescription = localizedDescription; this.dataObjectDefinitionKey = dataObjectDefinitionKey; } public void setId(String id) { this.id = id; } @Override public String getId() { return id; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getExecutionId() { return executionId; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getLocalizedName() { if (localizedName != null && localizedName.length() > 0) { return localizedName; } else { return name; } } public void setLocalizedName(String localizedName) { this.localizedName = localizedName; }
@Override public String getDescription() { if (localizedDescription != null && localizedDescription.length() > 0) { return localizedDescription; } else { return description; } } public void setDescription(String description) { this.description = description; } @Override public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } @Override public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String getDataObjectDefinitionKey() { return dataObjectDefinitionKey; } public void setDataObjectDefinitionKey(String dataObjectDefinitionKey) { this.dataObjectDefinitionKey = dataObjectDefinitionKey; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DataObjectImpl.java
1
请完成以下Java代码
public class WEBUI_C_Flatrate_DataEntry_ReactivateIt extends JavaProcess implements IProcessPrecondition { private final IDocumentBL documentBL = Services.get(IDocumentBL.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { final I_C_Flatrate_DataEntry entryRecord = ProcessUtil.extractEntryOrNull(context); if (entryRecord == null) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (!DocStatus.ofCode(entryRecord.getDocStatus()).isCompleted()) {
return ProcessPreconditionsResolution.rejectWithInternalReason("C_Flatrate_DataEntry not completed"); } return ProcessPreconditionsResolution.accept(); } @Override protected final String doIt() { final I_C_Flatrate_DataEntry entryRecord = ProcessUtil.extractEntry(getProcessInfo()); documentBL.processEx(entryRecord, X_C_Flatrate_DataEntry.DOCACTION_Re_Activate, X_C_Flatrate_DataEntry.DOCSTATUS_InProgress); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\process\WEBUI_C_Flatrate_DataEntry_ReactivateIt.java
1
请在Spring Boot框架中完成以下Java代码
public static List toList() { WeiXinTradeTypeEnum[] ary = WeiXinTradeTypeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list; } public static WeiXinTradeTypeEnum getEnum(String name) { WeiXinTradeTypeEnum[] arry = WeiXinTradeTypeEnum.values(); for (int i = 0; i < arry.length; i++) { if (arry[i].name().equalsIgnoreCase(name)) { return arry[i]; } } return null; } /** * 取枚举的json字符串
* * @return */ public static String getJsonStr() { WeiXinTradeTypeEnum[] enums = WeiXinTradeTypeEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (WeiXinTradeTypeEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\weixinpay\WeiXinTradeTypeEnum.java
2
请在Spring Boot框架中完成以下Java代码
public class PaymentTermBreakId implements RepoIdAware { int repoId; @NonNull PaymentTermId paymentTermId; public static PaymentTermBreakId ofRepoId(@NonNull final PaymentTermId paymentTermId, final int paymentTermBreakId) { return new PaymentTermBreakId(paymentTermId, paymentTermBreakId); } public static PaymentTermBreakId ofRepoId(final int paymentTermId, final int paymentTermBreakId) { return new PaymentTermBreakId(PaymentTermId.ofRepoId(paymentTermId), paymentTermBreakId); } @Nullable public static PaymentTermBreakId ofRepoIdOrNull( @Nullable final Integer paymentTermId, @Nullable final Integer paymentTermBreakId) { return paymentTermId != null && paymentTermId > 0 && paymentTermBreakId != null && paymentTermBreakId > 0 ? ofRepoId(paymentTermId, paymentTermBreakId) : null; } public static Optional<PaymentTermBreakId> optionalOfRepoId( @Nullable final Integer paymentTermId, @Nullable final Integer paymentTermBreakId) { return Optional.ofNullable(ofRepoIdOrNull(paymentTermId, paymentTermBreakId)); } @Nullable
public static PaymentTermBreakId ofRepoIdOrNull( @Nullable final PaymentTermId paymentTermId, @Nullable final Integer paymentTermBreakId) { return paymentTermId != null && paymentTermBreakId != null && paymentTermBreakId > 0 ? ofRepoId(paymentTermId, paymentTermBreakId) : null; } @Jacksonized @Builder private PaymentTermBreakId(@NonNull final PaymentTermId paymentTermId, final int repoId) { this.paymentTermId = paymentTermId; this.repoId = Check.assumeGreaterThanZero(repoId, "C_PaymentTerm_Break_ID"); } public static int toRepoId(@Nullable final PaymentTermBreakId paymentTermBreakId) { return paymentTermBreakId != null ? paymentTermBreakId.getRepoId() : -1; } public static boolean equals(final @Nullable PaymentTermBreakId id1, final @Nullable PaymentTermBreakId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\paymentterm\PaymentTermBreakId.java
2
请完成以下Java代码
public GroupMatcher createPredicate( final de.metas.order.model.I_C_CompensationGroup_SchemaLine schemaLine, final List<de.metas.order.model.I_C_CompensationGroup_SchemaLine> allSchemaLines) { final ConditionsId contractConditionsId = ConditionsId.ofRepoIdOrNull(schemaLine.getC_Flatrate_Conditions_ID()); if (contractConditionsId == null) { throw new AdempiereException("Schema line does not have contract conditions set: " + schemaLine); } return new ContractConditionsGroupMatcher(contractConditionsId); } @ToString @AllArgsConstructor private static final class ContractConditionsGroupMatcher implements GroupMatcher { private final ConditionsId contractConditionsId; @Override public boolean isMatching(@NonNull final Group group)
{ return Objects.equals(contractConditionsId, group.getContractConditionsId()); // if i just this instead: // // return ConditionsId.equals(contractConditionsId, group.getContractConditionsId()); // // then i get this build error in intellij // /home/tobi/work-metas_2/metasfresh/backend/de.metas.contracts/src/main/java/de/metas/contracts/compensationGroup/ContractsCompensationGroupAdvisor.java:111:32 // java: no suitable method found for equals(de.metas.contracts.ConditionsId,de.metas.contracts.ConditionsId) // method java.lang.Object.equals(java.lang.Object) is not applicable // (actual and formal argument lists differ in length) // method de.metas.contracts.ConditionsId.equals(java.lang.Object) is not applicable // (actual and formal argument lists differ in length) } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\compensationGroup\ContractsCompensationGroupAdvisor.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() // // View info .add("viewId", viewId) .add("profileId", profileId) .add("filters", filters) .add("orderBys", orderBys) // // Page info .add("firstRow", firstRow) .add("pageLength", pageLength) .add("page", page) // .toString(); } @Nullable public String getViewDescription(final String adLanguage) { if (viewDescription == null) { return null; } final String viewDescriptionStr = viewDescription.translate(adLanguage); return !Check.isBlank(viewDescriptionStr) ? viewDescriptionStr : null; } public boolean isPageLoaded() { return page != null; }
public List<DocumentId> getRowIds() { if (rowIds != null) { return rowIds; } return getPage().stream().map(IViewRow::getId).collect(ImmutableList.toImmutableList()); } public boolean isEmpty() { return getPage().isEmpty(); } /** * @return loaded page * @throws IllegalStateException if the page is not loaded, see {@link #isPageLoaded()} */ public List<IViewRow> getPage() { if (page == null) { throw new IllegalStateException("page not loaded for " + this); } return page; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewResult.java
1
请完成以下Java代码
public I_C_Flatrate_DataEntry retrieveFlatrateDataEntry( @NonNull final de.metas.contracts.model.I_C_Flatrate_Term flatrateTerm, @NonNull final Timestamp date) { final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); final List<I_C_Flatrate_DataEntry> dataEntries = InterfaceWrapperHelper.createList( flatrateDAO.retrieveDataEntries(flatrateTerm, date, I_C_Flatrate_DataEntry.TYPE_Procurement_PeriodBased, true), // onlyNonSim = true I_C_Flatrate_DataEntry.class); for (final I_C_Flatrate_DataEntry dataEntry : dataEntries) { if (dataEntry.getM_Product_DataEntry_ID() == flatrateTerm.getM_Product_ID()) { return dataEntry; } } return null;
} @Nullable @Override public I_C_Flatrate_Term retrieveTermForPartnerAndProduct(final Date date, final int bPartnerID, final int pmmProductId) { return retrieveAllRunningContractsOnDateQuery(date) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_DropShip_BPartner_ID, bPartnerID) .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_PMM_Product_ID, pmmProductId) .addCompareFilter(I_C_Flatrate_Term.COLUMNNAME_StartDate, Operator.LESS_OR_EQUAL, date) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate, Direction.Descending, Nulls.Last) .endOrderBy() .create() .first(I_C_Flatrate_Term.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMContractsDAO.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getExchangeRate() { return exchangeRate; } /** * Sets the value of the exchangeRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setExchangeRate(BigDecimal value) { this.exchangeRate = value; } /** * Gets the value of the exchangeDate property. * * @return * possible object is * {@link XMLGregorianCalendar } *
*/ public XMLGregorianCalendar getExchangeDate() { return exchangeDate; } /** * Sets the value of the exchangeDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setExchangeDate(XMLGregorianCalendar value) { this.exchangeDate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\TargetCurrencyType.java
2
请在Spring Boot框架中完成以下Java代码
public Collection<Class<? extends PurchaseCandidateCreatedEvent>> getHandledEventType() { return ImmutableList.of(PurchaseCandidateCreatedEvent.class); } @Override public void validateEvent(@NonNull final PurchaseCandidateCreatedEvent event) { // nothing to do; the event was already validated on construction time } @Override public void handleEvent(@NonNull final PurchaseCandidateCreatedEvent event) { handlePurchaseCandidateEvent(event); } @Override protected CandidatesQuery createCandidatesQuery(@NonNull final PurchaseCandidateEvent eventt) { final PurchaseCandidateCreatedEvent event = (PurchaseCandidateCreatedEvent)eventt; if (event.getSupplyCandidateRepoId() <= 0) {
return CandidatesQuery.FALSE; } return CandidatesQuery.fromId(CandidateId.ofRepoId(event.getSupplyCandidateRepoId())); } @Override protected CandidateBuilder updateBuilderFromEvent( @NonNull final CandidateBuilder candidateBuilder, @NonNull final PurchaseCandidateEvent event) { final PurchaseCandidateCreatedEvent createdEvent = PurchaseCandidateCreatedEvent.cast(event); final SupplyRequiredDescriptor supplyRequiredDescriptor = createdEvent.getSupplyRequiredDescriptor(); final DemandDetail demandDetail = DemandDetail.forSupplyRequiredDescriptorOrNull(supplyRequiredDescriptor); return candidateBuilder.additionalDemandDetail(demandDetail); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateCreatedHandler.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isSkipCheckingPriceListSOTrxFlag() { return skipCheckingPriceListSOTrxFlag; } /** If set to not-{@code null}, then the {@link de.metas.pricing.rules.Discount} rule with go with this break as opposed to look for the currently matching break. */ @Override public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak) { this.forcePricingConditionsBreak = forcePricingConditionsBreak; return this; } @Override public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware() { final Object referencedObj = getReferencedObject(); if (referencedObj == null) { return Optional.empty(); } final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class); final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj); return Optional.ofNullable(asiAware); } @Override public Quantity getQuantity() { final BigDecimal ctxQty = getQty();
if (ctxQty == null) { return null; } final UomId ctxUomId = getUomId(); if (ctxUomId == null) { return null; } return Quantitys.of(ctxQty, ctxUomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
2
请完成以下Java代码
public class MobileApplicationPermission { @NonNull @Getter MobileApplicationRepoId mobileApplicationId; @NonNull @Getter MobileApplicationResource resource; @Getter boolean allowAccess; boolean allowAllActions; @NonNull ImmutableSet<MobileApplicationActionId> allowedActionIds; @Builder(toBuilder = true) private MobileApplicationPermission( @NonNull final MobileApplicationRepoId mobileApplicationId, final boolean allowAccess, final boolean allowAllActions, @NonNull final Set<MobileApplicationActionId> allowedActionIds) { this.mobileApplicationId = mobileApplicationId; this.allowAccess = allowAccess; this.resource = MobileApplicationResource.of(mobileApplicationId); this.allowAllActions = allowAllActions; this.allowedActionIds = ImmutableSet.copyOf(allowedActionIds); } public static MobileApplicationPermission cast(@NonNull final Permission permission) { return (MobileApplicationPermission)permission; } public MobileApplicationPermission mergeFrom(@NonNull final MobileApplicationPermission from) { if (!Objects.equals(this.mobileApplicationId, from.mobileApplicationId)) { throw new AdempiereException("Cannot merge permissions for different mobile applications: " + this + ", " + from); } return toBuilder() .allowAccess(this.allowAccess || from.allowAccess) .allowAllActions(this.allowAllActions || from.allowAllActions) .allowedActionIds(Sets.union(this.allowedActionIds, from.allowedActionIds)) .build(); } @NonNull public static MobileApplicationPermission merge( @Nullable final MobileApplicationPermission existingPermission, @NonNull final MobileApplicationPermission permission, @NonNull final PermissionsBuilder.CollisionPolicy collisionPolicy) { if (existingPermission == null)
{ return permission; } final boolean samePermissionAlreadyExists = Objects.equals(existingPermission, permission); if (collisionPolicy == PermissionsBuilder.CollisionPolicy.Override) { return permission; } else if (collisionPolicy == PermissionsBuilder.CollisionPolicy.Merge) { if (!samePermissionAlreadyExists) { return existingPermission.mergeFrom(permission); } else { return existingPermission; } } else if (collisionPolicy == PermissionsBuilder.CollisionPolicy.Fail) { if (!samePermissionAlreadyExists) { throw new AdempiereException("Found another permission for same resource but with different accesses: " + existingPermission + ", " + permission); } // NOTE: if they are equals, do nothing return existingPermission; } else if (collisionPolicy == PermissionsBuilder.CollisionPolicy.Skip) { return existingPermission; } else { throw new AdempiereException("Unknown CollisionPolicy: " + collisionPolicy); } } public boolean isAllowAction(@NonNull final MobileApplicationActionId actionId) { if (!allowAccess) {return false;} return allowAllActions || allowedActionIds.contains(actionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermission.java
1
请完成以下Java代码
public void setM_PropertiesConfig_ID (int M_PropertiesConfig_ID) { if (M_PropertiesConfig_ID < 1) set_Value (COLUMNNAME_M_PropertiesConfig_ID, null); else set_Value (COLUMNNAME_M_PropertiesConfig_ID, Integer.valueOf(M_PropertiesConfig_ID)); } /** Get Properties Configuration. @return Properties Configuration */ @Override public int getM_PropertiesConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Properties Configuration Line. @param M_PropertiesConfig_Line_ID Properties Configuration Line */ @Override public void setM_PropertiesConfig_Line_ID (int M_PropertiesConfig_Line_ID) { if (M_PropertiesConfig_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_Line_ID, Integer.valueOf(M_PropertiesConfig_Line_ID)); } /** Get Properties Configuration Line. @return Properties Configuration Line */ @Override public int getM_PropertiesConfig_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig_Line.java
1
请完成以下Java代码
public Flux<DataBuffer> getBody() { return outputMessage.getBody(); } }; } public static class Config { private @Nullable ParameterizedTypeReference inClass; private @Nullable ParameterizedTypeReference outClass; private @Nullable String contentType; private @Nullable RewriteFunction rewriteFunction; public @Nullable ParameterizedTypeReference getInClass() { return inClass; } public Config setInClass(Class inClass) { return setInClass(ParameterizedTypeReference.forType(inClass)); } public Config setInClass(ParameterizedTypeReference inTypeReference) { this.inClass = inTypeReference; return this; } public @Nullable ParameterizedTypeReference getOutClass() { return outClass; } public Config setOutClass(Class outClass) { return setOutClass(ParameterizedTypeReference.forType(outClass)); } public Config setOutClass(ParameterizedTypeReference outClass) { this.outClass = outClass;
return this; } public @Nullable RewriteFunction getRewriteFunction() { return rewriteFunction; } public Config setRewriteFunction(RewriteFunction rewriteFunction) { this.rewriteFunction = rewriteFunction; return this; } public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass, RewriteFunction<T, R> rewriteFunction) { setInClass(inClass); setOutClass(outClass); setRewriteFunction(rewriteFunction); return this; } public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass, ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) { setInClass(inClass); setOutClass(outClass); setRewriteFunction(rewriteFunction); return this; } public @Nullable String getContentType() { return contentType; } public Config setContentType(@Nullable String contentType) { this.contentType = contentType; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyRequestBodyGatewayFilterFactory.java
1
请完成以下Java代码
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info(String.format(" Jeecg-Boot 发送消息任务 SendMsgJob ! 时间:" + DateUtils.getTimestamp())); // 1.读取消息中心数据,只查询未发送的和发送失败不超过次数的 QueryWrapper<SysMessage> queryWrapper = new QueryWrapper<SysMessage>(); queryWrapper.eq("es_send_status", SendMsgStatusEnum.WAIT.getCode()) .or(i -> i.eq("es_send_status", SendMsgStatusEnum.FAIL.getCode()).lt("es_send_num", 6)); List<SysMessage> sysMessages = sysMessageService.list(queryWrapper); System.out.println(sysMessages); // 2.根据不同的类型走不通的发送实现类 for (SysMessage sysMessage : sysMessages) { // 代码逻辑说明: 模板消息发送测试调用方法修改 Integer sendNum = sysMessage.getEsSendNum(); try { MessageDTO md = new MessageDTO(); md.setTitle(sysMessage.getEsTitle()); md.setContent(sysMessage.getEsContent()); md.setToUser(sysMessage.getEsReceiver()); md.setType(sysMessage.getEsType());
md.setToAll(false); // 代码逻辑说明: 【QQYUN-8523】敲敲云发邮件通知,不稳定--- md.setIsTimeJob(true); sysBaseAPI.sendTemplateMessage(md); //发送消息成功 sysMessage.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode()); } catch (Exception e) { e.printStackTrace(); // 发送消息出现异常 sysMessage.setEsSendStatus(SendMsgStatusEnum.FAIL.getCode()); } sysMessage.setEsSendNum(++sendNum); // 发送结果回写到数据库 sysMessageService.updateById(sysMessage); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\job\SendMsgJob.java
1
请完成以下Java代码
public void setQty (BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Resource Assignment. @param S_ResourceAssignment_ID Resource Assignment */ public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID) { if (S_ResourceAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID)); } /** Get Resource Assignment. @return Resource Assignment */ public int getS_ResourceAssignment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Resource getS_Resource() throws RuntimeException { return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name) .getPO(getS_Resource_ID(), get_TrxName()); } /** Set Resource. @param S_Resource_ID
Resource */ public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Resource. @return Resource */ public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceAssignment.java
1
请完成以下Java代码
public AlarmComment findAlarmCommentById(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return DaoUtil.getData(alarmCommentRepository.findById(key)); } @Override public ListenableFuture<AlarmComment> findAlarmCommentByIdAsync(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return findByIdAsync(tenantId, key); } @Override public void createPartition(AlarmCommentEntity entity) { partitioningRepository.createPartitionIfNotExists(ALARM_COMMENT_TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours)); } @Override
public PageData<AlarmComment> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(alarmCommentRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Override protected Class<AlarmCommentEntity> getEntityClass() { return AlarmCommentEntity.class; } @Override protected JpaRepository<AlarmCommentEntity, UUID> getRepository() { return alarmCommentRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\alarm\JpaAlarmCommentDao.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(final String name) { this.name = name; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } // @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass())
return false; final Foo other = (Foo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\mime\Foo.java
1
请在Spring Boot框架中完成以下Java代码
public JsonProduct getProductInfoNonNull() { if (this.jsonProduct == null) { throw new RuntimeCamelException("JsonProduct cannot be null!"); } return this.jsonProduct; } @NonNull public JsonPluFileAudit getJsonPluFileAuditNonNull() { if (this.jsonPluFileAudit == null) { throw new RuntimeCamelException("JsonPluFileAudit cannot be null!"); } return this.jsonPluFileAudit; } @NonNull public String getUpdatedPLUFileContent() { if (this.pluFileXmlContent == null) { throw new RuntimeCamelException("pluFileXmlContent cannot be null!"); } return this.pluFileXmlContent; } @NonNull public String getPLUTemplateFilename() { if (this.pluTemplateFilename == null)
{ throw new RuntimeCamelException("filename cannot be null!"); } return this.pluTemplateFilename; } @NonNull public List<String> getPluFileConfigKeys() { return this.pluFileConfigs.getPluFileConfigs() .stream() .map(JsonExternalSystemLeichMehlPluFileConfig::getTargetFieldName) .collect(ImmutableList.toImmutableList()); } @Nullable public Integer getAdPInstance() { return JsonMetasfreshId.toValue(this.jsonExternalSystemRequest.getAdPInstanceId()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderRouteContext.java
2
请完成以下Java代码
public class AccessPredicateVoter implements AccessDecisionVoter<ServerCall<?, ?>> { @Override public boolean supports(final ConfigAttribute attribute) { return attribute instanceof AccessPredicateConfigAttribute; } @Override public boolean supports(final Class<?> clazz) { return ServerCall.class.isAssignableFrom(clazz); } @Override public int vote(final Authentication authentication, final ServerCall<?, ?> serverCall, final Collection<ConfigAttribute> attributes) { final AccessPredicateConfigAttribute attr = find(attributes); if (attr == null) { return ACCESS_ABSTAIN; } final boolean allowed = attr.getAccessPredicate().test(authentication, serverCall); return allowed ? ACCESS_GRANTED : ACCESS_DENIED; } /**
* Finds the first AccessPredicateConfigAttribute in the given collection. * * @param attributes The attributes to search in. * @return The first found AccessPredicateConfigAttribute or null, if no such elements were found. */ private AccessPredicateConfigAttribute find(final Collection<ConfigAttribute> attributes) { for (final ConfigAttribute attribute : attributes) { if (attribute instanceof AccessPredicateConfigAttribute) { return (AccessPredicateConfigAttribute) attribute; } } return null; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\check\AccessPredicateVoter.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentResponse.java
2
请完成以下Java代码
public boolean equals(Object o) { if (!(o instanceof Intervalable)) { return false; } Intervalable other = (Intervalable) o; return this.start == other.getStart() && this.end == other.getEnd(); } @Override public int hashCode() { return this.start % 100 + this.end % 100; } @Override public int compareTo(Object o)
{ if (!(o instanceof Intervalable)) { return -1; } Intervalable other = (Intervalable) o; int comparison = this.start - other.getStart(); return comparison != 0 ? comparison : this.end - other.getEnd(); } @Override public String toString() { return this.start + ":" + this.end; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\interval\Interval.java
1
请完成以下Java代码
public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName == null ? null : categoryName.trim(); } public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() {
return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", categoryId=").append(categoryId); sb.append(", categoryName=").append(categoryName); sb.append(", isDeleted=").append(isDeleted); sb.append(", createTime=").append(createTime); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsCategory.java
1
请在Spring Boot框架中完成以下Java代码
public class MyBatisController { @Autowired private UserDao userDao; // 查询所有记录 @GetMapping("/users/mybatis/queryAll") public List<User> queryAll() { return userDao.findAllUsers(); } // 新增一条记录 @GetMapping("/users/mybatis/insert") public Boolean insert(String name, String password) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false; } User user = new User(); user.setName(name); user.setPassword(password); return userDao.insertUser(user) > 0; } // 修改一条记录 @GetMapping("/users/mybatis/update") public Boolean update(Integer id, String name, String password) { if (id == null || id < 1 || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false;
} User user = new User(); user.setId(id); user.setName(name); user.setPassword(password); return userDao.updUser(user) > 0; } // 删除一条记录 @GetMapping("/users/mybatis/delete") public Boolean delete(Integer id) { if (id == null || id < 1) { return false; } return userDao.delUser(id) > 0; } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-mybatis\src\main\java\cn\lanqiao\springboot3\controller\MyBatisController.java
2
请完成以下Java代码
public static InMemoryOrderStore provider() { return instance; } public static class PersistenceOrder { public int orderId; public String paymentMethod; public String address; public List<OrderItem> orderItems; public PersistenceOrder(int orderId, String paymentMethod, String address, List<OrderItem> orderItems) { this.orderId = orderId; this.paymentMethod = paymentMethod; this.address = address; this.orderItems = orderItems; }
public static class OrderItem { public int productId; public float unitPrice; public float itemWeight; public int quantity; public OrderItem(int productId, int quantity, float unitWeight, float unitPrice) { this.itemWeight = unitWeight; this.quantity = quantity; this.unitPrice = unitPrice; this.productId = productId; } } } }
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-infrastructure\src\main\java\com\baeldung\dddcontexts\infrastructure\db\InMemoryOrderStore.java
1
请完成以下Java代码
private static List<KPIField> excludeFields(final List<KPIField> fields, @Nullable final KPIField... excludeFields) { final List<KPIField> excludeFieldsList = excludeFields != null && excludeFields.length > 0 ? Stream.of(excludeFields).filter(Objects::nonNull).collect(Collectors.toList()) : null; if (excludeFieldsList == null || excludeFieldsList.isEmpty()) { return fields; } return fields.stream() .filter(field -> !excludeFieldsList.contains(field)) .collect(ImmutableList.toImmutableList()); } @Override public void loadRowToResult(@NonNull final KPIDataResult.Builder data, @NonNull final ResultSet rs) throws SQLException { final KPIDataValue url = SQLRowLoaderUtils.retrieveValue(rs, urlField); final KPIDataSetValuesMap.KPIDataSetValuesMapBuilder resultEntry = data .dataSet("URLs") .dataSetValue(KPIDataSetValuesAggregationKey.of(url)) .put("url", url);
loadField(resultEntry, rs, "caption", captionField); loadField(resultEntry, rs, "target", openTargetField); } public static void loadField( @NonNull final KPIDataSetValuesMap.KPIDataSetValuesMapBuilder resultEntry, @NonNull final ResultSet rs, @NonNull final String targetFieldName, @Nullable final KPIField field) throws SQLException { if (field == null) { return; } final KPIDataValue value = SQLRowLoaderUtils.retrieveValue(rs, field); resultEntry.put(targetFieldName, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\URLsSQLRowLoader.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isNonBlockingRedelivery() { return this.nonBlockingRedelivery; } public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) { this.nonBlockingRedelivery = nonBlockingRedelivery; } public Duration getSendTimeout() { return this.sendTimeout; } public void setSendTimeout(Duration sendTimeout) { this.sendTimeout = sendTimeout; } public JmsPoolConnectionFactoryProperties getPool() { return this.pool; } public Packages getPackages() { return this.packages; } String determineBrokerUrl() { if (this.brokerUrl != null) { return this.brokerUrl; } if (this.embedded.isEnabled()) { return DEFAULT_EMBEDDED_BROKER_URL; } return DEFAULT_NETWORK_BROKER_URL; } /** * Configuration for an embedded ActiveMQ broker. */ public static class Embedded { /** * Whether to enable embedded mode if the ActiveMQ Broker is available. */ private boolean enabled = true;
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Packages { /** * Whether to trust all packages. */ private @Nullable Boolean trustAll; /** * List of specific packages to trust (when not trusting all packages). */ private List<String> trusted = new ArrayList<>(); public @Nullable Boolean getTrustAll() { return this.trustAll; } public void setTrustAll(@Nullable Boolean trustAll) { this.trustAll = trustAll; } public List<String> getTrusted() { return this.trusted; } public void setTrusted(List<String> trusted) { this.trusted = trusted; } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
2
请完成以下Java代码
public String getUserOperationId() { return userOperationId; } public void setUserOperationId(String userOperationId) { this.userOperationId = userOperationId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); } @Override public String toString() { return this.getClass().getSimpleName()
+ "[activityInstanceId=" + activityInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", id=" + id + ", tenantId=" + tenantId + ", userOperationId=" + userOperationId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDetailEventEntity.java
1
请完成以下Java代码
public void setC_Print_Job_Detail_ID (int C_Print_Job_Detail_ID) { if (C_Print_Job_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, Integer.valueOf(C_Print_Job_Detail_ID)); } @Override public int getC_Print_Job_Detail_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Detail_ID); } @Override public de.metas.printing.model.I_C_Print_Job_Line getC_Print_Job_Line() { return get_ValueAsPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class); } @Override public void setC_Print_Job_Line(de.metas.printing.model.I_C_Print_Job_Line C_Print_Job_Line) { set_ValueFromPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class, C_Print_Job_Line); }
@Override public void setC_Print_Job_Line_ID (int C_Print_Job_Line_ID) { if (C_Print_Job_Line_ID < 1) set_Value (COLUMNNAME_C_Print_Job_Line_ID, null); else set_Value (COLUMNNAME_C_Print_Job_Line_ID, Integer.valueOf(C_Print_Job_Line_ID)); } @Override public int getC_Print_Job_Line_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_Line_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public class HttpSessionSaml2AuthenticationRequestRepository implements Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> { private static final String DEFAULT_SAML2_AUTHN_REQUEST_ATTR_NAME = HttpSessionSaml2AuthenticationRequestRepository.class .getName() .concat(".SAML2_AUTHN_REQUEST"); private String saml2AuthnRequestAttributeName = DEFAULT_SAML2_AUTHN_REQUEST_ATTR_NAME; @Override public AbstractSaml2AuthenticationRequest loadAuthenticationRequest(HttpServletRequest request) { HttpSession httpSession = request.getSession(false); if (httpSession == null) { return null; } return (AbstractSaml2AuthenticationRequest) httpSession.getAttribute(this.saml2AuthnRequestAttributeName); } @Override public void saveAuthenticationRequest(AbstractSaml2AuthenticationRequest authenticationRequest, HttpServletRequest request, HttpServletResponse response) {
if (authenticationRequest == null) { removeAuthenticationRequest(request, response); return; } HttpSession httpSession = request.getSession(); httpSession.setAttribute(this.saml2AuthnRequestAttributeName, authenticationRequest); } @Override public AbstractSaml2AuthenticationRequest removeAuthenticationRequest(HttpServletRequest request, HttpServletResponse response) { AbstractSaml2AuthenticationRequest authenticationRequest = loadAuthenticationRequest(request); if (authenticationRequest == null) { return null; } HttpSession httpSession = request.getSession(); httpSession.removeAttribute(this.saml2AuthnRequestAttributeName); return authenticationRequest; } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\HttpSessionSaml2AuthenticationRequestRepository.java
2
请完成以下Java代码
protected boolean register(Application application, String adminUrl, boolean firstAttempt) { try { String id = this.registrationClient.register(adminUrl, application); if (this.registeredId.compareAndSet(null, id)) { LOGGER.info("Application registered itself as {}", id); } else { LOGGER.debug("Application refreshed itself as {}", id); } return true; } catch (Exception ex) { if (firstAttempt) { LOGGER.warn( "Failed to register application as {} at spring-boot-admin ({}): {}. Further attempts are logged on DEBUG level", application, this.adminUrls, ex.getMessage(), ex); } else { LOGGER.debug("Failed to register application as {} at spring-boot-admin ({}): {}", application, this.adminUrls, ex.getMessage(), ex); } return false; } } @Override public void deregister() { String id = this.registeredId.get(); if (id == null) { return;
} for (String adminUrl : this.adminUrls) { try { this.registrationClient.deregister(adminUrl, id); this.registeredId.compareAndSet(id, null); if (this.registerOnce) { break; } } catch (Exception ex) { LOGGER.warn("Failed to deregister application (id={}) at spring-boot-admin ({}): {}", id, adminUrl, ex.getMessage()); } } } @Override public String getRegisteredId() { return this.registeredId.get(); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\DefaultApplicationRegistrator.java
1
请在Spring Boot框架中完成以下Java代码
public class ApiFallbackProvider implements FallbackProvider { public String getRoute() { return "*"; } public ClientHttpResponse fallbackResponse(String route, final Throwable cause) { return new ClientHttpResponse() { public HttpStatus getStatusCode() { return HttpStatus.OK; } public int getRawStatusCode() { return HttpStatus.OK.value(); } public String getStatusText() { return HttpStatus.OK.getReasonPhrase(); } public void close() {}
public InputStream getBody() { // 响应内容 String bodyText = String.format("{\"code\": 500,\"message\": \"Service unavailable:%s\"}", cause.getMessage()); return new ByteArrayInputStream(bodyText.getBytes()); } public HttpHeaders getHeaders() { // 响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // json 返回 return headers; } }; } }
repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo07-hystrix\src\main\java\cn\iocoder\springcloud\labx21\zuuldemo\fallback\ApiFallbackProvider.java
2
请完成以下Java代码
public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int n = to.length(); char[] circle = new char[n]; /* * First fill the circle buffer with as many characters as are in the to string. If we reach an early end, bail. */ for (i = 0; i < n; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < n; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= n) {
j -= n; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= n) { offset -= n; } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\XMLTokener.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @EmbeddedId private UserId userId; private Email email; public User() { } public User(UserId userId, Email email) { this.userId = userId; this.email = email; } public UserId getUserId() {
return userId; } public void setUserId(UserId userId) { this.userId = userId; } public Email getEmail() { return email; } public void setEmail(Email email) { this.email = email; } }
repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\serializable\User.java
2
请完成以下Spring Boot application配置
spring: security: oauth2: authorizationserver: client: oidc-client: registration: client-id: mcp-client client-secret: "{noop}secret" client-authentication-methods: client_secret_basic authorization-grant-types: client_credentials # Avo
id starting docker from the shared codebase docker: compose: enabled: false logging: level: org.springframework.ai.mcp: DEBUG
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\resources\application-mcp.yml
2
请在Spring Boot框架中完成以下Java代码
public boolean isSystem() { return repoId == SYSTEM.repoId; } public boolean isTrash() { return repoId == TRASH.repoId; } public boolean isRegular() { return !isSystem() && !isTrash(); } @Override
@JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final ClientId clientId) { return clientId != null ? clientId.getRepoId() : -1; } public static boolean equals(@Nullable final ClientId id1, @Nullable final ClientId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\ClientId.java
2
请完成以下Java代码
public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity
*/ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public void setSourceAmt (final @Nullable BigDecimal SourceAmt) { set_Value (COLUMNNAME_SourceAmt, SourceAmt); } @Override public BigDecimal getSourceAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SourceAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSource_Currency_ID (final int Source_Currency_ID) { if (Source_Currency_ID < 1) set_Value (COLUMNNAME_Source_Currency_ID, null); else set_Value (COLUMNNAME_Source_Currency_ID, Source_Currency_ID); } @Override public int getSource_Currency_ID() { return get_ValueAsInt(COLUMNNAME_Source_Currency_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostDetail.java
1
请完成以下Java代码
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Config_ScriptedImportConversion_ID (final int ExternalSystem_Config_ScriptedImportConversion_ID) { if (ExternalSystem_Config_ScriptedImportConversion_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID, ExternalSystem_Config_ScriptedImportConversion_ID); } @Override public int getExternalSystem_Config_ScriptedImportConversion_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ScriptedImportConversion_ID);
} @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setScriptIdentifier (final String ScriptIdentifier) { set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier); } @Override public String getScriptIdentifier() { return get_ValueAsString(COLUMNNAME_ScriptIdentifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedImportConversion.java
1
请完成以下Java代码
protected String doIt() throws Exception { addLog("Calling with params: externalSystemConfigAlbertaId {}, ignoreSelection {}, orgId {}", externalSystemConfigAlbertaId, ignoreSelection, orgId); final Set<BPartnerId> bPartnerIdSet = (ignoreSelection ? getAllBPartnerRecords() : getSelectedBPartnerRecords()) .stream() .map(I_C_BPartner::getC_BPartner_ID) .map(BPartnerId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); final OrgId computedOrgId = orgId > 0 ? OrgId.ofRepoId(orgId) : getProcessInfo().getOrgId(); final ExternalSystemAlbertaConfigId albertaConfigId = ExternalSystemAlbertaConfigId.ofRepoId(externalSystemConfigAlbertaId); final Stream<JsonExternalSystemRequest> requestList = invokeAlbertaService .streamSyncExternalRequestsForBPartnerIds(bPartnerIdSet, albertaConfigId, getPinstanceId(), computedOrgId); final ExternalSystemMessageSender externalSystemMessageSender = SpringContextHolder.instance.getBean(ExternalSystemMessageSender.class); requestList.forEach(externalSystemMessageSender::send); return JavaProcess.MSG_OK; } @NonNull private List<I_C_BPartner> getAllBPartnerRecords() { final IQueryBuilder<I_C_BPartner> bPartnerQuery = queryBL.createQueryBuilder(I_C_BPartner.class) .addOnlyActiveRecordsFilter(); if (orgId > 0) { bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId); } return bPartnerQuery.create() .stream() .collect(ImmutableList.toImmutableList());
} @NonNull private List<I_C_BPartner> getSelectedBPartnerRecords() { final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class); if (orgId > 0) { bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId); } return bPartnerQuery.create() .stream() .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeAlbertaForBPartnerIds.java
1
请完成以下Java代码
public static void concatByJoinBy100(Blackhole blackhole) { concatByJoin(DATA_100, blackhole); } @Benchmark public static void concatByJoinBy1000(Blackhole blackhole) { concatByJoin(DATA_1000, blackhole); } @Benchmark public static void concatByJoinBy10000(Blackhole blackhole) { concatByJoin(DATA_10000, blackhole); } public static void concatByJoin(String[] data, Blackhole blackhole) { String concatString = String.join("", data); blackhole.consume(concatString); } @Benchmark public static void concatByFormatBy100(Blackhole blackhole) { concatByFormat(FORMAT_STR_100, DATA_100, blackhole); } @Benchmark public static void concatByFormatBy1000(Blackhole blackhole) { concatByFormat(FORMAT_STR_1000, DATA_1000, blackhole); } @Benchmark public static void concatByFormatBy10000(Blackhole blackhole) { concatByFormat(FORMAT_STR_10000, DATA_10000, blackhole); } public static void concatByFormat(String formatStr, String[] data, Blackhole blackhole) { String concatString = String.format(formatStr, data); blackhole.consume(concatString); } @Benchmark public static void concatByStreamBy100(Blackhole blackhole) { concatByStream(DATA_100, blackhole); } @Benchmark
public static void concatByStreamBy1000(Blackhole blackhole) { concatByStream(DATA_1000, blackhole); } @Benchmark public static void concatByStreamBy10000(Blackhole blackhole) { concatByStream(DATA_10000, blackhole); } public static void concatByStream(String[] data, Blackhole blackhole) { String concatString = ""; List<String> strList = List.of(data); concatString = strList.stream().collect(Collectors.joining("")); blackhole.consume(concatString); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(BatchConcatBenchmark.class.getSimpleName()).threads(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\performance\BatchConcatBenchmark.java
1
请完成以下Java代码
public final class AndMessageMatcher<T> extends AbstractMessageMatcherComposite<T> { /** * Creates a new instance * @param messageMatchers the {@link MessageMatcher} instances to try */ public AndMessageMatcher(List<MessageMatcher<T>> messageMatchers) { super(messageMatchers); } /** * Creates a new instance * @param messageMatchers the {@link MessageMatcher} instances to try */ @SafeVarargs public AndMessageMatcher(MessageMatcher<T>... messageMatchers) { super(messageMatchers);
} @Override public boolean matches(Message<? extends T> message) { for (MessageMatcher<T> matcher : getMessageMatchers()) { this.logger.debug(LogMessage.format("Trying to match using %s", matcher)); if (!matcher.matches(message)) { this.logger.debug("Did not match"); return false; } } this.logger.debug("All messageMatchers returned true"); return true; } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\AndMessageMatcher.java
1
请在Spring Boot框架中完成以下Java代码
public void updateOperatorPwd(Long operatorId, String newPwd) { PmsOperator pmsOperator = pmsOperatorDao.getById(operatorId); pmsOperator.setLoginPwd(newPwd); pmsOperatorDao.update(pmsOperator); } /** * 根据登录名取得操作员对象 */ public PmsOperator findOperatorByLoginName(String loginName) { return pmsOperatorDao.findByLoginName(loginName); } /** * 保存操作員信息及其关联的角色. * * @param pmsOperator * . * @param roleOperatorStr * . */ @Transactional public void saveOperator(PmsOperator pmsOperator, String roleOperatorStr) { // 保存操作员信息 pmsOperatorDao.insert(pmsOperator); // 保存角色关联信息 if (StringUtils.isNotBlank(roleOperatorStr) && roleOperatorStr.length() > 0) { saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr); } } /** * 保存用户和角色之间的关联关系 */ private void saveOrUpdateOperatorRole(PmsOperator pmsOperator, String roleIdsStr) { // 删除原来的角色与操作员关联 List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(pmsOperator.getId()); Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>(); for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) { delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole); } if (StringUtils.isNotBlank(roleIdsStr)) { // 创建新的关联 String[] roleIds = roleIdsStr.split(","); for (int i = 0; i < roleIds.length; i++) { long roleId = Long.parseLong(roleIds[i]); if (delMap.get(roleId) == null) { PmsOperatorRole pmsOperatorRole = new PmsOperatorRole(); pmsOperatorRole.setOperatorId(pmsOperator.getId()); pmsOperatorRole.setRoleId(roleId); pmsOperatorRole.setCreater(pmsOperator.getCreater()); pmsOperatorRole.setCreateTime(new Date()); pmsOperatorRole.setStatus(PublicStatusEnum.ACTIVE.name()); pmsOperatorRoleDao.insert(pmsOperatorRole); } else { delMap.remove(roleId); }
} } Iterator<Long> iterator = delMap.keySet().iterator(); while (iterator.hasNext()) { long roleId = iterator.next(); pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, pmsOperator.getId()); } } /** * 修改操作員信息及其关联的角色. * * @param pmsOperator * . * @param roleOperatorStr * . */ public void updateOperator(PmsOperator pmsOperator, String roleOperatorStr) { pmsOperatorDao.update(pmsOperator); // 更新角色信息 this.saveOrUpdateOperatorRole(pmsOperator, roleOperatorStr); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorServiceImpl.java
2
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public List<AuthorList> getAuthors() { return authors; } public void setAuthors(List<AuthorList> authors) { this.authors = authors; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((BookList) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootManyToManyBidirectionalListVsSet\src\main\java\com\bookstore\entity\BookList.java
1
请完成以下Java代码
public class M_ForecastLine { @Init public void registerCallout() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_ForecastLine.COLUMNNAME_C_BPartner_ID, I_M_ForecastLine.COLUMNNAME_M_Product_ID, I_M_ForecastLine.COLUMNNAME_Qty, I_M_ForecastLine.COLUMNNAME_M_HU_PI_Item_Product_ID }) public void add_M_HU_PI_Item_Product(final I_M_ForecastLine forecastLine) { final IHUDocumentHandlerFactory huDocumentHandlerFactory = Services.get(IHUDocumentHandlerFactory.class); final IHUDocumentHandler handler = huDocumentHandlerFactory.createHandler(I_M_ForecastLine.Table_Name); if (null != handler) { handler.applyChangesFor(forecastLine); updateQtyPacks(forecastLine); updateQtyCalculated(forecastLine); } } @CalloutMethod(columnNames = { I_M_ForecastLine.COLUMNNAME_Qty })
public void updateQtyTU(final I_M_ForecastLine forecastLine) { updateQtyPacks(forecastLine); updateQtyCalculated(forecastLine); } @CalloutMethod(columnNames = { I_M_ForecastLine.COLUMNNAME_QtyEnteredTU, I_M_ForecastLine.COLUMNNAME_M_HU_PI_Item_Product_ID }) public void updateQtyCU(final I_M_ForecastLine forecastLine) { final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine); final Integer qtyPacks = packingAware.getQtyTU().intValue(); Services.get(IHUPackingAwareBL.class).setQtyCUFromQtyTU(packingAware, qtyPacks); } private void updateQtyPacks(final I_M_ForecastLine forecastLine) { final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine); Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware); } private void updateQtyCalculated(final I_M_ForecastLine forecastLine) { final IHUPackingAware packingAware = new ForecastLineHUPackingAware(forecastLine); final BigDecimal qty = packingAware.getQty(); packingAware.setQty(qty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ForecastLine.java
1