instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Payroll Department. @param HR_Department_ID Payroll Department */ public void setHR_Department_ID (int HR_Department_ID) { if (HR_Department_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Department_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Department_ID, Integer.valueOf(HR_Department_ID)); } /** Get Payroll Department. @return Payroll Department */ public int getHR_Department_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Department_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()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Department.java
1
请完成以下Java代码
public void setQtyPromised_TU (java.math.BigDecimal QtyPromised_TU) { set_Value (COLUMNNAME_QtyPromised_TU, QtyPromised_TU); } /** Get Zusagbar (TU). @return Zusagbar (TU) */ @Override public java.math.BigDecimal getQtyPromised_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU); if (bd == null) return Env.ZERO; return bd; } /** Set Zusagbar TU (nächste Woche). @param QtyPromised_TU_NextWeek Zusagbar TU (nächste Woche) */ @Override public void setQtyPromised_TU_NextWeek (java.math.BigDecimal QtyPromised_TU_NextWeek) { throw new IllegalArgumentException ("QtyPromised_TU_NextWeek is virtual column"); } /** Get Zusagbar TU (nächste Woche). @return Zusagbar TU (nächste Woche) */ @Override public java.math.BigDecimal getQtyPromised_TU_NextWeek () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_NextWeek); if (bd == null) return Env.ZERO; return bd; } /** Set Zusagbar TU (diese Woche). @param QtyPromised_TU_ThisWeek Zusagbar TU (diese Woche) */ @Override public void setQtyPromised_TU_ThisWeek (java.math.BigDecimal QtyPromised_TU_ThisWeek) { throw new IllegalArgumentException ("QtyPromised_TU_ThisWeek is virtual column"); } /** Get Zusagbar TU (diese Woche). @return Zusagbar TU (diese Woche) */ @Override public java.math.BigDecimal getQtyPromised_TU_ThisWeek () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_ThisWeek); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity to Order. @param QtyToOrder Quantity to Order */ @Override public void setQtyToOrder (java.math.BigDecimal QtyToOrder) { set_Value (COLUMNNAME_QtyToOrder, QtyToOrder); }
/** Get Quantity to Order. @return Quantity to Order */ @Override public java.math.BigDecimal getQtyToOrder () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity to Order (TU). @param QtyToOrder_TU Quantity to Order (TU) */ @Override public void setQtyToOrder_TU (java.math.BigDecimal QtyToOrder_TU) { set_Value (COLUMNNAME_QtyToOrder_TU, QtyToOrder_TU); } /** Get Quantity to Order (TU). @return Quantity to Order (TU) */ @Override public java.math.BigDecimal getQtyToOrder_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder_TU); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate.java
1
请在Spring Boot框架中完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public class ConfirmationActivityHandler implements WFActivityHandler, UserConfirmationSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("manufacturing.confirmation"); private final ManufacturingJobService manufacturingJobService; public ConfirmationActivityHandler(final ManufacturingJobService manufacturingJobService) {this.manufacturingJobService = manufacturingJobService;} @Override public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;} @Override public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent(wfActivity); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) {
return wfActivity.getStatus(); } @Override public WFProcess userConfirmed(@NonNull final UserConfirmationRequest request) { final WFProcess wfProcess = request.getWfProcess(); request.getWfActivity().getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE); final ManufacturingJobActivityId jobActivityId = request.getWfActivity().getId().getAsId(ManufacturingJobActivityId.class); final ManufacturingJob job = ManufacturingMobileApplication.getManufacturingJob(wfProcess); job.assertUserReporting(); final ManufacturingJob changedJob = manufacturingJobService.withActivityCompleted(job, jobActivityId); return ManufacturingRestService.toWFProcess(changedJob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\confirmation\ConfirmationActivityHandler.java
2
请在Spring Boot框架中完成以下Java代码
public String host() { return obtain(ElasticProperties::getHost, ElasticConfig.super::host); } @Override public String index() { return obtain(ElasticProperties::getIndex, ElasticConfig.super::index); } @Override public String indexDateFormat() { return obtain(ElasticProperties::getIndexDateFormat, ElasticConfig.super::indexDateFormat); } @Override public String indexDateSeparator() { return obtain(ElasticProperties::getIndexDateSeparator, ElasticConfig.super::indexDateSeparator); } @Override public String timestampFieldName() { return obtain(ElasticProperties::getTimestampFieldName, ElasticConfig.super::timestampFieldName); } @Override public boolean autoCreateIndex() { return obtain(ElasticProperties::isAutoCreateIndex, ElasticConfig.super::autoCreateIndex); }
@Override public @Nullable String userName() { return get(ElasticProperties::getUserName, ElasticConfig.super::userName); } @Override public @Nullable String password() { return get(ElasticProperties::getPassword, ElasticConfig.super::password); } @Override public @Nullable String pipeline() { return get(ElasticProperties::getPipeline, ElasticConfig.super::pipeline); } @Override public @Nullable String apiKeyCredentials() { return get(ElasticProperties::getApiKeyCredentials, ElasticConfig.super::apiKeyCredentials); } @Override public boolean enableSource() { return obtain(ElasticProperties::isEnableSource, ElasticConfig.super::enableSource); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticPropertiesConfigAdapter.java
2
请完成以下Java代码
protected void ensureAvailableBytes(int size) { if (offset + size > bufferSize) { try { int wantedBytes = offset + size - bufferSize; // 实际只需要这么多 wantedBytes = Math.max(wantedBytes, is.available()); // 如果非阻塞IO能读到更多,那越多越好 wantedBytes = Math.min(wantedBytes, offset); // 但不能超过脏区的大小 byte[] bytes = new byte[wantedBytes]; int readBytes = IOUtil.readBytesFromOtherInputStream(is, bytes); assert readBytes > 0 : "已到达文件尾部!"; System.arraycopy(this.bytes, offset, this.bytes, offset - wantedBytes, bufferSize - offset); System.arraycopy(bytes, 0, this.bytes, bufferSize - wantedBytes, wantedBytes); offset -= wantedBytes; } catch (IOException e) { throw new RuntimeException(e); } } }
@Override public void close() { super.close(); if (is == null) { return; } try { is.close(); } catch (IOException e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayOtherStream.java
1
请在Spring Boot框架中完成以下Java代码
public User getUserDefault(Long id) { String a = null; // 测试服务降级 a.toString(); User user = new User(); user.setId(-1L); user.setUsername("defaultUser"); user.setPassword("123456"); return user; } public User getUserDefault2(Long id, Throwable e) { System.out.println(e.getMessage()); User user = new User(); user.setId(-2L); user.setUsername("defaultUser2"); user.setPassword("123456"); return user; } public List<User> getUsers() { return this.restTemplate.getForObject("http://Server-Provider/user", List.class); } public String addUser() { User user = new User(1L, "mrbird", "123456"); HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); if (status.is2xxSuccessful()) {
return "新增用户成功"; } else { return "新增用户失败"; } } @CacheRemove(commandKey = "getUserById") @HystrixCommand public void updateUser(@CacheKey("id") User user) { this.restTemplate.put("http://Server-Provider/user", user); } public void deleteUser(@PathVariable Long id) { this.restTemplate.delete("http://Server-Provider/user/{1}", id); } }
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java
2
请完成以下Java代码
private static final class DailyFlatrateDataEntry { public static DailyFlatrateDataEntry of(final Date day) { return new DailyFlatrateDataEntry(day); } private final Date day; private BigDecimal qtyPlanned = BigDecimal.ZERO; private BigDecimal qtyPlannedAllocated = BigDecimal.ZERO; private DailyFlatrateDataEntry(final Date day) { super(); Check.assumeNotNull(day, "day not null"); this.day = day; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("day", day) .add("qtyPlanned", qtyPlanned) .add("qtyPlannedAllocated", qtyPlannedAllocated) .toString(); } public Date getDay()
{ return day; } public void addQtyPlanned(final BigDecimal qtyPlannedToAdd) { if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0) { return; } qtyPlanned = qtyPlanned.add(qtyPlannedToAdd); } public BigDecimal allocateQtyPlanned() { final BigDecimal qtyPlannedToAllocate = qtyPlanned.subtract(qtyPlannedAllocated); qtyPlannedAllocated = qtyPlanned; return qtyPlannedToAllocate; } public boolean isFullyAllocated() { return qtyPlannedAllocated.compareTo(qtyPlanned) == 0; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\PMMContractBuilder.java
1
请完成以下Java代码
public String getMsgId() { return msgId; } /** * Sets the value of the msgId property. * * @param value * allowed object is * {@link String } * */ public void setMsgId(String value) { this.msgId = value; } /** * Gets the value of the msgNmId property. * * @return * possible object is * {@link String } * */ public String getMsgNmId() { return msgNmId; } /** * Sets the value of the msgNmId property. * * @param value * allowed object is * {@link String }
* */ public void setMsgNmId(String value) { this.msgNmId = value; } /** * Gets the value of the creDtTm property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreDtTm() { return creDtTm; } /** * Sets the value of the creDtTm property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreDtTm(XMLGregorianCalendar value) { this.creDtTm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\OriginalBusinessQuery1.java
1
请完成以下Java代码
private void checkWaitingJobs(TenantId tenantId, JobType jobType) { Job queuedJob = jobDao.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId, jobType, QUEUED); if (queuedJob == null || jobDao.existsByTenantIdAndTypeAndStatusOneOf(tenantId, jobType, PENDING, RUNNING)) { return; } queuedJob.setStatus(PENDING); saveJob(tenantId, queuedJob, true, QUEUED); } @Override public PageData<Job> findJobsByFilter(TenantId tenantId, JobFilter filter, PageLink pageLink) { PageData<Job> jobs = jobDao.findByTenantIdAndFilter(tenantId, filter, pageLink); Set<EntityId> entityIds = jobs.getData().stream() .map(Job::getEntityId) .collect(Collectors.toSet()); Map<EntityId, EntityInfo> entityInfos = entityService.fetchEntityInfos(tenantId, null, entityIds); jobs.getData().forEach(job -> { EntityInfo entityInfo = entityInfos.get(job.getEntityId()); if (entityInfo != null) { job.setEntityName(entityInfo.getName()); } }); return jobs; } @Override public Job findLatestJobByKey(TenantId tenantId, String key) { return jobDao.findLatestByTenantIdAndKey(tenantId, key); } @Override public void deleteJob(TenantId tenantId, JobId jobId) { Job job = findJobById(tenantId, jobId); if (!job.getStatus().isOneOf(CANCELLED, COMPLETED, FAILED)) { throw new IllegalArgumentException("Job must be cancelled, completed or failed"); } jobDao.removeById(tenantId, jobId.getId()); } @Override
public int deleteJobsByEntityId(TenantId tenantId, EntityId entityId) { // TODO: cancel all jobs for this entity return jobDao.removeByEntityId(tenantId, entityId); } private Job findForUpdate(TenantId tenantId, JobId jobId) { return jobDao.findByIdForUpdate(tenantId, jobId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findJobById(tenantId, (JobId) entityId)); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(jobDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { jobDao.removeById(tenantId, id.getId()); } @Override public void deleteByTenantId(TenantId tenantId) { jobDao.removeByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.JOB; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\job\DefaultJobService.java
1
请在Spring Boot框架中完成以下Java代码
public XMLGregorianCalendar getPriceValidFrom() { return priceValidFrom; } /** * Sets the value of the priceValidFrom property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setPriceValidFrom(XMLGregorianCalendar value) { this.priceValidFrom = value; } /** * Gets the value of the priceValidTo property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getPriceValidTo() { return priceValidTo; } /** * Sets the value of the priceValidTo property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setPriceValidTo(XMLGregorianCalendar value) { this.priceValidTo = value; }
/** * Gets the value of the parties property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parties property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParties().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BusinessEntityType } * * */ public List<BusinessEntityType> getParties() { if (parties == null) { parties = new ArrayList<BusinessEntityType>(); } return this.parties; } }
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\PriceSpecificationType.java
2
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = 3659932210257138726L; private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User [userName=" + userName + ", password=" + password + "]"; } public User() { } public User(String userName, String password) { super(); this.userName = userName; this.password = password;
} private void writeObject(ObjectOutputStream oos) throws IOException { this.password = "xyz" + password; oos.defaultWriteObject(); } private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { aInputStream.defaultReadObject(); this.password = password.substring(3); } private Object readResolve() { return this; } }
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\readresolvevsreadobject\User.java
1
请在Spring Boot框架中完成以下Java代码
class Passenger { @Id @GeneratedValue @Column(nullable = false) private Long id; @Basic(optional = false) @Column(nullable = false) private String firstName; @Basic(optional = false) @Column(nullable = false) private String lastName; @Basic(optional = false) @Column(nullable = false) private Integer seatNumber; private Passenger(String firstName, String lastName, Integer seatNumber) { this.firstName = firstName; this.lastName = lastName; this.seatNumber = seatNumber; } static Passenger from(String firstName, String lastName, Integer seatNumber) { return new Passenger(firstName, lastName, seatNumber); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; Passenger passenger = (Passenger) object; return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) && Objects.equals(getLastName(), passenger.getLastName());
} @Override public int hashCode() { return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); } @Override public String toString() { final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); toStringBuilder.append("{ id=").append(id); toStringBuilder.append(", firstName='").append(firstName).append('\''); toStringBuilder.append(", lastName='").append(lastName).append('\''); toStringBuilder.append(", seatNumber=").append(seatNumber); toStringBuilder.append('}'); return toStringBuilder.toString(); } Long getId() { return id; } String getFirstName() { return firstName; } String getLastName() { return lastName; } Integer getSeatNumber() { return seatNumber; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\boot\passenger\Passenger.java
2
请完成以下Java代码
public static final class PublicKeyCredentialUserEntityBuilder { @SuppressWarnings("NullAway.Init") private String name; @SuppressWarnings("NullAway.Init") private Bytes id; private @Nullable String displayName; private PublicKeyCredentialUserEntityBuilder() { } /** * Sets the {@link #getName()} property. * @param name the name * @return the {@link PublicKeyCredentialUserEntityBuilder} */ public PublicKeyCredentialUserEntityBuilder name(String name) { this.name = name; return this; } /** * Sets the {@link #getId()} property. * @param id the id * @return the {@link PublicKeyCredentialUserEntityBuilder} */ public PublicKeyCredentialUserEntityBuilder id(Bytes id) { this.id = id; return this; } /** * Sets the {@link #getDisplayName()} property. * @param displayName the display name * @return the {@link PublicKeyCredentialUserEntityBuilder}
*/ public PublicKeyCredentialUserEntityBuilder displayName(String displayName) { this.displayName = displayName; return this; } /** * Builds a new {@link PublicKeyCredentialUserEntity} * @return a new {@link PublicKeyCredentialUserEntity} */ public PublicKeyCredentialUserEntity build() { return new ImmutablePublicKeyCredentialUserEntity(this.name, this.id, this.displayName); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutablePublicKeyCredentialUserEntity.java
1
请完成以下Java代码
public class MacbookPro extends Computer { private static final Logger LOG = LoggerFactory.getLogger(MacbookPro.class); public MacbookPro(int age, String color) { super(age, color); } MacbookPro(Integer age, String color, Integer healty) { super(age, color, healty); } @Override public void turnOnPc() { LOG.debug("MacbookPro turned on"); }
@Override public void turnOffPc() { LOG.debug("MacbookPro turned off"); } @Override public Double calculateValue(Double initialValue) { Function<Double, Double> function = super::calculateValue; final Double pcValue = function.apply(initialValue); LOG.debug("First value is:" + pcValue); return pcValue + (initialValue / 10); } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\doublecolon\MacbookPro.java
1
请完成以下Java代码
public void save(final I_DD_Order ddOrder) { ddOrderLowLevelDAO.save(ddOrder); } public void save(final I_DD_OrderLine ddOrderline) { ddOrderLowLevelDAO.save(ddOrderline); } public void save(final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlternative) { ddOrderLowLevelDAO.save(ddOrderLineOrAlternative); } public List<I_DD_OrderLine> retrieveLines(final I_DD_Order order) { return ddOrderLowLevelDAO.retrieveLines(order); } public List<I_DD_OrderLine_Alternative> retrieveAllAlternatives(final I_DD_OrderLine ddOrderLine) {
return ddOrderLowLevelDAO.retrieveAllAlternatives(ddOrderLine); } public void updateUomFromProduct(final I_DD_OrderLine ddOrderLine) { final ProductId productId = ProductId.ofRepoIdOrNull(ddOrderLine.getM_Product_ID()); if (productId == null) { // nothing to do return; } final UomId stockingUomId = productBL.getStockUOMId(productId); ddOrderLine.setC_UOM_ID(stockingUomId.getRepoId()); } public void deleteOrders(@NonNull final DeleteOrdersQuery deleteOrdersQuery) { ddOrderLowLevelDAO.deleteOrders(deleteOrdersQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DDOrderLowLevelService.java
1
请完成以下Java代码
public String toString() { return new ToStringCreator(this).append("changeSet", this.changeSet) .append("restartRequired", this.restartRequired) .toString(); } /** * Return an overview of the changes that triggered this event. * @return an overview of the changes * @since 2.6.11 */ public String overview() { int added = 0; int deleted = 0; int modified = 0; for (ChangedFiles changedFiles : this.changeSet) { for (ChangedFile changedFile : changedFiles) { Type type = changedFile.getType(); if (type == Type.ADD) { added++; } else if (type == Type.DELETE) { deleted++;
} else if (type == Type.MODIFY) { modified++; } } } int size = added + deleted + modified; return String.format("%s (%s, %s, %s)", quantityOfUnit(size, "class path change"), quantityOfUnit(added, "addition"), quantityOfUnit(deleted, "deletion"), quantityOfUnit(modified, "modification")); } private String quantityOfUnit(int quantity, String unit) { return quantity + " " + ((quantity != 1) ? unit + "s" : unit); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\classpath\ClassPathChangedEvent.java
1
请完成以下Java代码
public static VariableOrderProperty forTaskVariable(String variableName, ValueType valueType) { VariableOrderProperty orderingProperty = new VariableOrderProperty(variableName, valueType); orderingProperty.relationConditions.add( new QueryEntityRelationCondition(VariableInstanceQueryProperty.TASK_ID, TaskQueryProperty.TASK_ID)); return orderingProperty; } public static VariableOrderProperty forCaseInstanceVariable(String variableName, ValueType valueType) { VariableOrderProperty orderingProperty = new VariableOrderProperty(variableName, valueType); orderingProperty.relationConditions.add( new QueryEntityRelationCondition(VariableInstanceQueryProperty.CASE_EXECUTION_ID, TaskQueryProperty.CASE_INSTANCE_ID)); return orderingProperty; } public static VariableOrderProperty forCaseExecutionVariable(String variableName, ValueType valueType) { VariableOrderProperty orderingProperty = new VariableOrderProperty(variableName, valueType); orderingProperty.relationConditions.add( new QueryEntityRelationCondition(VariableInstanceQueryProperty.CASE_EXECUTION_ID, TaskQueryProperty.CASE_EXECUTION_ID)); return orderingProperty; } public static QueryProperty typeToQueryProperty(ValueType type) { if (ValueType.STRING.equals(type)) { return VariableInstanceQueryProperty.TEXT_AS_LOWER; } else if (ValueType.INTEGER.equals(type)) { return VariableInstanceQueryProperty.LONG;
} else if (ValueType.SHORT.equals(type)) { return VariableInstanceQueryProperty.LONG; } else if (ValueType.DATE.equals(type)) { return VariableInstanceQueryProperty.LONG; } else if (ValueType.BOOLEAN.equals(type)) { return VariableInstanceQueryProperty.LONG; } else if (ValueType.LONG.equals(type)) { return VariableInstanceQueryProperty.LONG; } else if (ValueType.DOUBLE.equals(type)) { return VariableInstanceQueryProperty.DOUBLE; } else { throw new ProcessEngineException("Cannot order by variables of type " + type.getName()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableOrderProperty.java
1
请完成以下Java代码
public List<ProcessDefinitionStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsGroupedByProcessDefinitionVersion(this, page); } public ProcessDefinitionStatisticsQuery includeFailedJobs() { includeFailedJobs = true; return this; } public ProcessDefinitionStatisticsQuery includeIncidents() { includeIncidents = true; return this; } public ProcessDefinitionStatisticsQuery includeIncidentsForType(String incidentType) { this.includeIncidentsForType = incidentType; return this; } public boolean isFailedJobsToInclude() { return includeFailedJobs; }
public boolean isIncidentsToInclude() { return includeIncidents || includeRootIncidents || includeIncidentsForType != null; } protected void checkQueryOk() { super.checkQueryOk(); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } if (includeRootIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeRootIncident() and includeIncidentForType() to execute one query."); } if (includeIncidents && includeRootIncidents) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeRootIncidents() to execute one query."); } } @Override public ProcessDefinitionStatisticsQuery includeRootIncidents() { this.includeRootIncidents = true; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionStatisticsQueryImpl.java
1
请完成以下Java代码
public class SynchronizedBlocks { private int count = 0; private static int staticCount = 0; void performSynchronisedTask() { synchronized (this) { setCount(getCount() + 1); } } static void performStaticSyncTask() { synchronized (SynchronizedBlocks.class) { setStaticCount(getStaticCount() + 1); } }
public int getCount() { return count; } public void setCount(int count) { this.count = count; } static int getStaticCount() { return staticCount; } private static void setStaticCount(int staticCount) { SynchronizedBlocks.staticCount = staticCount; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-4\src\main\java\com\baeldung\concurrent\synchronize\SynchronizedBlocks.java
1
请完成以下Java代码
public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value = "compact", converter = BooleanConverter.class) public void setCompact(Boolean compact) { this.compact = compact; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected CleanableHistoricCaseInstanceReport createNewQuery(ProcessEngine engine) { return engine.getHistoryService().createCleanableHistoricCaseInstanceReport(); } @Override protected void applyFilters(CleanableHistoricCaseInstanceReport query) { if (caseDefinitionIdIn != null && caseDefinitionIdIn.length > 0) {
query.caseDefinitionIdIn(caseDefinitionIdIn); } if (caseDefinitionKeyIn != null && caseDefinitionKeyIn.length > 0) { query.caseDefinitionKeyIn(caseDefinitionKeyIn); } if (Boolean.TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIdIn != null && tenantIdIn.length > 0) { query.tenantIdIn(tenantIdIn); } if (Boolean.TRUE.equals(compact)) { query.compact(); } } @Override protected void applySortBy(CleanableHistoricCaseInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { query.orderByFinished(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportDto.java
1
请完成以下Java代码
public void signalExecution(ExecutionTriggerDto triggerDto) { RuntimeService runtimeService = engine.getRuntimeService(); try { VariableMap variables = VariableValueDto.toMap(triggerDto.getVariables(), engine, objectMapper); runtimeService.signal(executionId, variables); } catch (RestException e) { String errorMessage = String.format("Cannot signal execution %s: %s", executionId, e.getMessage()); throw new InvalidRequestException(e.getStatus(), e, errorMessage); } catch (AuthorizationException e) { throw e; } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Cannot signal execution " + executionId + ": " + e.getMessage()); } } @Override public VariableResource getLocalVariables() { return new LocalExecutionVariablesResource(engine, executionId, objectMapper); }
@Override public EventSubscriptionResource getMessageEventSubscription(String messageName) { return new MessageEventSubscriptionResource(engine, executionId, messageName, objectMapper); } @Override public IncidentDto createIncident(CreateIncidentDto createIncidentDto) { Incident newIncident = null; try { newIncident = engine.getRuntimeService() .createIncident(createIncidentDto.getIncidentType(), executionId, createIncidentDto.getConfiguration(), createIncidentDto.getMessage()); } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); } return IncidentDto.fromIncident(newIncident); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ExecutionResourceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public Object getValue() { return variableValue; } @Override public void setValue(Object value) { variableValue = value; } @Override public String getTypeName() { return TYPE_TRANSIENT; } @Override public void setTypeName(String typeName) { // Not relevant } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getExecutionId() { return executionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } @Override public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getMetaInfo() {
return metaInfo; } @Override public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } // The methods below are not relevant, as getValue() is used directly to return the value set during the transaction @Override public String getTextValue() { return null; } @Override public void setTextValue(String textValue) { } @Override public String getTextValue2() { return null; } @Override public void setTextValue2(String textValue2) { } @Override public Long getLongValue() { return null; } @Override public void setLongValue(Long longValue) { } @Override public Double getDoubleValue() { return null; } @Override public void setDoubleValue(Double doubleValue) { } @Override public byte[] getBytes() { return null; } @Override public void setBytes(byte[] bytes) { } @Override public Object getCachedValue() { return null; } @Override public void setCachedValue(Object cachedValue) { } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
2
请完成以下Java代码
public class SignalReceivedListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNSignalReceivedEvent>> processRuntimeEventListeners; private ToSignalReceivedConverter converter; public SignalReceivedListenerDelegate( List<BPMNElementEventListener<BPMNSignalReceivedEvent>> processRuntimeEventListeners, ToSignalReceivedConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiSignalEvent) {
converter .from((ActivitiSignalEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNSignalReceivedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\SignalReceivedListenerDelegate.java
1
请完成以下Java代码
public BigDecimal getOrderedQuantity() { return getShipmentScheduleDetail().getOrderedQuantity(); } @NonNull public BigDecimal getReservedQuantity() { return getShipmentScheduleDetail().getReservedQuantity(); } @Nullable public OldShipmentScheduleData getOldShipmentScheduleData() { return getShipmentScheduleDetail().getOldShipmentScheduleData(); } @OverridingMethodsMustInvokeSuper
public void validate() { checkIdGreaterThanZero("shipmentScheduleId", shipmentScheduleId); Check.errorIf(eventDescriptor == null, "eventDescriptor may not be null"); Check.errorIf(materialDescriptor == null, "materialDescriptor may not be null"); } @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.of(M_SHIPMENTSCHEDULE_TABLE_NAME, shipmentScheduleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\shipmentschedule\AbstractShipmentScheduleEvent.java
1
请完成以下Java代码
protected Map<String, List<ExecutableScript>> getPaEnvScripts(ProcessApplicationReference pa) { try { ProcessApplicationInterface processApplication = pa.getProcessApplication(); ProcessApplicationInterface rawObject = processApplication.getRawObject(); if (rawObject instanceof AbstractProcessApplication) { AbstractProcessApplication abstractProcessApplication = (AbstractProcessApplication) rawObject; return abstractProcessApplication.getEnvironmentScripts(); } return null; } catch (ProcessApplicationUnavailableException e) { throw new ProcessEngineException("Process Application is unavailable.", e); } } protected List<ExecutableScript> getEnvScripts(ExecutableScript script, ScriptEngine scriptEngine) { List<ExecutableScript> envScripts = getEnvScripts(script.getLanguage().toLowerCase()); if (envScripts.isEmpty()) { envScripts = getEnvScripts(scriptEngine.getFactory().getLanguageName().toLowerCase()); } return envScripts; } /** * Returns the env scripts for the given language. Performs lazy initialization of the env scripts. * * @param scriptLanguage the language * @return a list of executable environment scripts. Never null. */ protected List<ExecutableScript> getEnvScripts(String scriptLanguage) { Map<String, List<ExecutableScript>> environment = getEnv(scriptLanguage); List<ExecutableScript> envScripts = environment.get(scriptLanguage); if(envScripts == null) { synchronized (this) { envScripts = environment.get(scriptLanguage); if(envScripts == null) { envScripts = initEnvForLanguage(scriptLanguage); environment.put(scriptLanguage, envScripts); } }
} return envScripts; } /** * Initializes the env scripts for a given language. * * @param language the language * @return the list of env scripts. Never null. */ protected List<ExecutableScript> initEnvForLanguage(String language) { List<ExecutableScript> scripts = new ArrayList<>(); for (ScriptEnvResolver resolver : envResolvers) { String[] resolvedScripts = resolver.resolve(language); if(resolvedScripts != null) { for (String resolvedScript : resolvedScripts) { scripts.add(scriptFactory.createScriptFromSource(language, resolvedScript)); } } } return scripts; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\env\ScriptingEnvironment.java
1
请完成以下Java代码
public class RedisCacheMetrics extends CacheMeterBinder<RedisCache> { private final RedisCache cache; public RedisCacheMetrics(RedisCache cache, Iterable<Tag> tags) { super(cache, cache.getName(), tags); this.cache = cache; } @Override protected @Nullable Long size() { return null; } @Override protected long hitCount() { return this.cache.getStatistics().getHits(); } @Override protected Long missCount() { return this.cache.getStatistics().getMisses(); } @Override protected @Nullable Long evictionCount() { return null; }
@Override protected long putCount() { return this.cache.getStatistics().getPuts(); } @Override protected void bindImplementationSpecificMetrics(MeterRegistry registry) { FunctionCounter.builder("cache.removals", this.cache, (cache) -> cache.getStatistics().getDeletes()) .tags(getTagsWithCacheName()) .description("Cache removals") .register(registry); FunctionCounter.builder("cache.gets", this.cache, (cache) -> cache.getStatistics().getPending()) .tags(getTagsWithCacheName()) .tag("result", "pending") .description("The number of pending requests") .register(registry); TimeGauge .builder("cache.lock.duration", this.cache, TimeUnit.NANOSECONDS, (cache) -> cache.getStatistics().getLockWaitDuration(TimeUnit.NANOSECONDS)) .tags(getTagsWithCacheName()) .description("The time the cache has spent waiting on a lock") .register(registry); } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\metrics\RedisCacheMetrics.java
1
请完成以下Java代码
public UomId getPriceUomId() { return purchaseCandidate.getPriceUomId(); } @Nullable public Percent getDiscount() { return purchaseCandidate.getDiscountEff(); } @Nullable public String getExternalPurchaseOrderUrl() { return purchaseCandidate.getExternalPurchaseOrderUrl(); } @Nullable public ExternalId getExternalHeaderId() { return purchaseCandidate.getExternalHeaderId(); } @Nullable
public ExternalSystemId getExternalSystemId() { return purchaseCandidate.getExternalSystemId(); } @Nullable public ExternalId getExternalLineId() { return purchaseCandidate.getExternalLineId(); } @Nullable public String getPOReference() { return purchaseCandidate.getPOReference(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
1
请完成以下Java代码
public java.util.Date getUtilDate() { return utilDate; } public void setUtilDate(java.util.Date utilDate) { this.utilDate = utilDate; } public java.util.Date getUtilTime() { return utilTime; } public void setUtilTime(java.util.Date utilTime) { this.utilTime = utilTime; } public java.util.Date getUtilTimestamp() { return utilTimestamp; } public void setUtilTimestamp(java.util.Date utilTimestamp) { this.utilTimestamp = utilTimestamp; } public Calendar getCalendarDate() { return calendarDate; } public void setCalendarDate(Calendar calendarDate) { this.calendarDate = calendarDate; } public Calendar getCalendarTimestamp() { return calendarTimestamp; } public void setCalendarTimestamp(Calendar calendarTimestamp) { this.calendarTimestamp = calendarTimestamp; } public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } public LocalTime getLocalTime() { return localTimeField; } public void setLocalTime(LocalTime localTime) { this.localTimeField = localTime; } public OffsetTime getOffsetTime() { return offsetTime; } public void setOffsetTime(OffsetTime offsetTime) { this.offsetTime = offsetTime;
} public Instant getInstant() { return instant; } public void setInstant(Instant instant) { this.instant = instant; } public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } public OffsetDateTime getOffsetDateTime() { return offsetDateTime; } public void setOffsetDateTime(OffsetDateTime offsetDateTime) { this.offsetDateTime = offsetDateTime; } public ZonedDateTime getZonedDateTime() { return zonedDateTime; } public void setZonedDateTime(ZonedDateTime zonedDateTime) { this.zonedDateTime = zonedDateTime; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\TemporalValues.java
1
请在Spring Boot框架中完成以下Java代码
public Date getMovementDate() { return movementDate; } public void setMovementDate(final Date movementDate) { this.movementDate = movementDate; } public String getPoReference() { return poReference; } public void setPoReference(final String poReference) { this.poReference = poReference; } public String getShipmentDocumentno() { return shipmentDocumentno; } public void setShipmentDocumentno(final String shipmentDocumentno) { this.shipmentDocumentno = shipmentDocumentno; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cOrderID == null ? 0 : cOrderID.hashCode()); result = prime * result + (dateOrdered == null ? 0 : dateOrdered.hashCode()); result = prime * result + (mInOutID == null ? 0 : mInOutID.hashCode()); result = prime * result + (movementDate == null ? 0 : movementDate.hashCode()); result = prime * result + (poReference == null ? 0 : poReference.hashCode()); result = prime * result + (shipmentDocumentno == null ? 0 : shipmentDocumentno.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 Cctop111V other = (Cctop111V)obj; if (cOrderID == null) { if (other.cOrderID != null) { return false; } } else if (!cOrderID.equals(other.cOrderID)) { return false; } if (dateOrdered == null) { if (other.dateOrdered != null) { return false; } } else if (!dateOrdered.equals(other.dateOrdered)) { return false; } if (mInOutID == null) { if (other.mInOutID != null) {
return false; } } else if (!mInOutID.equals(other.mInOutID)) { return false; } if (movementDate == null) { if (other.movementDate != null) { return false; } } else if (!movementDate.equals(other.movementDate)) { return false; } if (poReference == null) { if (other.poReference != null) { return false; } } else if (!poReference.equals(other.poReference)) { return false; } if (shipmentDocumentno == null) { if (other.shipmentDocumentno != null) { return false; } } else if (!shipmentDocumentno.equals(other.shipmentDocumentno)) { return false; } return true; } @Override public String toString() { return "Cctop111V [cOrderID=" + cOrderID + ", mInOutID=" + mInOutID + ", dateOrdered=" + dateOrdered + ", movementDate=" + movementDate + ", poReference=" + poReference + ", shipmentDocumentno=" + shipmentDocumentno + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop111V.java
2
请完成以下Java代码
public int toInt() { return value; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(value); } @Override public int compareTo(@NonNull final QuantityTU other) { return this.value - other.value; } public QuantityTU add(@NonNull final QuantityTU toAdd) { if (this.value == 0) { return toAdd; }
else if (toAdd.value == 0) { return this; } else { return ofInt(this.value + toAdd.value); } } public QuantityTU subtract(@NonNull final QuantityTU toSubtract) { if (toSubtract.value == 0) { return this; } else { return ofInt(this.value - toSubtract.value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityTU.java
1
请完成以下Java代码
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { Element element = new Element(uri, localName, qName, attributes, locator); if (elementStack.isEmpty()) { parse.rootElement = element; } else { elementStack.peek().add(element); } elementStack.push(element); } public void characters(char[] ch, int start, int length) throws SAXException { elementStack.peek().appendText(String.valueOf(ch, start, length)); } public void endElement(String uri, String localName, String qName) throws SAXException { elementStack.pop(); } public void error(SAXParseException e) { parse.addError(e); }
public void fatalError(SAXParseException e) { parse.addError(e); } public void warning(SAXParseException e) { parse.addWarning(e); } public void setDocumentLocator(Locator locator) { this.locator = locator; } public void setDefaultNamespace(String defaultNamespace) { this.defaultNamespace = defaultNamespace; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\ParseHandler.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!getSelectedRowIds().isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final PickingSlotRow pickingSlotRow = getSingleSelectedRow(); if (!pickingSlotRow.isPickedHURow()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU)); } if (!pickingSlotRow.isTopLevelHU()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU)); } if (pickingSlotRow.getHuQtyCU().signum() <= 0) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_PICK_SOMETHING)); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() { final PickingSlotRow rowToProcess = getSingleSelectedRow(); printPickingLabel(rowToProcess.getHuId()); return MSG_OK; } protected void printPickingLabel(@NonNull final HuId huId) { huLabelService.print(HULabelPrintRequest.builder() .sourceDocType(HULabelSourceDocType.Picking) .hu(HUToReportWrapper.of(handlingUnitsDAO.getById(huId))) .onlyIfAutoPrint(false) .failOnMissingLabelConfig(true) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_TU_Label.java
1
请完成以下Java代码
public class BeanToCsv { public void beanToCSVWithDefault(List<Application> applications) throws Exception { try (FileWriter writer = new FileWriter("src/main/resources/application.csv")) { var builder = new StatefulBeanToCsvBuilder<Application>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER) .withSeparator(',') .build(); builder.write(applications); } } public void beanToCSVWithCustomHeaderStrategy(List<Application> applications) throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException { try (FileWriter writer = new FileWriter("src/main/resources/application2.csv")) { var mappingStrategy = new CustomHeaderStrategy<Application>(); mappingStrategy.setType(Application.class); var builder = new StatefulBeanToCsvBuilder<Application>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER) .withMappingStrategy(mappingStrategy) .build(); builder.write(applications); } }
public void beanToCSVWithCustomPositionStrategy(List<ApplicationWithAnnotation> applications) throws Exception { try (FileWriter writer = new FileWriter("src/main/resources/application3.csv")) { var builder = new StatefulBeanToCsvBuilder<ApplicationWithAnnotation>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER) .build(); builder.write(applications); } } public void beanToCSVWithCustomHeaderAndPositionStrategy(List<ApplicationWithAnnotation> applications) throws IOException, CsvRequiredFieldEmptyException, CsvDataTypeMismatchException { try (FileWriter writer = new FileWriter("src/main/resources/application4.csv")) { var mappingStrategy = new CustomColumnPositionStrategy<ApplicationWithAnnotation>(); mappingStrategy.setType(ApplicationWithAnnotation.class); var builder = new StatefulBeanToCsvBuilder<ApplicationWithAnnotation>(writer).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER) .withMappingStrategy(mappingStrategy) .build(); builder.write(applications); } } }
repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\pojotocsv\BeanToCsv.java
1
请完成以下Java代码
public XMLGregorianCalendar getBirthDt() { return birthDt; } /** * Sets the value of the birthDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setBirthDt(XMLGregorianCalendar value) { this.birthDt = value; } /** * Gets the value of the prvcOfBirth property. * * @return * possible object is * {@link String } * */ public String getPrvcOfBirth() { return prvcOfBirth; } /** * Sets the value of the prvcOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setPrvcOfBirth(String value) { this.prvcOfBirth = value; } /** * Gets the value of the cityOfBirth property. * * @return * possible object is * {@link String } *
*/ public String getCityOfBirth() { return cityOfBirth; } /** * Sets the value of the cityOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setCityOfBirth(String value) { this.cityOfBirth = value; } /** * Gets the value of the ctryOfBirth property. * * @return * possible object is * {@link String } * */ public String getCtryOfBirth() { return ctryOfBirth; } /** * Sets the value of the ctryOfBirth property. * * @param value * allowed object is * {@link String } * */ public void setCtryOfBirth(String value) { this.ctryOfBirth = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DateAndPlaceOfBirth.java
1
请完成以下Java代码
public class AmzS3Config { /** * Amazon S3 的区域配置,例如 "us-west-2"。 * 该区域决定了 S3 存储桶的地理位置。 */ private String region; /** * Amazon S3 的端点 URL * 该端点用于访问 S3 服务。 */ private String endPoint; /** * Amazon S3 的域名 * 该域名用于构建访问 S3 服务的完整 URL。 */ private String domain; /** * Amazon S3 的访问密钥 ID,用于身份验证。 * 该密钥与 secretKey 一起使用来授权对 S3 服务的访问。 */ private String accessKey; /** * Amazon S3 的秘密访问密钥,用于身份验证。 * 该密钥与 accessKey 一起使用来授权对 S3 服务的访问。 */ private String secretKey;
/** * 默认的 S3 存储桶名称。 * 该存储桶用于存储上传的文件和数据。 */ private String defaultBucket; /** * 文件上传后存储的文件夹格式,默认为 "yyyy-MM"。 */ private String timeformat; /** * 创建并返回一个 AmazonS3 客户端实例。 * 使用当前配置类的 endPoint, region, accessKey 和 secretKey。 * 声明为 @Bean 后,Spring 会将其作为单例管理,并在需要时自动注入。 * * @return 配置好的 AmazonS3 客户端实例 */ @Bean public S3Client amazonS3Client() { return S3Client.builder().region(Region.of(region)) .endpointOverride(URI.create(endPoint)) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) .build(); } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\config\AmzS3Config.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String title; private BigDecimal price; private LocalDate publishDate; // for JPA only, no use public Book() { } public Book(String title, BigDecimal price, LocalDate publishDate) { this.title = title; this.price = price; this.publishDate = publishDate; } public Book(Long id, String title, BigDecimal price, LocalDate publishDate) { this.id = id; this.title = title; this.price = price; this.publishDate = publishDate; } @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", price=" + price + ", publishDate=" + publishDate + '}'; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public LocalDate getPublishDate() { return publishDate; } public void setPublishDate(LocalDate publishDate) { this.publishDate = publishDate; } }
repos\spring-boot-master\spring-boot-commandlinerunner\src\main\java\com\mkyong\book\Book.java
2
请完成以下Java代码
public class GetJobExceptionStacktraceCmd implements Command<String>, Serializable { private static final long serialVersionUID = 1L; private String jobId; protected JobType jobType; public GetJobExceptionStacktraceCmd(String jobId, JobType jobType) { this.jobId = jobId; this.jobType = jobType; } public String execute(CommandContext commandContext) { if (jobId == null) { throw new ActivitiIllegalArgumentException("jobId is null"); } AbstractJobEntity job = null; switch (jobType) { case ASYNC: job = commandContext.getJobEntityManager().findById(jobId); break; case TIMER: job = commandContext.getTimerJobEntityManager().findById(jobId); break;
case SUSPENDED: job = commandContext.getSuspendedJobEntityManager().findById(jobId); break; case DEADLETTER: job = commandContext.getDeadLetterJobEntityManager().findById(jobId); break; } if (job == null) { throw new ActivitiObjectNotFoundException("No job found with id " + jobId, Job.class); } return job.getExceptionStacktrace(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetJobExceptionStacktraceCmd.java
1
请完成以下Java代码
protected void createMailActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createMailActivityBehavior(serviceTask)); } protected void createMuleActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createMuleActivityBehavior(serviceTask)); } protected void createCamelActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createCamelActivityBehavior(serviceTask)); } protected void createShellActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createShellActivityBehavior(serviceTask)); } protected void createActivityBehaviorForCustomServiceTaskType(BpmnParse bpmnParse, ServiceTask serviceTask) { logger.warn( "Invalid service task type: '" + serviceTask.getType() + "' " + " for service task " + serviceTask.getId() ); } protected void createClassDelegateServiceTask(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createClassDelegateServiceTask(serviceTask)); } protected void createServiceTaskDelegateExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(
bpmnParse.getActivityBehaviorFactory().createServiceTaskDelegateExpressionActivityBehavior(serviceTask) ); } protected void createServiceTaskExpressionActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior( bpmnParse.getActivityBehaviorFactory().createServiceTaskExpressionActivityBehavior(serviceTask) ); } protected void createWebServiceActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createWebServiceActivityBehavior(serviceTask)); } protected void createDefaultServiceTaskActivityBehavior(BpmnParse bpmnParse, ServiceTask serviceTask) { serviceTask.setBehavior(bpmnParse.getActivityBehaviorFactory().createDefaultServiceTaskBehavior(serviceTask)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ServiceTaskParseHandler.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Parent. @param Parent_ID Parent of Entity */ @Override public void setParent_ID (int Parent_ID) { if (Parent_ID < 1) set_Value (COLUMNNAME_Parent_ID, null); else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent. @return Parent of Entity */ @Override public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Permission Issuer. @param PermissionIssuer Permission Issuer */ @Override public void setPermissionIssuer (java.lang.String PermissionIssuer) { set_Value (COLUMNNAME_PermissionIssuer, PermissionIssuer); } /** Get Permission Issuer. @return Permission Issuer */ @Override public java.lang.String getPermissionIssuer () { return (java.lang.String)get_Value(COLUMNNAME_PermissionIssuer); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Root Entry. @param Root_ID Root Entry */ @Override public void setRoot_ID (int Root_ID) { if (Root_ID < 1)
set_Value (COLUMNNAME_Root_ID, null); else set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID)); } /** Get Root Entry. @return Root Entry */ @Override public int getRoot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java
1
请完成以下Java代码
public class MigrationToXML extends JavaProcess { private int migrationId = 0; private String fileName; @Override protected void prepare() { for (ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameterName().equals("AD_Migration_ID")) { migrationId = para.getParameterAsInt(); } else if (para.getParameterName().equals("FileName")) { fileName = (String)para.getParameter(); } } // if run from Migration window if (migrationId <= 0 && I_AD_Migration.Table_Name.equals(getTableName())) {
migrationId = getRecord_ID(); } log.debug("AD_Migration_ID = " + migrationId + ", filename = " + fileName); } @Override protected String doIt() throws Exception { final I_AD_Migration migration = InterfaceWrapperHelper.create(getCtx(), migrationId, I_AD_Migration.class, get_TrxName()); final XMLWriter writer = new XMLWriter(fileName); writer.write(migration); return "Exported migration to: " + fileName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationToXML.java
1
请在Spring Boot框架中完成以下Java代码
public List<Citizen> findAll() { if (!encryptionConfig.isAutoDecryption()) { List<EncryptedCitizen> allEncrypted = mongo.findAll(EncryptedCitizen.class); return allEncrypted.stream() .map(this::decrypt) .collect(Collectors.toList()); } else { return mongo.findAll(Citizen.class); } } public Citizen findByEmail(String email) { Criteria emailCriteria = Criteria.where("email"); if (encryptionConfig.isAutoEncryption()) { emailCriteria.is(email); } else { emailCriteria .is(encrypt(email, DETERMINISTIC_ALGORITHM)); } Query byEmail = new Query(emailCriteria); if (encryptionConfig.isAutoDecryption()) { return mongo.findOne(byEmail, Citizen.class); } else { EncryptedCitizen encryptedCitizen = mongo.findOne(byEmail, EncryptedCitizen.class); return decrypt(encryptedCitizen); } } public Binary encrypt(BsonValue bsonValue, String algorithm) { Objects.requireNonNull(bsonValue); Objects.requireNonNull(algorithm); EncryptOptions options = new EncryptOptions(algorithm); options.keyId(encryptionConfig.getDataKeyId()); BsonBinary encryptedValue = clientEncryption.encrypt(bsonValue, options); return new Binary(encryptedValue.getType(), encryptedValue.getData()); } public Binary encrypt(String value, String algorithm) { Objects.requireNonNull(value); Objects.requireNonNull(algorithm); return encrypt(new BsonString(value), algorithm);
} public Binary encrypt(Integer value, String algorithm) { Objects.requireNonNull(value); Objects.requireNonNull(algorithm); return encrypt(new BsonInt32(value), algorithm); } public BsonValue decryptProperty(Binary value) { Objects.requireNonNull(value); return clientEncryption.decrypt(new BsonBinary(value.getType(), value.getData())); } private Citizen decrypt(EncryptedCitizen encrypted) { Objects.requireNonNull(encrypted); Citizen citizen = new Citizen(); citizen.setName(encrypted.getName()); BsonValue decryptedBirthYear = encrypted.getBirthYear() != null ? decryptProperty(encrypted.getBirthYear()) : null; if (decryptedBirthYear != null) { citizen.setBirthYear(decryptedBirthYear.asInt32().intValue()); } BsonValue decryptedEmail = encrypted.getEmail() != null ? decryptProperty(encrypted.getEmail()) : null; if (decryptedEmail != null) { citizen.setEmail(decryptedEmail.asString().getValue()); } return citizen; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-3\src\main\java\com\baeldung\boot\csfle\service\CitizenService.java
2
请完成以下Java代码
public InjectedPlanItemInstanceBuilder caseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; return this; } @Override public InjectedPlanItemInstanceBuilder elementId(String elementId) { this.elementId = elementId; return this; } @Override public PlanItemInstance createInStage(String stagePlanItemInstanceId) { validateData(); this.stagePlanItemInstanceId = stagePlanItemInstanceId; return commandExecutor.execute(new CreateInjectedPlanItemInstanceCmd(this)); } @Override public PlanItemInstance createInCase(String caseInstanceId) { validateData(); this.caseInstanceId = caseInstanceId; return commandExecutor.execute(new CreateInjectedPlanItemInstanceCmd(this)); } protected void validateData() { if (caseDefinitionId == null) { throw new FlowableIllegalArgumentException("The case definition id must be provided for the plan item instance"); } if (elementId == null) { throw new FlowableIllegalArgumentException("The element id must be provided for the plan item instance"); } } public boolean injectInStage() { return stagePlanItemInstanceId != null; } public boolean injectInCase() {
return caseInstanceId != null; } public String getStagePlanItemInstanceId() { return stagePlanItemInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public String getName() { return name; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getElementId() { return elementId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\InjectedPlanItemInstanceBuilderImpl.java
1
请完成以下Java代码
public void stop() { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } private static class EchoClientHandler extends Thread { private Socket clientSocket; private PrintWriter out; private BufferedReader in; public EchoClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { try { out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (".".equals(inputLine)) { out.println("bye"); break; } out.println(inputLine); } in.close();
out.close(); clientSocket.close(); } catch (IOException e) { LOG.debug(e.getMessage()); } } } public static void main(String[] args) { EchoMultiServer server = new EchoMultiServer(); server.start(5555); } }
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\socket\EchoMultiServer.java
1
请完成以下Java代码
public void setIsArchiveFile (final boolean IsArchiveFile) { set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile); } @Override public boolean isArchiveFile() { return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile); } @Override public void setIsReceipt (final boolean IsReceipt) { set_Value (COLUMNNAME_IsReceipt, IsReceipt); } @Override public boolean isReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsReceipt); } @Override public void setIsReconciled (final boolean IsReconciled) { set_Value (COLUMNNAME_IsReconciled, IsReconciled); } @Override public boolean isReconciled() { return get_ValueAsBoolean(COLUMNNAME_IsReconciled); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } @Override
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { throw new IllegalArgumentException ("Processing is virtual column"); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
1
请完成以下Java代码
public class SyncFuture<V> implements Future<V> { private V result; private Throwable e; public SyncFuture(V result) { this.result = result; } public SyncFuture(Throwable e) { this.e = e; } public boolean cancel(boolean mayInterruptIfRunning) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return true;
} public V get() throws InterruptedException, ExecutionException { if(e==null) { return result; } else { throw new ExecutionException(e); } } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\SyncFuture.java
1
请完成以下Java代码
public class DocxNaiveTextReplacer { public void replaceText() throws IOException { String filePath = getClass().getClassLoader() .getResource("baeldung-copy.docx") .getPath(); try (InputStream inputStream = new FileInputStream(filePath)) { XWPFDocument doc = new XWPFDocument(inputStream); doc = replaceText(doc, "Baeldung", "Hello"); saveFile(filePath, doc); doc.close(); } } private XWPFDocument replaceText(XWPFDocument doc, String originalText, String updatedText) { replaceTextInParagraphs(doc.getParagraphs(), originalText, updatedText); for (XWPFTable tbl : doc.getTables()) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { replaceTextInParagraphs(cell.getParagraphs(), originalText, updatedText); } } } return doc; } private void replaceTextInParagraphs(List<XWPFParagraph> paragraphs, String originalText, String updatedText) { paragraphs.forEach(paragraph -> replaceTextInParagraph(paragraph, originalText, updatedText)); } private void replaceTextInParagraph(XWPFParagraph paragraph, String originalText, String updatedText) {
List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { String text = run.getText(0); if (text != null && text.contains(originalText)) { String updatedRunText = text.replace(originalText, updatedText); run.setText(updatedRunText, 0); } } } private void saveFile(String filePath, XWPFDocument doc) throws IOException { try (FileOutputStream out = new FileOutputStream(filePath)) { doc.write(out); } } }
repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\replacevariables\DocxNaiveTextReplacer.java
1
请在Spring Boot框架中完成以下Java代码
public void insert(HistoryJobEntity jobEntity, boolean fireCreateEvent) { doInsert(jobEntity, fireCreateEvent); } protected boolean doInsert(HistoryJobEntity jobEntity, boolean fireCreateEvent) { jobEntity.setCreateTime(getClock().getCurrentTime()); super.insert(jobEntity, fireCreateEvent); return true; } @Override public List<HistoryJob> findHistoryJobsByQueryCriteria(HistoryJobQueryImpl jobQuery) { return dataManager.findHistoryJobsByQueryCriteria(jobQuery); } @Override public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) { return dataManager.findHistoryJobCountByQueryCriteria(jobQuery); } @Override public void delete(HistoryJobEntity jobEntity) { super.delete(jobEntity, false);
deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getAdvancedJobHandlerConfigurationByteArrayRef()); deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // Send event FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity), serviceConfiguration.getEngineName()); } } @Override public void deleteNoCascade(HistoryJobEntity historyJobEntity) { super.delete(historyJobEntity); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityManagerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> delete(@RequestParam(name = "id", required = true) String id) { service.removeById(id); return Result.ok("删除成功!"); } /** * 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.service.removeByIds(Arrays.asList(ids.split(","))); return Result.ok("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */
@GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { OpenApiAuth openApiAuth = service.getById(id); return Result.ok(openApiAuth); } /** * 生成AKSK * @return */ @GetMapping("genAKSK") public Result<String[]> genAKSK() { return Result.ok(AKSKGenerator.genAKSKPair()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiAuthController.java
2
请在Spring Boot框架中完成以下Java代码
public class Group { @Id private Long id; private String name; @ManyToMany(fetch = FetchType.EAGER) private List<User> members; public Group() { } public Long getId() { return this.id; } public String getName() { return this.name; } public List<User> getMembers() { return this.members; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; }
public void setMembers(List<User> members) { this.members = members; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Group group = (Group) o; return Objects.equals(id, group.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Group(id=" + this.getId() + ", name=" + this.getName() + ", members=" + this.getMembers() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\eager\list\moderatedomain\Group.java
2
请完成以下Java代码
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest)request; final AuthResolution authResolution = getAuthResolution(httpRequest); if (authResolution.isDoNotAuthenticate()) { chain.doFilter(request, response); } else { final HttpServletResponse httpResponse = (HttpServletResponse)response; try { userAuthTokenService.run( () -> extractTokenStringIfAvailable(httpRequest), authResolution, () -> { extractAdLanguage(httpRequest).ifPresent(Env::setAD_Language); chain.doFilter(httpRequest, httpResponse); }); } catch (final UserNotAuthorizedException ex) { httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getLocalizedMessage()); } } } private AuthResolution getAuthResolution(@NonNull final HttpServletRequest httpRequest) { // don't check auth for OPTIONS method calls because this causes troubles on chrome preflight checks if ("OPTIONS".equals(httpRequest.getMethod())) { return AuthResolution.DO_NOT_AUTHENTICATE; } return configuration.getAuthResolution(httpRequest).orElse(AuthResolution.AUTHENTICATION_REQUIRED); } @Nullable private static String extractTokenStringIfAvailable(final HttpServletRequest httpRequest) { // // Check Authorization header first { final String authorizationString = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_Authorization)); if (authorizationString != null) {
if (authorizationString.startsWith("Token ")) { return authorizationString.substring(5).trim(); } else if (authorizationString.startsWith("Basic ")) { final String userAndTokenString = new String(DatatypeConverter.parseBase64Binary(authorizationString.substring(5).trim())); final int index = userAndTokenString.indexOf(':'); return userAndTokenString.substring(index + 1); } else { return authorizationString; } } } // // Check apiKey query parameter { return StringUtils.trimBlankToNull(httpRequest.getParameter(QUERY_PARAM_API_KEY)); } } @VisibleForTesting Optional<String> extractAdLanguage(@NonNull final HttpServletRequest httpRequest) { final String acceptLanguageHeader = StringUtils.trimBlankToNull(httpRequest.getHeader(HEADER_AcceptLanguage)); final ADLanguageList availableLanguages = languageDAO.retrieveAvailableLanguages(); final String adLanguage = availableLanguages.getAD_LanguageFromHttpAcceptLanguage(acceptLanguageHeader, availableLanguages.getBaseADLanguage()); return Optional.ofNullable(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class DistributionNetworkLineId implements RepoIdAware { int repoId; private DistributionNetworkLineId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "DD_NetworkDistributionLine_ID"); } @JsonCreator public static DistributionNetworkLineId ofRepoId(final int repoId) { return new DistributionNetworkLineId(repoId); } public static DistributionNetworkLineId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new DistributionNetworkLineId(repoId) : null; } public static Optional<DistributionNetworkLineId> optionalOfRepoId(@Nullable final Integer repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); }
public static int toRepoId(final DistributionNetworkLineId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(final DistributionNetworkLineId o1, final DistributionNetworkLineId o2) { return Objects.equals(o1, o2); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\material\planning\ddorder\DistributionNetworkLineId.java
2
请完成以下Java代码
public static int toRepoId(@Nullable final HUPIItemProductId id) { return id != null ? id.getRepoId() : -1; } public static int toRepoIdVirtualToZero(@Nullable final HUPIItemProductId id) { return id != null && !id.isVirtualHU() ? id.getRepoId() : -1; } public static boolean isRegular(@Nullable final HUPIItemProductId id) { return id != null && id.isRegular(); } public static final HUPIItemProductId TEMPLATE_HU = new HUPIItemProductId(100); public static final HUPIItemProductId VIRTUAL_HU = new HUPIItemProductId(101); int repoId; private HUPIItemProductId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_PI_Item_Product_ID"); } @JsonValue @Override public int getRepoId() { return repoId;
} public static boolean equals(@Nullable final HUPIItemProductId id1, @Nullable final HUPIItemProductId id2) { return Objects.equals(id1, id2); } public static HUPIItemProductId nullToVirtual(final HUPIItemProductId id) { return id != null ? id : VIRTUAL_HU; } public boolean isVirtualHU() { return isVirtualHU(repoId); } public static boolean isVirtualHU(final int repoId) { return repoId == VIRTUAL_HU.repoId; } public boolean isRegular() { return repoId != VIRTUAL_HU.repoId && repoId != TEMPLATE_HU.repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HUPIItemProductId.java
1
请完成以下Java代码
public int getCRM_Occupation_Parent_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_Parent_ID); } /** * JobType AD_Reference_ID=541383 * Reference name: JobType */ public static final int JOBTYPE_AD_Reference_ID=541383; /** Job = B */ public static final String JOBTYPE_Job = "B"; /** Specialization = F */ public static final String JOBTYPE_Specialization = "F"; /** AdditionalSpecialization = Z */ public static final String JOBTYPE_AdditionalSpecialization = "Z"; @Override public void setJobType (final @Nullable java.lang.String JobType) { set_Value (COLUMNNAME_JobType, JobType); } @Override public java.lang.String getJobType() { return get_ValueAsString(COLUMNNAME_JobType); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name);
} @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CRM_Occupation.java
1
请完成以下Java代码
public BigDecimal getQtyEntered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered); if (bd == null) return Env.ZERO; return bd; } public org.compiere.model.I_M_InOutLine getRef_InOutLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getRef_InOutLine_ID(), get_TrxName()); } /** Set Referenced Shipment Line. @param Ref_InOutLine_ID Referenced Shipment Line */ public void setRef_InOutLine_ID (int Ref_InOutLine_ID) { if (Ref_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_Ref_InOutLine_ID, Integer.valueOf(Ref_InOutLine_ID)); } /** Get Referenced Shipment Line. @return Referenced Shipment Line */ public int getRef_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Ref_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InOutLine getReversalLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getReversalLine_ID(), get_TrxName()); } /** Set Reversal Line. @param ReversalLine_ID Use to keep the reversal line ID for reversing costing purpose */ public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null); else set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Reversal Line. @return Use to keep the reversal line ID for reversing costing purpose */ public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Verworfene Menge. @param ScrappedQty Durch QA verworfene Menge */ public void setScrappedQty (BigDecimal ScrappedQty) { set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty); } /** Get Verworfene Menge. @return Durch QA verworfene Menge */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Zielmenge. @param TargetQty Zielmenge der Warenbewegung */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Zielmenge. @return Zielmenge der Warenbewegung */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java
1
请完成以下Spring Boot application配置
server.port=8000 spring.mail.host=smtp.qq.com spring.mail.username=xxx@qq.com spring.mail.password= spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.boot.admin.notify.mail.from=
xx@qq.com spring.boot.admin.notify.mail.to=xxx@qq.com spring.security.user.name= admin spring.security.user.password= admin
repos\spring-boot-leaning-master\2.x_42_courses\第 5-3 课: Spring Boot Admin 的使用\spring-boot-admin\spring-boot-admin-server\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class CostDetailId implements RepoIdAware { @JsonCreator public static CostDetailId ofRepoId(final int repoId) { return new CostDetailId(repoId); } public static CostDetailId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new CostDetailId(repoId) : null; } public static int toRepoId(final CostDetailId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(final CostDetailId o1, final CostDetailId o2) { return Objects.equals(o1, o2); }
int repoId; private CostDetailId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_CostDetail_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailId.java
2
请在Spring Boot框架中完成以下Java代码
public class GlobalActionsDispatcher { private static final Logger logger = LogManager.getLogger(GlobalActionsDispatcher.class); private ImmutableMap<GlobalActionType, GlobalActionHandler> handlers; public GlobalActionsDispatcher(final Optional<List<GlobalActionHandler>> handlers) { if (handlers.isPresent()) { this.handlers = Maps.uniqueIndex(handlers.get(), GlobalActionHandler::getTypeHandled); logger.info("Registered handlers: {}", handlers); } else { this.handlers = ImmutableMap.of(); logger.warn("No handlers registered");
} } public GlobalActionHandlerResult dispatchEvent(@NonNull final GlobalActionEvent event) { return getHandler(event.getType()).handleEvent(event); } private GlobalActionHandler getHandler(final GlobalActionType type) { final GlobalActionHandler handler = handlers.get(type); if (handler == null) { throw new AdempiereException("No handler found for " + type); } return handler; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\globalaction\GlobalActionsDispatcher.java
2
请完成以下Java代码
private Result processInvoiceCandidates(@NonNull final Iterator<InvoiceCandidateId> invoiceCandidateIds) { int counter = 0; boolean anyException = false; while (invoiceCandidateIds.hasNext()) { final InvoiceCandidateId invoiceCandidateId = invoiceCandidateIds.next(); try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_Invoice_Candidate.Table_Name, invoiceCandidateId)) { trxManager.runInNewTrx(() -> { logger.debug("Processing invoiceCandidate"); final I_C_Invoice_Candidate invoiceCandidateRecord = invoiceCandDAO.getById(invoiceCandidateId); invoiceCandidateFacadeService.syncICToCommissionInstance(invoiceCandidateRecord, false/* candidateDeleted */); }); counter++; } catch (final RuntimeException e) { anyException = true;
final AdIssueId adIssueId = errorManager.createIssue(e); Loggables.withLogger(logger, Level.DEBUG) .addLog("C_Invoice_Candidate_ID={}: Caught {} and created AD_Issue_ID={}; exception-message={}", invoiceCandidateId.getRepoId(), e.getClass(), adIssueId.getRepoId(), e.getLocalizedMessage()); } } return new Result(counter, anyException); } @Value private static class Result { int counter; boolean anyException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\process\C_Invoice_Candidate_CreateOrUpdateCommissionInstance.java
1
请完成以下Java代码
public String getId() { return id; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskId() { return taskId; } public String getActivityId() { return activityId; }
public String getType() { return type; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getExecutionId() { return executionId; } public String getActivityInstanceId() { return activityInstanceId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricDetailQueryImpl.java
1
请完成以下Java代码
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, ServerWebExchange exchange) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return exchange.getSession() .doOnSuccess((session) -> { Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session); authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient); session.getAttributes().put(this.sessionAttributeName, authorizedClients); }) .then(Mono.empty()); // @formatter:on } @Override public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal, ServerWebExchange exchange) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return exchange.getSession() .doOnSuccess((session) -> { Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session); authorizedClients.remove(clientRegistrationId); if (authorizedClients.isEmpty()) {
session.getAttributes().remove(this.sessionAttributeName); } else { session.getAttributes().put(this.sessionAttributeName, authorizedClients); } }) .then(Mono.empty()); // @formatter:on } private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(WebSession session) { Assert.notNull(session, "session cannot be null"); Map<String, OAuth2AuthorizedClient> authorizedClients = session.getAttribute(this.sessionAttributeName); return (authorizedClients != null) ? authorizedClients : new HashMap<>(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\WebSessionServerOAuth2AuthorizedClientRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class WebLogAspect { private Logger logger = Logger.getLogger(getClass()); ThreadLocal<Long> startTime = new ThreadLocal<>(); @Pointcut("execution(public * com.boylegu.springboot_vue.controller..*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
} @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { logger.info("RESPONSE : " + ret); logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get())); } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\config\WebLogAspect.java
2
请完成以下Java代码
public class GameAnnotatedByJsonFormat { private Long id; private String name; @JsonFormat(shape = Shape.NUMBER) private boolean paused; @JsonFormat(shape = Shape.NUMBER) private boolean over; public GameAnnotatedByJsonFormat() { } public GameAnnotatedByJsonFormat(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getName() {
return this.name; } public void setName(String name) { this.name = name; } public boolean isPaused() { return paused; } public void setPaused(boolean paused) { this.paused = paused; } public boolean isOver() { return over; } public void setOver(boolean over) { this.over = over; } }
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\booleanAsInt\GameAnnotatedByJsonFormat.java
1
请完成以下Java代码
private final boolean isTourInstanceAssignmentRequired(final I_M_DeliveryDay deliveryDay) { // Tour assignment (change) is not allowed if our delivery day is already processed if (deliveryDay.isProcessed()) { return false; } // // If Delivery Day has documents allocated to it, we really need to assign it to a tour final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); final boolean tourInstanceAssignmentRequired = deliveryDayDAO.hasAllocations(deliveryDay); return tourInstanceAssignmentRequired; } private ITourInstanceQueryParams createTourInstanceQueryParams(final I_M_DeliveryDay deliveryDay) { final ITourInstanceQueryParams tourInstanceMatchingParams = new PlainTourInstanceQueryParams(); tourInstanceMatchingParams.setM_Tour(deliveryDay.getM_Tour()); tourInstanceMatchingParams.setDeliveryDate(deliveryDay.getDeliveryDate()); return tourInstanceMatchingParams; } @Override
public void process(final I_M_Tour_Instance tourInstance) { Check.assumeNotNull(tourInstance, "tourInstance not null"); tourInstance.setProcessed(true); InterfaceWrapperHelper.save(tourInstance); } @Override public void unprocess(final I_M_Tour_Instance tourInstance) { Check.assumeNotNull(tourInstance, "tourInstance not null"); tourInstance.setProcessed(false); InterfaceWrapperHelper.save(tourInstance); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourInstanceBL.java
1
请完成以下Java代码
public <T extends TypedValue> T getVariable(String variableName) { TypedValue value = cachedVariables.getValueTyped(variableName); if(value == null) { if(execution != null) { value = runtimeService.getVariableTyped(execution.getId(), variableName); cachedVariables.put(variableName, value); } } return (T) value; } public void setVariable(String variableName, Object value) { cachedVariables.put(variableName, value); } public VariableMap getCachedVariables() { return cachedVariables; } @SuppressWarnings("unchecked") public <T extends TypedValue> T getVariableLocal(String variableName) { TypedValue value = cachedVariablesLocal.getValueTyped(variableName); if (value == null) { if (task != null) { value = taskService.getVariableLocalTyped(task.getId(), variableName); cachedVariablesLocal.put(variableName, value); } else if (execution != null) { value = runtimeService.getVariableLocalTyped(execution.getId(), variableName); cachedVariablesLocal.put(variableName, value); } } return (T) value; }
public void setVariableLocal(String variableName, Object value) { if (execution == null && task == null) { throw new ProcessEngineCdiException("Cannot set a local cached variable: neither a Task nor an Execution is associated."); } cachedVariablesLocal.put(variableName, value); } public VariableMap getCachedVariablesLocal() { return cachedVariablesLocal; } public void flushVariableCache() { if(task != null) { taskService.setVariablesLocal(task.getId(), cachedVariablesLocal); taskService.setVariables(task.getId(), cachedVariables); } else if(execution != null) { runtimeService.setVariablesLocal(execution.getId(), cachedVariablesLocal); runtimeService.setVariables(execution.getId(), cachedVariables); } else { throw new ProcessEngineCdiException("Cannot flush variable cache: neither a Task nor an Execution is associated."); } // clear variable cache after flush cachedVariables.clear(); cachedVariablesLocal.clear(); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\ScopedAssociation.java
1
请完成以下Java代码
public MRPQueryBuilder setAD_Client_ID(final Integer adClientId) { this._adClientId = adClientId; return this; } private int getAD_Client_ID_ToUse() { if (_adClientId != null) { return _adClientId; } return -1; } @Override public MRPQueryBuilder setAD_Org_ID(final Integer adOrgId) { this._adOrgId = adOrgId; return this; } private int getAD_Org_ID_ToUse() { if (_adOrgId != null) { return _adOrgId; } return -1; } @Override public MRPQueryBuilder setM_Warehouse_ID(final Integer warehouseId) { this._warehouseId = warehouseId; return this; } private int getM_Warehouse_ID_ToUse() { if (_warehouseId != null) { return _warehouseId; } return -1; } @Override public MRPQueryBuilder setPP_Plant_ID(final Integer ppPlantId) { this._ppPlantId = ppPlantId; return this; } private Set<Integer> getPP_Plant_IDs_ToUse() { int ppPlantId = -1; if (_ppPlantId != null) { ppPlantId = _ppPlantId; } if (ppPlantId <= 0) { return Collections.emptySet(); } final Set<Integer> plantIds = new HashSet<>(); plantIds.add(ppPlantId); plantIds.add(null); return plantIds; } @Override public MRPQueryBuilder setM_Product_ID(final Integer productId) { this._productId = productId; return this; } private int getM_Product_ID_ToUse() { if (_productId != null) {
return _productId; } return -1; } @Override public MRPQueryBuilder setTypeMRP(final String typeMRP) { this._typeMRP = typeMRP; return this; } public String getTypeMRP() { return _typeMRP; } @Nullable public Date getDatePromisedMax() { return this._datePromisedMax; } @Nullable public MRPFirmType getMRPFirmType() { return this._mrpFirmType; } public boolean isQtyNotZero() { return false; } @Nullable public Boolean getMRPAvailable() { return _mrpAvailable; } public boolean isOnlyActiveRecords() { return _onlyActiveRecords; } @Override public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords) { this._onlyActiveRecords = onlyActiveRecords; return this; } @Override public MRPQueryBuilder setOrderType(final String orderType) { this._orderTypes.clear(); if (orderType != null) { this._orderTypes.add(orderType); } return this; } private Set<String> getOrderTypes() { return this._orderTypes; } @Override public MRPQueryBuilder setReferencedModel(final Object referencedModel) { this._referencedModel = referencedModel; return this; } public Object getReferencedModel() { return this._referencedModel; } @Override public void setPP_Order_BOMLine_Null() { this._ppOrderBOMLine_Null = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java
1
请完成以下Java代码
public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue) { set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue); } /** Set System-Problem. @param AD_Issue_ID Automatically created or manually entered System Issue */ @Override public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } /** Get System-Problem. @return Automatically created or manually entered System Issue */ @Override public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java-Klasse. @param Classname Java-Klasse */ @Override public void setClassname (java.lang.String Classname) { set_ValueNoCheck (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Fehler. @param IsError Ein Fehler ist bei der Durchführung aufgetreten */ @Override public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return Ein Fehler ist bei der Durchführung aufgetreten */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message
*/ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
1
请完成以下Java代码
public void setM_Lot_ID (int M_Lot_ID) { if (M_Lot_ID < 1) set_Value (COLUMNNAME_M_Lot_ID, null); else set_Value (COLUMNNAME_M_Lot_ID, Integer.valueOf(M_Lot_ID)); } /** Get Los. @return Product Lot Definition */ @Override public int getM_Lot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Lot_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Serien-Nr.. @param SerNo Product Serial Number */ @Override public void setSerNo (java.lang.String SerNo) { set_Value (COLUMNNAME_SerNo, SerNo); } /** Get Serien-Nr.. @return Product Serial Number */ @Override public java.lang.String getSerNo () { return (java.lang.String)get_Value(COLUMNNAME_SerNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetInstance.java
1
请完成以下Java代码
public static BigDecimal randomBigDecimal( final BigDecimal valueMin, final BigDecimal valueMax, final int scale) { final BigDecimal range = valueMax.subtract(valueMin); final BigDecimal random = BigDecimal.valueOf(Math.random()); return valueMin .add(random.multiply(range)) .setScale(scale, RoundingMode.DOWN); } @Nullable public static Integer graterThanZeroOrNull(@Nullable final Integer value) { return Optional.ofNullable(value) .filter(v1 -> v1 > 0) .orElse(null); } public static boolean isZeroOrNull(@Nullable final BigDecimal value) { if (value == null) { return true; } else return value.compareTo(BigDecimal.ZERO) == 0; } @NonNull public static String toStringWithCustomDecimalSeparator(@NonNull final BigDecimal value, final char separator) { final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(separator); final int scale = value.scale(); final String format; if (scale > 0) { final StringBuilder formatBuilder = new StringBuilder("0."); IntStream.range(0, scale) .forEach(ignored -> formatBuilder.append("0")); format = formatBuilder.toString(); } else { format = "0"; } final DecimalFormat formatter = new DecimalFormat(format, symbols); return formatter.format(value);
} @Nullable public static BigDecimal zeroToNull(@Nullable final BigDecimal value) { return value != null && value.signum() != 0 ? value : null; } public static boolean equalsByCompareTo(@Nullable final BigDecimal value1, @Nullable final BigDecimal value2) { //noinspection NumberEquality return (value1 == value2) || (value1 != null && value1.compareTo(value2) == 0); } @SafeVarargs public static int firstNonZero(final Supplier<Integer>... suppliers) { if (suppliers == null || suppliers.length == 0) { return 0; } for (final Supplier<Integer> supplier : suppliers) { if (supplier == null) { continue; } final Integer value = supplier.get(); if (value != null && value != 0) { return value; } } return 0; } @NonNull public static BigDecimal roundTo5Cent(@NonNull final BigDecimal initialValue) { final BigDecimal multiplyBy20 = initialValue.multiply(TWENTY); final BigDecimal intPart = multiplyBy20.setScale(0, RoundingMode.HALF_UP); return intPart.divide(TWENTY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\NumberUtils.java
1
请完成以下Java代码
public static ApplicationProtocolNegotiationHandler getServerAPNHandler() { ApplicationProtocolNegotiationHandler serverAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ctx.pipeline() .addLast(Http2FrameCodecBuilder.forServer() .build(), new Http2ServerResponseHandler()); return; } throw new IllegalStateException("Protocol: " + protocol + " not supported"); } }; return serverAPNHandler; } public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) { final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class); final Http2Connection connection = new DefaultHttp2Connection(false); HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder() .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength) .propagateSettings(true) .build())) .frameLogger(logger) .connection(connection) .build(); ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ChannelPipeline p = ctx.pipeline(); p.addLast(connectionHandler); p.addLast(settingsHandler, responseHandler); return; } ctx.close(); throw new IllegalStateException("Protocol: " + protocol + " not supported");
} }; return clientAPNHandler; } public static FullHttpRequest createGetRequest(String host, int port) { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER); request.headers() .add(HttpHeaderNames.HOST, new String(host + ":" + port)); request.headers() .add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS); request.headers() .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers() .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); return request; } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\Http2Util.java
1
请在Spring Boot框架中完成以下Java代码
public class FurtherIdentificationType { @XmlValue protected String value; @XmlAttribute(name = "IdentificationType", namespace = "http://erpel.at/schemas/1p0/documents", required = true) protected String identificationType; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Used to identify the type of further information. Currently, the following identification types are used: * AdditionalInternalDestination ... Additional destination, mostly provided in a LOC+159 segment * DUNS ... DUNS-number * FiscalNumber ... fiscal number of party * GLN ... Global Location Number/ILN * IssuedBySupplier ... ID given by supplier * IssuedByCustomer ... ID given by customer * Location ... physical location * Odette ... ID assigned by ODETTE
* PlantCode ... plant code * StorageLocation ... storage within location * StorageCell ... most fine-grained location id (actual shelf / storage bin) * TribunalPlaceRegistrationNumber ... Tribunal place registration number (GS1 Code) * UnloadingPoint ... unloading point * ZZZ ... mutually defined ID by both parties * * * @return * possible object is * {@link String } * */ public String getIdentificationType() { return identificationType; } /** * Sets the value of the identificationType property. * * @param value * allowed object is * {@link String } * */ public void setIdentificationType(String value) { this.identificationType = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\FurtherIdentificationType.java
2
请在Spring Boot框架中完成以下Java代码
public class PmsOperatorRole extends PermissionBaseEntity { private static final long serialVersionUID = 174356028197753020L; private Long roleId;// 角色ID private Long operatorId;// /操作员ID /** * 角色ID * * @return */ public Long getRoleId() { return roleId; } /** * 角色ID * * @return */ public void setRoleId(Long roleId) { this.roleId = roleId; }
/** * 操作员ID * * @return */ public Long getOperatorId() { return operatorId; } /** * 操作员ID * * @return */ public void setOperatorId(Long operatorId) { this.operatorId = operatorId; } public PmsOperatorRole() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperatorRole.java
2
请完成以下Java代码
public class BoundarySignalEventActivityBehavior extends BoundaryEventActivityBehavior { private static final long serialVersionUID = 1L; protected SignalEventDefinition signalEventDefinition; protected Signal signal; public BoundarySignalEventActivityBehavior( SignalEventDefinition signalEventDefinition, Signal signal, boolean interrupting ) { super(interrupting); this.signalEventDefinition = signalEventDefinition; this.signal = signal; } @Override public void execute(DelegateExecution execution) { CommandContext commandContext = Context.getCommandContext(); ExecutionEntity executionEntity = (ExecutionEntity) execution; String signalName = null; if (StringUtils.isNotEmpty(signalEventDefinition.getSignalRef())) { signalName = signalEventDefinition.getSignalRef(); } else { Expression signalExpression = commandContext .getProcessEngineConfiguration() .getExpressionManager() .createExpression(signalEventDefinition.getSignalExpression()); signalName = signalExpression.getValue(execution).toString(); } commandContext.getEventSubscriptionEntityManager().insertSignalEvent(signalName, signal, executionEntity); } @Override public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = (ExecutionEntity) execution; BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement(); if (boundaryEvent.isCancelActivity()) { String eventName = null; if (signal != null) { eventName = signal.getName(); } else { eventName = signalEventDefinition.getSignalRef(); } EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof SignalEventSubscriptionEntity && eventSubscription.getEventName().equals(eventName) ) { eventSubscriptionEntityManager.delete(eventSubscription); } } } super.trigger(executionEntity, triggerName, triggerData); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BoundarySignalEventActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public void insertNewBook() { Author author = authorRepository.fetchByName("Joana Nimar"); Book book = new Book(); book.setIsbn("004-JN"); book.setTitle("History Details"); author.addBook(book); // use addBook() helper authorRepository.save(author); } @Transactional public void deleteLastBook() {
Author author = authorRepository.fetchByName("Joana Nimar"); List<Book> books = author.getBooks(); author.removeBook(books.get(books.size() - 1)); } @Transactional public void deleteFirstBook() { Author author = authorRepository.fetchByName("Joana Nimar"); List<Book> books = author.getBooks(); author.removeBook(books.get(0)); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOneToManyUnidirectional\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public JwtDecoder jwtDecoder(RSAKey rsaKey) throws Exception { return NimbusJwtDecoder.withPublicKey(rsaKey.toRSAPublicKey()).build(); } @Bean public JwtEncoder jwtEncoder(RSAKey rsaKey) throws Exception { return NimbusJwtEncoder.withKeyPair(rsaKey.toRSAPublicKey(), rsaKey.toRSAPrivateKey()).build(); } /** * This is usually not necessary and oauth2-resource-server config works out-of-the-box, * but we need to support "Token" scheme in addition to "Bearer" scheme. * * @see org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver */ @Bean public BearerTokenResolver bearerTokenResolver() { return new BearerTokenResolver() { private static final Pattern pattern = Pattern.compile("^(Bearer|Token) (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE);
@Override public String resolve(HttpServletRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); if (authorization == null) { return null; } Matcher matcher = pattern.matcher(authorization); if (!matcher.matches()) { BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } }; } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\config\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Settings getSettings() { return this.settings; } public static class Settings { /** * Whether to enable trace output. */ private boolean trace; /** * Whether to enable remote access. */ private boolean webAllowOthers; /** * Password to access preferences and tools of H2 Console. */ private @Nullable String webAdminPassword; public boolean isTrace() { return this.trace; } public void setTrace(boolean trace) { this.trace = trace; }
public boolean isWebAllowOthers() { return this.webAllowOthers; } public void setWebAllowOthers(boolean webAllowOthers) { this.webAllowOthers = webAllowOthers; } public @Nullable String getWebAdminPassword() { return this.webAdminPassword; } public void setWebAdminPassword(@Nullable String webAdminPassword) { this.webAdminPassword = webAdminPassword; } } }
repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleProperties.java
2
请完成以下Java代码
public final class StringUtil { private static final Pattern pattern = Pattern.compile("(\\w[^,]*)|([#$]\\{[^}]*})"); /** * Splits a comma separated list in to single Strings. The list can * contain expressions with commas in it. * * @param text the comma separated list * @return the Strings of the list or an empty List if text is empty or null */ public static List<String> splitCommaSeparatedList(String text) { if (text == null || text.isEmpty()) { return Collections.emptyList(); } Matcher matcher = pattern.matcher(text); List<String> parts = new ArrayList<String>(); while(matcher.find()) { parts.add(matcher.group().trim()); } return parts; } /** * Joins a list of Strings to a comma separated single String. * * @param list the list to join * @return the resulting comma separated string or null if the list is null */ public static String joinCommaSeparatedList(List<String> list) { return joinList(list, ", "); } public static List<String> splitListBySeparator(String text, String separator) { String[] result = new String[]{}; if (text != null) { result = text.split(separator); } return new ArrayList<String>(Arrays.asList(result)); }
public static String joinList(List<String> list, String separator) { if (list == null) { return null; } int size = list.size(); if (size == 0) { return ""; } else if (size == 1) { return list.get(0); } else { StringBuilder builder = new StringBuilder(size * 8); builder.append(list.get(0)); for (Object element : list.subList(1, size)) { builder.append(separator); builder.append(element); } return builder.toString(); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\StringUtil.java
1
请完成以下Java代码
public void setIsReverted (final boolean IsReverted) { set_Value (COLUMNNAME_IsReverted, IsReverted); } @Override public boolean isReverted() { return get_ValueAsBoolean(COLUMNNAME_IsReverted); } @Override public org.compiere.model.I_M_Inventory getM_Inventory() { return get_ValueAsPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setM_Inventory(final org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } @Override public void setM_Inventory_ID (final int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, M_Inventory_ID); } @Override public int getM_Inventory_ID() { return get_ValueAsInt(COLUMNNAME_M_Inventory_ID); } @Override public org.compiere.model.I_M_InventoryLine getM_InventoryLine() { return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class); } @Override public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } @Override public void setM_InventoryLine_ID (final int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null);
else set_Value (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID); } @Override public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); } @Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public void setMD_Candidate_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID) { if (MD_Candidate_StockChange_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID); } @Override public int getMD_Candidate_StockChange_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
1
请完成以下Java代码
public void setExtensionProperties(Map<String, String> extensionProperties) { this.extensionProperties = extensionProperties; } @JsonIgnore @Override public String getExtensionProperty(String propertyKey) { if(extensionProperties != null) { return extensionProperties.get(propertyKey); } return null; } @Override public String toString() { return "ExternalTaskImpl [" + "activityId=" + activityId + ", " + "activityInstanceId=" + activityInstanceId + ", " + "businessKey=" + businessKey + ", " + "errorDetails=" + errorDetails + ", " + "errorMessage=" + errorMessage + ", " + "executionId=" + executionId + ", " + "id=" + id + ", " + formatTimeField("lockExpirationTime", lockExpirationTime) + ", " + formatTimeField("createTime", createTime) + ", " + "priority=" + priority + ", " + "processDefinitionId=" + processDefinitionId + ", " + "processDefinitionKey=" + processDefinitionKey + ", " + "processDefinitionVersionTag=" + processDefinitionVersionTag + ", "
+ "processInstanceId=" + processInstanceId + ", " + "receivedVariableMap=" + receivedVariableMap + ", " + "retries=" + retries + ", " + "tenantId=" + tenantId + ", " + "topicName=" + topicName + ", " + "variables=" + variables + ", " + "workerId=" + workerId + "]"; } protected String formatTimeField(String timeField, Date time) { return timeField + "=" + (time == null ? null : DateFormat.getDateTimeInstance().format(time)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskImpl.java
1
请完成以下Java代码
public List<I_C_RfQResponseLineQty> retrieveResponseQtys(final I_C_RfQResponseLine rfqResponseLine) { final List<I_C_RfQResponseLineQty> rfqResponseLineQtys = retrieveResponseQtysQuery(rfqResponseLine) .create() .list(I_C_RfQResponseLineQty.class); // optimization for (final I_C_RfQResponseLineQty rfqResponseLineQty : rfqResponseLineQtys) { rfqResponseLineQty.setC_RfQResponseLine(rfqResponseLine); } return rfqResponseLineQtys; } @Override public boolean hasResponseQtys(final I_C_RfQResponseLine rfqResponseLine) { return retrieveResponseQtysQuery(rfqResponseLine) .create() .anyMatch(); } @Override public I_C_RfQResponseLineQty retrieveResponseQty(final I_C_RfQResponseLine rfqResponseLine, final Date date) { Check.assumeNotNull(date, "date not null"); final Date day = TimeUtil.trunc(date, TimeUtil.TRUNC_DAY); final I_C_RfQResponseLineQty rfqResponseLineQty = retrieveResponseQtysQuery(rfqResponseLine) .addEqualsFilter(I_C_RfQResponseLineQty.COLUMN_DatePromised, day) .create() .firstOnly(I_C_RfQResponseLineQty.class); // optimization if (rfqResponseLineQty != null) { rfqResponseLineQty.setC_RfQResponseLine(rfqResponseLine); } return rfqResponseLineQty; } private IQueryBuilder<I_C_RfQResponseLineQty> retrieveResponseQtysQuery(final I_C_RfQResponseLine responseLine) { return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_RfQResponseLineQty.class, responseLine) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_RfQResponseLineQty.COLUMN_C_RfQResponseLine_ID, responseLine.getC_RfQResponseLine_ID()) .orderBy() .addColumn(I_C_RfQResponseLineQty.COLUMN_C_RfQResponseLineQty_ID) .endOrderBy(); } @Override public BigDecimal calculateQtyPromised(final I_C_RfQResponseLine rfqResponseLine) { final BigDecimal qtyPromised = retrieveResponseQtysQuery(rfqResponseLine) .create() .aggregate(I_C_RfQResponseLineQty.COLUMNNAME_QtyPromised, Aggregate.SUM, BigDecimal.class); if(qtyPromised == null) { return BigDecimal.ZERO; } return NumberUtils.stripTrailingDecimalZeros(qtyPromised); } @Override public boolean hasQtyRequiered(final I_C_RfQResponse rfqResponse) { return retrieveResponseLinesQuery(rfqResponse) .addNotEqualsFilter(I_C_RfQResponseLine.COLUMNNAME_QtyRequiered, BigDecimal.ZERO) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqDAO.java
1
请完成以下Java代码
public String getHitPolicyName() { return HitPolicy.OUTPUT_ORDER.getValue(); } @Override public void composeDecisionResults(final ELExecutionContext executionContext) { List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values()); boolean outputValuesPresent = false; for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) { List<Object> outputValues = entry.getValue(); if (outputValues != null && !outputValues.isEmpty()) { outputValuesPresent = true; break; } } if (!outputValuesPresent) { String hitPolicyViolatedMessage = String.format("HitPolicy: %s violated; no output values present", getHitPolicyName()); if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) { throw new FlowableException(hitPolicyViolatedMessage); } else { executionContext.getAuditContainer().setValidationMessage(hitPolicyViolatedMessage); } } // sort on predefined list(s) of output values ruleResults.sort((o1, o2) -> { CompareToBuilder compareToBuilder = new CompareToBuilder(); for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) { List<Object> outputValues = entry.getValue();
if (outputValues != null && !outputValues.isEmpty()) { compareToBuilder.append(o1.get(entry.getKey()), o2.get(entry.getKey()), new OutputOrderComparator<>(outputValues.toArray(new Comparable[outputValues.size()]))); compareToBuilder.toComparison(); } } return compareToBuilder.toComparison(); }); updateStackWithDecisionResults(ruleResults, executionContext); DecisionExecutionAuditContainer auditContainer = executionContext.getAuditContainer(); auditContainer.setDecisionResult(ruleResults); auditContainer.setMultipleResults(true); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyOutputOrder.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCouponId() { return couponId; } public void setCouponId(Long couponId) { this.couponId = couponId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getCouponCode() { return couponCode; } public void setCouponCode(String couponCode) { this.couponCode = couponCode; } public String getMemberNickname() { return memberNickname; } public void setMemberNickname(String memberNickname) { this.memberNickname = memberNickname; } public Integer getGetType() { return getType; } public void setGetType(Integer getType) { this.getType = getType; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getUseStatus() { return useStatus; }
public void setUseStatus(Integer useStatus) { this.useStatus = useStatus; } public Date getUseTime() { return useTime; } public void setUseTime(Date useTime) { this.useTime = useTime; } public Long getOrderId() { return orderId; } public void setOrderId(Long orderId) { this.orderId = orderId; } public String getOrderSn() { return orderSn; } public void setOrderSn(String orderSn) { this.orderSn = orderSn; } @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(", couponId=").append(couponId); sb.append(", memberId=").append(memberId); sb.append(", couponCode=").append(couponCode); sb.append(", memberNickname=").append(memberNickname); sb.append(", getType=").append(getType); sb.append(", createTime=").append(createTime); sb.append(", useStatus=").append(useStatus); sb.append(", useTime=").append(useTime); sb.append(", orderId=").append(orderId); sb.append(", orderSn=").append(orderSn); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponHistory.java
1
请在Spring Boot框架中完成以下Java代码
protected void validateDataImpl(TenantId tenantId, AssetProfile assetProfile) { validateString("Asset profile name", assetProfile.getName()); if (assetProfile.getTenantId() == null) { throw new DataValidationException("Asset profile should be assigned to tenant!"); } else { if (!tenantService.tenantExists(assetProfile.getTenantId())) { throw new DataValidationException("Asset profile is referencing to non-existent tenant!"); } } if (assetProfile.isDefault()) { AssetProfile defaultAssetProfile = assetProfileService.findDefaultAssetProfile(tenantId); if (defaultAssetProfile != null && !defaultAssetProfile.getId().equals(assetProfile.getId())) { throw new DataValidationException("Another default asset profile is present in scope of current tenant!"); } } if (StringUtils.isNotEmpty(assetProfile.getDefaultQueueName())) { Queue queue = queueService.findQueueByTenantIdAndName(tenantId, assetProfile.getDefaultQueueName()); if (queue == null) { throw new DataValidationException("Asset profile is referencing to non-existent queue!"); } } if (assetProfile.getDefaultRuleChainId() != null) { RuleChain ruleChain = ruleChainService.findRuleChainById(tenantId, assetProfile.getDefaultRuleChainId()); if (ruleChain == null) { throw new DataValidationException("Can't assign non-existent rule chain!"); }
if (!ruleChain.getTenantId().equals(assetProfile.getTenantId())) { throw new DataValidationException("Can't assign rule chain from different tenant!"); } } if (assetProfile.getDefaultDashboardId() != null) { DashboardInfo dashboard = dashboardService.findDashboardInfoById(tenantId, assetProfile.getDefaultDashboardId()); if (dashboard == null) { throw new DataValidationException("Can't assign non-existent dashboard!"); } if (!dashboard.getTenantId().equals(assetProfile.getTenantId())) { throw new DataValidationException("Can't assign dashboard from different tenant!"); } } } @Override protected AssetProfile validateUpdate(TenantId tenantId, AssetProfile assetProfile) { AssetProfile old = assetProfileDao.findById(assetProfile.getTenantId(), assetProfile.getId().getId()); if (old == null) { throw new DataValidationException("Can't update non existing asset profile!"); } return old; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\AssetProfileDataValidator.java
2
请在Spring Boot框架中完成以下Java代码
public class H2JpaConfig { @Autowired private Environment env; @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(new String[] { "com.baeldung.boot.domain" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } @Bean JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", env.getProperty("hibernate.globally_quoted_identifiers")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\boot\config\H2JpaConfig.java
2
请完成以下Java代码
private Optional<I_AD_Archive> getLastArchive(@NonNull final InvoiceId invoiceId) { return archiveBL.getLastArchiveRecord(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)); } @NonNull public JSONInvoiceInfoResponse getInvoiceInfo(@NonNull final InvoiceId invoiceId, final String ad_language) { final JSONInvoiceInfoResponse.JSONInvoiceInfoResponseBuilder result = JSONInvoiceInfoResponse.builder(); final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final CurrencyCode currency = currencyDAO.getCurrencyCodeById(CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final List<I_C_InvoiceLine> lines = invoiceDAO.retrieveLines(invoiceId); for (final I_C_InvoiceLine line : lines) { final String productName = productBL.getProductNameTrl(ProductId.ofRepoId(line.getM_Product_ID())).translate(ad_language); final Percent taxRate = taxDAO.getRateById(TaxId.ofRepoId(line.getC_Tax_ID())); result.lineInfo(JSONInvoiceLineInfo.builder() .lineNumber(line.getLine()) .productName(productName) .qtyInvoiced(line.getQtyEntered()) .price(line.getPriceEntered()) .taxRate(taxRate) .lineNetAmt(line.getLineNetAmt()) .currency(currency) .build()); } return result.build(); } @NonNull public Optional<JsonReverseInvoiceResponse> reverseInvoice(@NonNull final InvoiceId invoiceId) {
final I_C_Invoice documentRecord = invoiceDAO.getByIdInTrx(invoiceId); if (documentRecord == null) { return Optional.empty(); } documentBL.processEx(documentRecord, IDocument.ACTION_Reverse_Correct, IDocument.STATUS_Reversed); final JsonReverseInvoiceResponse.JsonReverseInvoiceResponseBuilder responseBuilder = JsonReverseInvoiceResponse.builder(); invoiceCandDAO .retrieveInvoiceCandidates(invoiceId) .stream() .map(this::buildJSONItem) .forEach(responseBuilder::affectedInvoiceCandidate); return Optional.of(responseBuilder.build()); } private JsonInvoiceCandidatesResponseItem buildJSONItem(@NonNull final I_C_Invoice_Candidate invoiceCandidate) { return JsonInvoiceCandidatesResponseItem .builder() .externalHeaderId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalHeaderId())) .externalLineId(JsonExternalId.ofOrNull(invoiceCandidate.getExternalLineId())) .metasfreshId(MetasfreshId.of(invoiceCandidate.getC_Invoice_Candidate_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\InvoiceService.java
1
请完成以下Java代码
public class DecisionRule extends DmnElement { protected List<RuleInputClauseContainer> inputEntries = new ArrayList<>(); protected List<RuleOutputClauseContainer> outputEntries = new ArrayList<>(); protected int ruleNumber; public List<RuleInputClauseContainer> getInputEntries() { return inputEntries; } public void addInputEntry(RuleInputClauseContainer inputEntry) { this.inputEntries.add(inputEntry); } public void setInputEntries(List<RuleInputClauseContainer> inputEntries) { this.inputEntries = inputEntries; } public List<RuleOutputClauseContainer> getOutputEntries() { return outputEntries; }
public void addOutputEntry(RuleOutputClauseContainer outputEntry) { this.outputEntries.add(outputEntry); } public void setOutputEntries(List<RuleOutputClauseContainer> outputEntries) { this.outputEntries = outputEntries; } public void setRuleNumber(int ruleNumber) { this.ruleNumber = ruleNumber; } public int getRuleNumber() { return ruleNumber; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DecisionRule.java
1
请完成以下Java代码
public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ 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 Times Dunned. @param TimesDunned Number of times dunned previously */ public void setTimesDunned (int TimesDunned) { set_Value (COLUMNNAME_TimesDunned, Integer.valueOf(TimesDunned)); }
/** Get Times Dunned. @return Number of times dunned previously */ public int getTimesDunned () { Integer ii = (Integer)get_Value(COLUMNNAME_TimesDunned); if (ii == null) return 0; return ii.intValue(); } /** Set Total Amount. @param TotalAmt Total Amount */ public void setTotalAmt (BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } /** Get Total Amount. @return Total Amount */ public BigDecimal getTotalAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRunLine.java
1
请完成以下Java代码
public LookupValue createAttachment( @NonNull final String emailId, @NonNull final String filename, @NonNull Resource fileContent) { final String attachmentId = UUID.randomUUID().toString(); // // Store it to internal attachments storage final File attachmentFile = getAttachmentFile(emailId, attachmentId); try(final FileOutputStream fileOutputStream = new FileOutputStream(attachmentFile)) { FileCopyUtils.copy(fileContent.getInputStream(), fileOutputStream); } catch (final IOException e) { throw new AdempiereException("Failed storing " + filename) .setParameter("filename", fileContent) .setParameter("attachmentFile", attachmentFile); } // return StringLookupValue.of(attachmentId, filename); } public byte[] getAttachmentAsByteArray(@NonNull final String emailId, @NonNull final LookupValue attachment) { final File attachmentFile = getAttachmentFile(emailId, attachment.getIdAsString()); return Util.readBytes(attachmentFile); }
public void deleteAttachments(@NonNull final String emailId, @NonNull final LookupValuesList attachmentsList) { attachmentsList.stream().forEach(attachment -> deleteAttachment(emailId, attachment)); } public void deleteAttachment(@NonNull final String emailId, @NonNull final LookupValue attachment) { final String attachmentId = attachment.getIdAsString(); final File attachmentFile = getAttachmentFile(emailId, attachmentId); if (!attachmentFile.exists()) { logger.debug("Attachment file {} is missing. Nothing to delete", attachmentFile); return; } if (!attachmentFile.delete()) { attachmentFile.deleteOnExit(); logger.warn("Cannot delete attachment file {}. Scheduled to be deleted on exit", attachmentFile); } else { logger.debug("Deleted attachment file {}", attachmentFile); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailAttachmentsRepository.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Zählbestand Einkauf (fresh). @param Fresh_QtyOnHand_ID Zählbestand Einkauf (fresh) */ @Override public void setFresh_QtyOnHand_ID (int Fresh_QtyOnHand_ID) { if (Fresh_QtyOnHand_ID < 1) set_ValueNoCheck (COLUMNNAME_Fresh_QtyOnHand_ID, null); else set_ValueNoCheck (COLUMNNAME_Fresh_QtyOnHand_ID, Integer.valueOf(Fresh_QtyOnHand_ID)); } /** Get Zählbestand Einkauf (fresh). @return Zählbestand Einkauf (fresh) */ @Override public int getFresh_QtyOnHand_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fresh_QtyOnHand_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand.java
1
请完成以下Java代码
public List<Model> findModelsByQueryCriteria(ModelQueryImpl query, Page page) { return modelDataManager.findModelsByQueryCriteria(query, page); } @Override public long findModelCountByQueryCriteria(ModelQueryImpl query) { return modelDataManager.findModelCountByQueryCriteria(query); } @Override public byte[] findEditorSourceByModelId(String modelId) { ModelEntity model = findById(modelId); if (model == null || model.getEditorSourceValueId() == null) { return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId()); return ref.getBytes(); } @Override public byte[] findEditorSourceExtraByModelId(String modelId) { ModelEntity model = findById(modelId); if (model == null || model.getEditorSourceExtraValueId() == null) { return null; } ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
return ref.getBytes(); } @Override public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return modelDataManager.findModelsByNativeQuery(parameterMap, firstResult, maxResults); } @Override public long findModelCountByNativeQuery(Map<String, Object> parameterMap) { return modelDataManager.findModelCountByNativeQuery(parameterMap); } public ModelDataManager getModelDataManager() { return modelDataManager; } public void setModelDataManager(ModelDataManager modelDataManager) { this.modelDataManager = modelDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityManagerImpl.java
1
请完成以下Java代码
public String[] getTenantIds() { return tenantIds; } public boolean isTenantIdSet() { return isTenantIdSet; } public BatchQuery withoutTenantId() { this.tenantIds = null; isTenantIdSet = true; return this; } public BatchQuery active() { this.suspensionState = SuspensionState.ACTIVE; return this; } public BatchQuery suspended() { this.suspensionState = SuspensionState.SUSPENDED; return this; } public SuspensionState getSuspensionState() { return suspensionState; } public BatchQuery orderById() { return orderBy(BatchQueryProperty.ID); } @Override public BatchQuery orderByTenantId() {
return orderBy(BatchQueryProperty.TENANT_ID); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getBatchManager() .findBatchCountByQueryCriteria(this); } public List<Batch> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getBatchManager() .findBatchesByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class CommissionTriggerService implements ICommissionTriggerService { private final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); private final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class); private final CommissionInstanceDAO commissionInstanceDAO; public CommissionTriggerService(final CommissionInstanceDAO commissionInstanceDAO) { this.commissionInstanceDAO = commissionInstanceDAO; } @Override public boolean isContainsCommissionTriggers(@NonNull final InvoiceId invoiceId) { final Set<SalesInvoiceLineDocumentId> invoiceLineIds = invoiceDAO.retrieveLines(invoiceId) .stream() .map(I_C_InvoiceLine::getC_InvoiceLine_ID) .map(invoiceLineId -> InvoiceAndLineId.ofRepoId(invoiceId, invoiceLineId)) .map(SalesInvoiceLineDocumentId::new) .collect(ImmutableSet.toImmutableSet());
final boolean linesSubjectToCommission = commissionInstanceDAO.isILsReferencedByCommissionInstances(invoiceLineIds); if (linesSubjectToCommission) { return true; } final List<I_C_Invoice_Candidate> invoiceCandidates = invoiceCandDAO.retrieveInvoiceCandidates(invoiceId); if (invoiceCandidates.isEmpty()) { return false; } final Set<SalesInvoiceCandidateDocumentId> invoiceCandIdSet = invoiceCandidates.stream() .map(I_C_Invoice_Candidate::getC_Invoice_Candidate_ID) .map(InvoiceCandidateId::ofRepoId) .map(SalesInvoiceCandidateDocumentId::new) .collect(ImmutableSet.toImmutableSet()); return commissionInstanceDAO.isICsReferencedByCommissionInstances(invoiceCandIdSet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionTriggerService.java
2
请完成以下Java代码
public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } public int getCounter() { return counter; } public void setCounter(int counter) { this.counter = counter; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(BUFFER_SIZE); } @Override public void onNext(String item) { buffer.add(item); // if buffer is full, process the items. if (buffer.size() >= BUFFER_SIZE) { processBuffer(); } //request more items. subscription.request(1); }
private void processBuffer() { if (buffer.isEmpty()) return; // Process all items in the buffer. Here, we just print it and sleep for 1 second. System.out.print("Processed items: "); buffer.stream() .forEach(item -> { System.out.print(" " + item); }); System.out.println(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } counter = counter + buffer.size(); buffer.clear(); } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onComplete() { completed = true; // process any remaining items in buffer before processBuffer(); subscription.cancel(); } }
repos\tutorials-master\core-java-modules\core-java-9-new-features\src\main\java\com\baeldung\java9\reactive\BaeldungBatchSubscriberImpl.java
1
请完成以下Java代码
public TableCalloutsMap getCallouts(final Properties ctx, final String tableName) { final TableCalloutsMap callouts = registeredCalloutsByTableId.get(tableName.toLowerCase()); return callouts == null ? TableCalloutsMap.EMPTY : callouts; } @Override public boolean registerCallout( @NonNull final String tableName, @NonNull final String columnName, @NonNull final ICalloutInstance callout) { final String tableNameToUse = tableName.toLowerCase(); // // Add the new callout to our internal map final AtomicBoolean registered = new AtomicBoolean(false); registeredCalloutsByTableId.compute(tableNameToUse, (tableNameKey, currentTabCalloutsMap) -> { if (currentTabCalloutsMap == null) { registered.set(true); return TableCalloutsMap.of(columnName, callout); } else { final TableCalloutsMap newTabCalloutsMap = currentTabCalloutsMap.compose(columnName, callout); registered.set(newTabCalloutsMap != currentTabCalloutsMap); return newTabCalloutsMap; } }); // Stop here if it was not registered if (!registered.get()) { return false; } logger.debug("Registered callout for {}.{}: {}", tableNameToUse, columnName, callout); // Make sure this provider is registered to ICalloutFactory. // We assume the factory won't register it twice. Services.get(ICalloutFactory.class).registerCalloutProvider(this);
return true; } @Override public boolean registerAnnotatedCallout(final Object annotatedCalloutObj) { final List<AnnotatedCalloutInstance> calloutInstances = new AnnotatedCalloutInstanceFactory() .setAnnotatedCalloutObject(annotatedCalloutObj) .create(); if (calloutInstances.isEmpty()) { throw new AdempiereException("No binding columns found for " + annotatedCalloutObj + " (class=" + annotatedCalloutObj.getClass() + ")"); } boolean registered = false; for (final AnnotatedCalloutInstance calloutInstance : calloutInstances) { final String tableName = calloutInstance.getTableName(); for (final String columnName : calloutInstance.getColumnNames()) { final boolean columNameRegistered = registerCallout(tableName, columnName, calloutInstance); if (columNameRegistered) { registered = true; } } } return registered; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\ProgramaticCalloutProvider.java
1
请完成以下Java代码
public class RouteDefinitionMetrics implements ApplicationListener<RefreshRoutesEvent> { private static final Log log = LogFactory.getLog(GatewayMetricsFilter.class); private final RouteDefinitionLocator routeLocator; private final AtomicInteger routeDefinitionCount; private final String metricsPrefix; public RouteDefinitionMetrics(MeterRegistry meterRegistry, RouteDefinitionLocator routeLocator, String metricsPrefix) { this.routeLocator = routeLocator; if (metricsPrefix.endsWith(".")) { this.metricsPrefix = metricsPrefix.substring(0, metricsPrefix.length() - 1); } else { this.metricsPrefix = metricsPrefix; } routeDefinitionCount = meterRegistry.gauge(this.metricsPrefix + ".routes.count", new AtomicInteger(0)); }
public String getMetricsPrefix() { return metricsPrefix; } @Override public void onApplicationEvent(RefreshRoutesEvent event) { routeLocator.getRouteDefinitions().count().subscribe(count -> { routeDefinitionCount.set(count.intValue()); if (log.isDebugEnabled()) { log.debug("New routes count: " + routeDefinitionCount); } }); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinitionMetrics.java
1
请在Spring Boot框架中完成以下Java代码
public String saveEmployee(@ModelAttribute ("employee") Employee employee){ // save employee to database employeeService.saveEmployee(employee); return "redirect:/"; } @GetMapping("/showFormForUpdate/{id}") public String showFormForUpdate(@PathVariable(value = "id") long id, Model model){ // get employee from the service Employee employee = employeeService.getEmployeeById(id); //set employee a model attribute to pre-population the form model.addAttribute("employee", employee); return "update_employee"; } @GetMapping("/deleteEmployee/{id}") public String deleteEmployee(@PathVariable (value = "id") long id) { // call delete employee method this.employeeService.deleteEmployeeById(id); return "redirect:/"; } @GetMapping("/page/{pageNo}") public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
@RequestParam("sortField") String sortField, @RequestParam("sortDir") String sortDir, Model model) { int pageSize = 5; Page<Employee> page = employeeService.findPaginated(pageNo, pageSize, sortField, sortDir); List<Employee> listEmployees = page.getContent(); model.addAttribute("currentPage", pageNo); model.addAttribute("totalPages", page.getTotalPages()); model.addAttribute("totalItems", page.getTotalElements()); model.addAttribute("sortField", sortField); model.addAttribute("sortDir", sortDir); model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc"); model.addAttribute("listEmployees", listEmployees); return "index"; } }
repos\Spring-Boot-Advanced-Projects-main\Registration-FullStack-Springboot\src\main\java\pagination\sort\controller\EmployeeController.java
2
请在Spring Boot框架中完成以下Java代码
public class MusicStoreService { @Autowired private MusicAlbumRepository albumRepository; @Autowired private CompilationRepository compilationRepository; @Autowired private StoreRepository storeRepository; @Autowired private MusicTrackRepository trackRepository; public MusicAlbum add(MusicAlbum item) { return albumRepository.save(item); } public List<MusicAlbum> getAlbumList() { return albumRepository.findAll(); } public Compilation add(Compilation item) { return compilationRepository.save(item); }
public List<Compilation> getCompilationList() { return compilationRepository.findAll(); } public Store add(Store item) { return storeRepository.save(item); } public List<Store> getStoreList() { return storeRepository.findAll(); } public MusicTrack add(MusicTrack item) { return trackRepository.save(item); } public List<MusicTrack> getTrackList() { return trackRepository.findAll(); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\collection\name\service\MusicStoreService.java
2
请完成以下Java代码
protected String doIt() throws Exception { final FTSConfigId ftsConfigId = FTSConfigId.ofRepoId(getRecord_ID()); final FTSConfig ftsConfig = ftsConfigService.getConfigById(ftsConfigId); deleteESIndexIfRequired(ftsConfig); enqueueModels(ftsConfig); return MSG_OK; } public void deleteESIndexIfRequired(final FTSConfig config) throws IOException { if (p_esDropIndex) { final String esIndexName = config.getEsIndexName(); elasticsearchSystem.elasticsearchClient() .indices() .delete(new DeleteIndexRequest(esIndexName), RequestOptions.DEFAULT); addLog("Elasticsearch index dropped: {}", esIndexName); } } private void enqueueModels(final FTSConfig ftsConfig) { final FTSConfigSourceTablesMap sourceTables = FTSConfigSourceTablesMap.ofList(ftsConfigService.getSourceTables().getByConfigId(ftsConfig.getId())); for (final TableName sourceTableName : sourceTables.getTableNames()) { enqueueModels(sourceTableName, sourceTables); } } private void enqueueModels( @NonNull final TableName sourceTableName,
@NonNull final FTSConfigSourceTablesMap sourceTablesMap) { final Stream<ModelToIndexEnqueueRequest> requestsStream = queryBL.createQueryBuilder(sourceTableName.getAsString()) .addOnlyActiveRecordsFilter() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .iterateAndStream() .flatMap(model -> extractRequests(model, sourceTablesMap).stream()); GuavaCollectors.batchAndStream(requestsStream, 500) .forEach(requests -> { modelsToIndexQueueService.enqueueNow(requests); addLog("Enqueued {} records from {} table", requests.size(), sourceTableName); }); } private List<ModelToIndexEnqueueRequest> extractRequests( @NonNull final Object model, @NonNull final FTSConfigSourceTablesMap sourceTables) { return EnqueueSourceModelInterceptor.extractRequests( model, ModelToIndexEventType.CREATED_OR_UPDATED, sourceTables); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\process\ES_FTS_Config_Sync.java
1
请完成以下Java代码
public void run() { try { Thread.sleep(this.shutdownTime); long start = System.currentTimeMillis(); while (!isUp()) { long runTime = System.currentTimeMillis() - start; if (runTime > this.timeout) { return; } Thread.sleep(this.sleepTime); } logger.info("Remote server has changed, triggering LiveReload"); this.liveReloadServer.triggerReload(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }
private boolean isUp() { try { ClientHttpRequest request = createRequest(); try (ClientHttpResponse response = request.execute()) { return response.getStatusCode() == HttpStatus.OK; } } catch (Exception ex) { return false; } } private ClientHttpRequest createRequest() throws IOException { return this.requestFactory.createRequest(this.uri, HttpMethod.GET); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\DelayedLiveReloadTrigger.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public String getVariable() { return variable; } public void setVariable(String variable) { this.variable = variable; } public String getType() { return type; } public String getDefaultExpression() { return defaultExpression; } public void setDefaultExpression(String defaultExpression) { this.defaultExpression = defaultExpression; } public void setType(String type) { this.type = type; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } public boolean isReadable() { return readable; } public void setReadable(boolean readable) { this.readable = readable; } public boolean isWriteable() { return writeable; } public void setWriteable(boolean writeable) { this.writeable = writeable; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; }
public List<FormValue> getFormValues() { return formValues; } public void setFormValues(List<FormValue> formValues) { this.formValues = formValues; } public FormProperty clone() { FormProperty clone = new FormProperty(); clone.setValues(this); return clone; } public void setValues(FormProperty otherProperty) { super.setValues(otherProperty); setName(otherProperty.getName()); setExpression(otherProperty.getExpression()); setVariable(otherProperty.getVariable()); setType(otherProperty.getType()); setDefaultExpression(otherProperty.getDefaultExpression()); setDatePattern(otherProperty.getDatePattern()); setReadable(otherProperty.isReadable()); setWriteable(otherProperty.isWriteable()); setRequired(otherProperty.isRequired()); formValues = new ArrayList<FormValue>(); if (otherProperty.getFormValues() != null && !otherProperty.getFormValues().isEmpty()) { for (FormValue formValue : otherProperty.getFormValues()) { formValues.add(formValue.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FormProperty.java
1