instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
static I_M_HU_PI_Item_Product extractHUPIItemProductOrNull(@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration) { final HUPIItemProductId huPIItemProductId = HUPIItemProductId.ofRepoIdOrNull(lutuConfiguration.getM_HU_PI_Item_Product_ID()); return huPIItemProductId != null ? Services.get(IHUPIItemProductDAO.class).getRecordById(huPIItemProductId) : null; } @Value @Builder class CreateLUTUConfigRequest { @NonNull I_M_HU_LUTU_Configuration baseLUTUConfiguration; @NonNull BigDecimal qtyTU;
@NonNull BigDecimal qtyCUsPerTU; @NonNull Integer tuHUPIItemProductID; @Nullable BigDecimal qtyLU; @Nullable Integer luHUPIID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\ILUTUConfigurationFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class RegisterReq extends AbsReq { /** 用户名 */ private String username; /** 密码 */ private String password; /** 手机号 */ private String phone; /** 邮箱 */ private String mail; /** 营业执照照片 */ private String licencePic; /** 用户类别 {@link com.gaoxi.enumeration.user.UserTypeEnum} */ private Integer userType; 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; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail;
} public String getLicencePic() { return licencePic; } public void setLicencePic(String licencePic) { this.licencePic = licencePic; } public Integer getUserType() { return userType; } public void setUserType(Integer userType) { this.userType = userType; } @Override public String toString() { return "RegisterReq{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", licencePic='" + licencePic + '\'' + ", userType=" + userType + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\RegisterReq.java
2
请在Spring Boot框架中完成以下Java代码
public Map<String, Object> datasource() throws SQLException { Map result = new HashMap(); result.put("数据源类名", dataSource.getClass()+""); // 获取数据库连接对象 Connection connection = dataSource.getConnection(); // 判断连接对象是否为空 result.put("能否正确获得连接", connection != null); connection.close(); return result; } // 查询数据源信息 @GetMapping("/datasource2") public Map<String, Object> datasource2() throws SQLException { DruidDataSource druidDataSource = (DruidDataSource)dataSource; Map result = new HashMap();
result.put("数据源类名", druidDataSource.getClass()+""); // 获取数据库连接对象 Connection connection = druidDataSource.getConnection(); // 判断连接对象是否为空 result.put("能否正确获得连接", connection != null); result.put("initialSize值为",druidDataSource.getInitialSize()); result.put("maxActive值为",druidDataSource.getMaxActive()); result.put("minIdle值为",druidDataSource.getMinIdle()); result.put("validationQuery值为",druidDataSource.getValidationQuery()); result.put("maxWait值为",druidDataSource.getMaxWait()); connection.close(); return result; } }
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-druid\src\main\java\cn\lanqiao\springboot3\controller\DataSourceController.java
2
请完成以下Java代码
public void serverCallStarted(ServerCallInfo<?, ?> callInfo) { this.metricsServerMeters.getServerCallCounter() .withTags(Tags.of("grpc.method", this.fullMethodName, INSTRUMENTATION_SOURCE_TAG_KEY, Constants.LIBRARY_NAME, INSTRUMENTATION_VERSION_TAG_KEY, Constants.VERSION)) .increment(); } @Override public void outboundWireSize(long bytes) { outboundWireSizeUpdater.getAndAdd(this, bytes); } @Override public void inboundWireSize(long bytes) { inboundWireSizeUpdater.getAndAdd(this, bytes); } @Override public void streamClosed(Status status) { if (streamClosedUpdater.getAndSet(this, 1) != 0) { return; } long callLatencyNanos = stopwatch.elapsed(TimeUnit.NANOSECONDS); Tags serverMetricTags = Tags.of("grpc.method", this.fullMethodName, "grpc.status", status.getCode().toString(), INSTRUMENTATION_SOURCE_TAG_KEY, Constants.LIBRARY_NAME, INSTRUMENTATION_VERSION_TAG_KEY, Constants.VERSION); this.metricsServerMeters.getServerCallDuration() .withTags(serverMetricTags) .record(callLatencyNanos, TimeUnit.NANOSECONDS); this.metricsServerMeters.getSentMessageSizeDistribution() .withTags(serverMetricTags) .record(outboundWireSize); this.metricsServerMeters.getReceivedMessageSizeDistribution()
.withTags(serverMetricTags) .record(inboundWireSize); } } final class MetricsServerTracerFactory extends ServerStreamTracer.Factory { private final MetricsServerMeters metricsServerMeters; MetricsServerTracerFactory(MeterRegistry registry) { this(MetricsServerInstruments.newServerMetricsMeters(registry)); } MetricsServerTracerFactory(MetricsServerMeters metricsServerMeters) { this.metricsServerMeters = metricsServerMeters; } @Override public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) { return new ServerTracer(MetricsServerStreamTracers.this, fullMethodName, this.metricsServerMeters); } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\metrics\MetricsServerStreamTracers.java
1
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = -4523695542426439365L; private Integer id; private String cnname; private String username; @JsonIgnore private String password; private String email; private String mobilePhone; private List<Role> roles; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCnname() { return cnname; } public void setCnname(String cnname) { this.cnname = cnname; } public String getUsername() { return username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public String getMobilePhone() { return mobilePhone; } public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } @Override public String toString() { return "User{" + "id=" + id + ", cnname=" + cnname + ", username=" + username + ", password=" + password + ", email=" + email + ", mobilePhone=" + mobilePhone + '}'; } }
repos\springBoot-master\springboot-dubbo\abel-user-api\src\main\java\cn\abel\user\models\User.java
1
请在Spring Boot框架中完成以下Java代码
public class LogicRepository implements ToDoRepository{ @Override public List<ToDo> findAll() { return null; } @Override public List<ToDo> findAll(Sort sort) { return null; } @Override public Page<ToDo> findAll(Pageable pageable) { return null; } @Override public List<ToDo> findAllById(Iterable<Long> iterable) { return null; } @Override public long count() { return 0; } @Override public void deleteById(Long aLong) { } @Override public void delete(ToDo toDo) { } @Override public void deleteAll(Iterable<? extends ToDo> iterable) { } @Override public void deleteAll() { } @Override public <S extends ToDo> S save(S s) { return null; } @Override public <S extends ToDo> List<S> saveAll(Iterable<S> iterable) { return null; } @Override public Optional<ToDo> findById(Long aLong) { return Optional.empty(); } @Override public boolean existsById(Long aLong) { return false; } @Override public void flush() { } @Override public <S extends ToDo> S saveAndFlush(S s) { return null; } @Override public void deleteInBatch(Iterable<ToDo> iterable) { }
@Override public void deleteAllInBatch() { } @Override public ToDo getOne(Long aLong) { return null; } @Override public <S extends ToDo> Optional<S> findOne(Example<S> example) { return Optional.empty(); } @Override public <S extends ToDo> List<S> findAll(Example<S> example) { return null; } @Override public <S extends ToDo> List<S> findAll(Example<S> example, Sort sort) { return null; } @Override public <S extends ToDo> Page<S> findAll(Example<S> example, Pageable pageable) { return null; } @Override public <S extends ToDo> long count(Example<S> example) { return 0; } @Override public <S extends ToDo> boolean exists(Example<S> example) { return false; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\3.TodoProjectDB\src\main\java\spring\project\repository\LogicRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class AcquiredExternalWorkerJobImpl implements AcquiredExternalWorkerJob { protected final ExternalWorkerJobEntity job; protected final Map<String, Object> variables; public AcquiredExternalWorkerJobImpl(ExternalWorkerJobEntity job, Map<String, Object> variables) { this.job = job; this.variables = variables; } @Override public Map<String, Object> getVariables() { return variables; } @Override public Date getDuedate() { return job.getDuedate(); } @Override public String getProcessInstanceId() { return job.getProcessInstanceId(); } @Override public String getExecutionId() { return job.getExecutionId(); } @Override public String getProcessDefinitionId() { return job.getProcessDefinitionId(); } @Override public String getCategory() { return job.getCategory(); } @Override public String getJobType() { return job.getJobType(); } @Override public String getElementId() { return job.getElementId(); } @Override public String getElementName() { return job.getElementName(); } @Override public String getScopeId() { return job.getScopeId(); } @Override public String getSubScopeId() { return job.getSubScopeId(); } @Override public String getScopeType() { return job.getScopeType(); } @Override public String getScopeDefinitionId() {
return job.getScopeDefinitionId(); } @Override public String getCorrelationId() { return job.getCorrelationId(); } @Override public boolean isExclusive() { return job.isExclusive(); } @Override public Date getCreateTime() { return job.getCreateTime(); } @Override public String getId() { return job.getId(); } @Override public int getRetries() { return job.getRetries(); } @Override public String getExceptionMessage() { return job.getExceptionMessage(); } @Override public String getTenantId() { return job.getTenantId(); } @Override public String getJobHandlerType() { return job.getJobHandlerType(); } @Override public String getJobHandlerConfiguration() { return job.getJobHandlerConfiguration(); } @Override public String getCustomValues() { return job.getCustomValues(); } @Override public String getLockOwner() { return job.getLockOwner(); } @Override public Date getLockExpirationTime() { return job.getLockExpirationTime(); } @Override public String toString() { return new StringJoiner(", ", AcquiredExternalWorkerJobImpl.class.getSimpleName() + "[", "]") .add("job=" + job) .toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\AcquiredExternalWorkerJobImpl.java
2
请完成以下Java代码
public Rule toRule() { return null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDefinitionEntity entity = (ApiDefinitionEntity) o; return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) && Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) && Objects.equals(predicateItems, entity.predicateItems); } @Override
public int hashCode() { return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); } @Override public String toString() { return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + ", predicateItems=" + predicateItems + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiDefinitionEntity.java
1
请完成以下Java代码
public class DefaultDataFetcherObservationConvention implements DataFetcherObservationConvention { private static final String DEFAULT_NAME = "graphql.datafetcher"; private static final KeyValue OUTCOME_SUCCESS = KeyValue.of(DataFetcherLowCardinalityKeyNames.OUTCOME, "SUCCESS"); private static final KeyValue OUTCOME_ERROR = KeyValue.of(DataFetcherLowCardinalityKeyNames.OUTCOME, "ERROR"); private static final KeyValue ERROR_TYPE_NONE = KeyValue.of(DataFetcherLowCardinalityKeyNames.ERROR_TYPE, "NONE"); private final String name; public DefaultDataFetcherObservationConvention() { this(DEFAULT_NAME); } public DefaultDataFetcherObservationConvention(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public String getContextualName(DataFetcherObservationContext context) { return "graphql field " + context.getEnvironment().getField().getName(); } @Override public KeyValues getLowCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(outcome(context), fieldName(context), errorType(context)); } protected KeyValue outcome(DataFetcherObservationContext context) { if (context.getError() != null) { return OUTCOME_ERROR; } return OUTCOME_SUCCESS; }
protected KeyValue fieldName(DataFetcherObservationContext context) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.FIELD_NAME, context.getEnvironment().getField().getName()); } protected KeyValue errorType(DataFetcherObservationContext context) { if (context.getError() != null) { return KeyValue.of(DataFetcherLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName()); } return ERROR_TYPE_NONE; } @Override public KeyValues getHighCardinalityKeyValues(DataFetcherObservationContext context) { return KeyValues.of(fieldPath(context)); } protected KeyValue fieldPath(DataFetcherObservationContext context) { return KeyValue.of(GraphQlObservationDocumentation.DataFetcherHighCardinalityKeyNames.FIELD_PATH, context.getEnvironment().getExecutionStepInfo().getPath().toString()); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataFetcherObservationConvention.java
1
请完成以下Java代码
public static MHRDepartment get(Properties ctx, int HR_Department_ID) { if (HR_Department_ID <= 0) { return null; } if (s_cache.size() == 0) { getAll(ctx); } MHRDepartment dep = s_cache.get(HR_Department_ID); if (dep != null) { return dep; } dep = new MHRDepartment(ctx, HR_Department_ID, null); if (dep.get_ID() == HR_Department_ID) { s_cache.put(HR_Department_ID, dep); } return dep; } private static CCache<Integer, MHRDepartment> s_cache = new CCache<>(Table_Name, 50, 0);
/** * @param ctx * @param HR_Department_ID * @param trxName */ public MHRDepartment(Properties ctx, int HR_Department_ID, String trxName) { super(ctx, HR_Department_ID, trxName); } /** * @param ctx * @param rs * @param trxName */ public MHRDepartment(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRDepartment.java
1
请完成以下Java代码
public BigDecimal getQtyOnHand () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOnHand); if (bd == null) return Env.ZERO; return bd; } /** Set Ordered Quantity. @param QtyOrdered Ordered Quantity */ public void setQtyOrdered (BigDecimal QtyOrdered) { set_ValueNoCheck (COLUMNNAME_QtyOrdered, QtyOrdered); } /** Get Ordered Quantity. @return Ordered Quantity */ public BigDecimal getQtyOrdered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered); if (bd == null) return Env.ZERO; return bd; }
/** Set Reserved Quantity. @param QtyReserved Reserved Quantity */ public void setQtyReserved (BigDecimal QtyReserved) { set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved); } /** Get Reserved Quantity. @return Reserved Quantity */ public BigDecimal getQtyReserved () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved); 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_M_Storage.java
1
请完成以下Java代码
private IQuery<I_C_BPartner_Product> toSqlQuery(@NonNull final BPartnerProductQuery query) { final IQueryBuilder<I_C_BPartner_Product> sqlQueryBuilder = queryBL.createQueryBuilder(I_C_BPartner_Product.class) .orderBy(I_C_BPartner_Product.COLUMNNAME_M_Product_ID) .orderBy(I_C_BPartner_Product.COLUMNNAME_SeqNo) .orderBy(I_C_BPartner_Product.COLUMNNAME_C_BPartner_Product_ID); final InSetPredicate<EAN13> cuEANs = query.getCuEANs(); if (cuEANs != null) { cuEANs.apply(new InSetPredicate.CaseConsumer<EAN13>() { @Override public void anyValue() {} @Override public void noValue()
{ sqlQueryBuilder.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_EAN_CU, null); } @Override public void onlyValues(final Set<EAN13> onlyValues) { final ImmutableSet<String> stringValues = onlyValues.stream() .map(EAN13::getAsString) .collect(ImmutableSet.toImmutableSet()); sqlQueryBuilder.addInArrayFilter(I_C_BPartner_Product.COLUMNNAME_EAN_CU, stringValues); } }); } return sqlQueryBuilder.create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\ProductRepository.java
1
请完成以下Java代码
private PodSpec buildPodSpec(DeptrackResource primary) { // Check for version override String imageVersion = StringUtils.hasText(primary.getSpec() .getFrontendVersion()) ? ":" + primary.getSpec() .getFrontendVersion() .trim() : ""; // Check for image override String imageName = StringUtils.hasText(primary.getSpec() .getFrontendImage()) ? primary.getSpec() .getFrontendImage() .trim() : Constants.DEFAULT_FRONTEND_IMAGE; return new PodSpecBuilder(template.getSpec().getTemplate().getSpec()) .editContainer(0) .withImage(imageName + imageVersion) .editFirstEnv() .withName("API_BASE_URL")
.withValue("https://" + primary.getSpec().getIngressHostname()) .endEnv() .and() .build(); } static class Discriminator extends ResourceIDMatcherDiscriminator<Deployment,DeptrackResource> { public Discriminator() { super(COMPONENT, (p) -> new ResourceID(p.getMetadata() .getName() + "-" + COMPONENT, p.getMetadata() .getNamespace())); } } }
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackFrontendDeploymentResource.java
1
请完成以下Java代码
protected List<HistoricTaskInstanceReportResult> executeCountByTaskName(CommandContext commandContext) { return commandContext.getTaskReportManager() .selectHistoricTaskInstanceCountByTaskNameReport(this); } @Override public List<DurationReportResult> duration(PeriodUnit periodUnit) { ensureNotNull(NotValidException.class, "periodUnit", periodUnit); this.durationPeriodUnit = periodUnit; CommandContext commandContext = Context.getCommandContext(); if(commandContext == null) { return commandExecutor.execute(new ExecuteDurationCmd()); } else { return executeDuration(commandContext); } } protected List<DurationReportResult> executeDuration(CommandContext commandContext) { return commandContext.getTaskReportManager() .createHistoricTaskDurationReport(this); } public Date getCompletedAfter() { return completedAfter; } public Date getCompletedBefore() { return completedBefore; } @Override public HistoricTaskInstanceReport completedAfter(Date completedAfter) { ensureNotNull(NotValidException.class, "completedAfter", completedAfter); this.completedAfter = completedAfter; return this; } @Override public HistoricTaskInstanceReport completedBefore(Date completedBefore) { ensureNotNull(NotValidException.class, "completedBefore", completedBefore); this.completedBefore = completedBefore; return this; } public TenantCheck getTenantCheck() { return tenantCheck; } public String getReportPeriodUnitName() { return durationPeriodUnit.name(); }
protected class ExecuteDurationCmd implements Command<List<DurationReportResult>> { @Override public List<DurationReportResult> execute(CommandContext commandContext) { return executeDuration(commandContext); } } protected class HistoricTaskInstanceCountByNameCmd implements Command<List<HistoricTaskInstanceReportResult>> { @Override public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) { return executeCountByTaskName(commandContext); } } protected class HistoricTaskInstanceCountByProcessDefinitionKey implements Command<List<HistoricTaskInstanceReportResult>> { @Override public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) { return executeCountByProcessDefinitionKey(commandContext); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(refundAmount, lineItemId, legacyReference); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RefundItem {\n"); sb.append(" refundAmount: ").append(toIndentedString(refundAmount)).append("\n"); sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n"); sb.append(" legacyReference: ").append(toIndentedString(legacyReference)).append("\n"); sb.append("}"); return sb.toString();
} /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\RefundItem.java
2
请完成以下Java代码
public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } public static HistoricTaskInstanceReportResultDto fromHistoricTaskInstanceReportResult(HistoricTaskInstanceReportResult taskReportResult) { HistoricTaskInstanceReportResultDto dto = new HistoricTaskInstanceReportResultDto(); dto.count = taskReportResult.getCount(); dto.processDefinitionKey = taskReportResult.getProcessDefinitionKey(); dto.processDefinitionId = taskReportResult.getProcessDefinitionId(); dto.processDefinitionName = taskReportResult.getProcessDefinitionName(); dto.taskName = taskReportResult.getTaskName(); dto.tenantId = taskReportResult.getTenantId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportResultDto.java
1
请完成以下Java代码
public double[][] cube() { double[][] X = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { X[i][j] = Math.pow(A[i][j], 3.); } } return X; } public void setZero() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = 0.; } } } public void save(DataOutputStream out) throws Exception { out.writeInt(m);
out.writeInt(n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { out.writeDouble(A[i][j]); } } } public boolean load(ByteArray byteArray) { m = byteArray.nextInt(); n = byteArray.nextInt(); A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = byteArray.nextDouble(); } } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Matrix.java
1
请完成以下Java代码
public String getSummary(final I_C_RfQ rfq) { // NOTE: nulls shall be tolerated because the method is used for building exception error messages if (rfq == null) { return "@C_RfQ_ID@ ?"; } return "@C_RfQ_ID@ #" + rfq.getDocumentNo(); } @Override public String getSummary(final I_C_RfQResponse rfqResponse) { // NOTE: nulls shall be tolerated because the method is used for building exception error messages if (rfqResponse == null) { return "@C_RfQResponse_ID@ ?"; } return "@C_RfQResponse_ID@ #" + rfqResponse.getName(); } @Override public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine) { final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine); rfqResponseLine.setQtyPromised(qtyPromised); InterfaceWrapperHelper.save(rfqResponseLine); }
// @Override // public void uncloseInTrx(final I_C_RfQResponse rfqResponse) // { // if (!isClosed(rfqResponse)) // { // throw new RfQDocumentNotClosedException(getSummary(rfqResponse)); // } // // // // final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher(); // rfQEventDispacher.fireBeforeUnClose(rfqResponse); // // // // // Mark as NOT closed // rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed); // InterfaceWrapperHelper.save(rfqResponse); // updateRfQResponseLinesStatus(rfqResponse); // // // // rfQEventDispacher.fireAfterUnClose(rfqResponse); // // // Make sure it's saved // InterfaceWrapperHelper.save(rfqResponse); // } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java
1
请完成以下Java代码
public List<BankAccount> getBankAccounts() { return bankAccounts; } public void setBankAccounts(List<BankAccount> bankAccounts) { this.bankAccounts = bankAccounts; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\entities\Person.java
1
请完成以下Java代码
protected Object execute(CommandContext commandContext, TaskEntity task) { if (task.getProcessDefinitionId() != null && Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.setTaskVariables(taskId, variables, isLocal); return null; } if (isLocal) { if (variables != null) { for (String variableName : variables.keySet()) { task.setVariableLocal(variableName, variables.get(variableName), false); } } } else { if (variables != null) { for (String variableName : variables.keySet()) {
task.setVariable(variableName, variables.get(variableName), false); } } } // ACT-1887: Force an update of the task's revision to prevent // simultaneous inserts of the same variable. If not, duplicate variables may occur since optimistic // locking doesn't work on inserts task.forceUpdate(); return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot add variables to"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SetTaskVariablesCmd.java
1
请完成以下Java代码
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); String accessToken = request.getParameter(Constants.THIRD_PARTY_ACCESS_TOKEN_NAME); //shiro后续流程可能会用到username,所以如果用accessToken登录时赋值username为它的值。 if (StringUtils.isBlank(username)) { username = accessToken; } return new ThirdPartySupportedToken(username, password, accessToken); } /** * 直接构造HttpResponse,不再执行后续的所有方法。 * * @param response * @param entity * @return */ private boolean responseDirectly(HttpServletResponse response, ResponseEntity entity) {
response.reset(); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); //设置跨域信息。 response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "*"); try { response.getWriter().write(JSON.toJSONString(entity)); } catch (IOException e) { logger.error("ResponseError ex:{}", ExceptionUtils.getStackTrace(e)); } return false; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\filter\ShiroFormAuthenticationFilter.java
1
请完成以下Java代码
public List<HistoricIncident> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIncidentManager() .findHistoricIncidentByQueryCriteria(this, page); } // getters ///////////////////////////////////////////////////// public String getId() { return id; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getExecutionId() { return executionId; } public String getActivityId() { return activityId; } public String getFailedActivityId() { return failedActivityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String[] getProcessDefinitionKeys() { return processDefinitionKeys;
} public String getCauseIncidentId() { return causeIncidentId; } public String getRootCauseIncidentId() { return rootCauseIncidentId; } public String getConfiguration() { return configuration; } public String getHistoryConfiguration() { return historyConfiguration; } public IncidentState getIncidentState() { return incidentState; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIncidentQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String index() { return "index"; } @PostMapping("/createOrder") public String createOrder(@RequestParam String totalAmount, @RequestParam String subject, Model model) { String outTradeNo = "ORDER_" + System.currentTimeMillis(); // 生成订单号 try { String qrCodeUrl = alipayService.createOrder(outTradeNo, totalAmount, subject); model.addAttribute("qrCodeUrl", qrCodeUrl); model.addAttribute("totalAmount", totalAmount); model.addAttribute("subject", subject); model.addAttribute("outTradeNo", outTradeNo); return "payment"; } catch (Exception e) {
model.addAttribute("error", "创建订单失败"); return "error"; } } @PostMapping("/queryPayment") public String queryPayment(String outTradeNo) { String TradeStatus=alipayService.queryPayment(outTradeNo); if(TradeStatus.equals("TRADE_SUCCESS")||TradeStatus.equals("TRADE_FINISHED")){ return "success"; }else{ return "error"; } } }
repos\springboot-demo-master\Alipay-facetoface\src\main\java\com.et\controller\PaymentController.java
2
请完成以下Java代码
private void resolve() { log.debug("Scheduled self resolve"); if (this.resolving || this.executor == null) { return; } this.resolving = true; this.executor.execute(new Resolve(this.listener)); } @Override public void shutdown() { this.listener = null; if (this.executor != null && this.usingExecutorResource) { this.executor = SharedResourceHolder.release(this.executorResource, this.executor); } } private SocketAddress getOwnAddress() { final String address = this.properties.getAddress(); final int port = this.properties.getPort(); final SocketAddress target; if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) { target = new InetSocketAddress(port); } else { target = new InetSocketAddress(InetAddresses.forString(address), port); } return target; } private String getOwnAddressString(final String fallback) { try { return getOwnAddress().toString().substring(1); } catch (final IllegalArgumentException e) { return fallback; } } @Override public String toString() { return "SelfNameResolver [" + getOwnAddressString("<unavailable>") + "]"; } /** * The logic for assigning the own address. */ private final class Resolve implements Runnable { private final Listener2 savedListener;
/** * Creates a new Resolve that stores a snapshot of the relevant states of the resolver. * * @param listener The listener to send the results to. */ Resolve(final Listener2 listener) { this.savedListener = requireNonNull(listener, "listener"); } @Override public void run() { try { this.savedListener.onResult(ResolutionResult.newBuilder() .setAddresses(ImmutableList.of( new EquivalentAddressGroup(getOwnAddress()))) .build()); } catch (final Exception e) { this.savedListener.onError(Status.UNAVAILABLE .withDescription("Failed to resolve own address").withCause(e)); } finally { SelfNameResolver.this.syncContext.execute(() -> SelfNameResolver.this.resolving = false); } } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\nameresolver\SelfNameResolver.java
1
请完成以下Java代码
public String getIocmCategory() { return iocmCategory; } /** * Sets the value of the iocmCategory property. * * @param value * allowed object is * {@link String } * */ public void setIocmCategory(String value) { this.iocmCategory = value; } /** * Gets the value of the delivery property. * * @return * possible object is * {@link String } * */ public String getDelivery() { if (delivery == null) { return "first"; } else { return delivery; } } /** * Sets the value of the delivery property. * * @param value * allowed object is * {@link String } * */ public void setDelivery(String value) { this.delivery = value; } /** * Gets the value of the regulationAttributes property. * * @return * possible object is * {@link Long }
* */ public long getRegulationAttributes() { if (regulationAttributes == null) { return 0L; } else { return regulationAttributes; } } /** * Sets the value of the regulationAttributes property. * * @param value * allowed object is * {@link Long } * */ public void setRegulationAttributes(Long value) { this.regulationAttributes = value; } /** * Gets the value of the limitation property. * * @return * possible object is * {@link Boolean } * */ public Boolean isLimitation() { return limitation; } /** * Sets the value of the limitation property. * * @param value * allowed object is * {@link Boolean } * */ public void setLimitation(Boolean value) { this.limitation = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordDrugType.java
1
请完成以下Java代码
protected void returnMessage(List<DataAssociation> dataOutputAssociations, DelegateExecution execution) { for (DataAssociation dataAssociationElement : dataOutputAssociations) { AbstractDataAssociation dataAssociation = createDataOutputAssociation(dataAssociationElement); dataAssociation.evaluate(execution); } } protected void fillMessage(List<DataAssociation> dataInputAssociations, DelegateExecution execution) { for (DataAssociation dataAssociationElement : dataInputAssociations) { AbstractDataAssociation dataAssociation = createDataInputAssociation(dataAssociationElement); dataAssociation.evaluate(execution); } } protected AbstractDataAssociation createDataInputAssociation(DataAssociation dataAssociationElement) { if (dataAssociationElement.getAssignments().isEmpty()) { return new MessageImplicitDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef()); } else { SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef()); ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager(); for (org.flowable.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (StringUtils.isNotEmpty(assignmentElement.getFrom()) && StringUtils.isNotEmpty(assignmentElement.getTo())) { Expression from = expressionManager.createExpression(assignmentElement.getFrom()); Expression to = expressionManager.createExpression(assignmentElement.getTo()); Assignment assignment = new Assignment(from, to); dataAssociation.addAssignment(assignment); } } return dataAssociation; } } protected AbstractDataAssociation createDataOutputAssociation(DataAssociation dataAssociationElement) { if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) { return new MessageImplicitDataOutputAssociation(dataAssociationElement.getTargetRef(), dataAssociationElement.getSourceRef()); } else { ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager(); Expression transformation = expressionManager.createExpression(dataAssociationElement.getTransformation()); AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(null, dataAssociationElement.getTargetRef(), transformation); return dataOutputAssociation; } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\WebServiceActivityBehavior.java
1
请完成以下Java代码
private void rollbackChunkTrx() { Check.assumeNotNull(chunkTrx, "chunkTrx shall NOT be null"); // // Case: Locally created transaction => rollback it if (chunkTrxIsLocal) { chunkTrx.rollback(); chunkTrx.close(); } // // Case: Savepoint on inherited transaction => rollback to savepoint else if (chunkTrxSavepoint != null) { chunkTrx.rollback(chunkTrxSavepoint);
chunkTrxSavepoint = null; } // // Case: Inherited transaction without any savepoint => do nothing else { // nothing } chunkTrx = null; // NOTE: no need to restore/reset thread transaction because the "execute" method will restore it anyways at the end // trxManager.setThreadInheritedTrxName(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemChunkProcessorExecutor.java
1
请完成以下Java代码
public static String buildStringRestriction(final String columnSQL, @Nullable final Object value, final boolean isIdentifier, final List<Object> params) { return buildStringRestriction(null, columnSQL, value, isIdentifier, params); } /** * apply function to parameter cg: task: 02381 */ public static String buildStringRestriction(@Nullable final String criteriaFunction, final String columnSQL, @Nullable final Object value, final boolean isIdentifier, final List<Object> params) { final String valueStr = prepareSearchString(value, isIdentifier); String whereClause; if (Check.isBlank(criteriaFunction)) { whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE" + " UPPER(" + DBConstants.FUNC_unaccent_string("?") + ")"; } else { //noinspection ConstantConditions whereClause = "UPPER(" + DBConstants.FUNC_unaccent_string(columnSQL) + ")" + " LIKE " + "UPPER(" + DBConstants.FUNC_unaccent_string(criteriaFunction.replaceFirst(columnSQL, "?")) + ")"; } params.add(valueStr); return whereClause; } public static String buildStringRestriction(final String columnSQL, final int displayType, final Object value, final Object valueTo, final boolean isRange, final List<Object> params) { final StringBuffer where = new StringBuffer(); if (isRange) { if (value != null || valueTo != null) where.append(" ("); if (value != null) { where.append(columnSQL).append(">?"); params.add(value); } if (valueTo != null) { if (value != null) where.append(" AND "); where.append(columnSQL).append("<?"); params.add(valueTo); } if (value != null || valueTo != null) where.append(") "); } else { where.append(columnSQL).append("=?"); params.add(value); } return where.toString(); } public static String prepareSearchString(final Object value) { return prepareSearchString(value, false); } public static String prepareSearchString(final Object value, final boolean isIdentifier) { if (value == null || value.toString().length() == 0) { return null;
} String valueStr; if (isIdentifier) { // metas-2009_0021_AP1_CR064: begin valueStr = ((String)value).trim(); if (!valueStr.startsWith("%")) valueStr = "%" + value; // metas-2009_0021_AP1_CR064: end if (!valueStr.endsWith("%")) valueStr += "%"; } else { valueStr = (String)value; if (valueStr.startsWith("%")) { ; // nothing } else if (valueStr.endsWith("%")) { ; // nothing } else if (valueStr.indexOf("%") < 0) { valueStr = "%" + valueStr + "%"; } else { ; // nothing } } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindHelper.java
1
请完成以下Java代码
public int getExclude_M_HU_Trx_Line_ID() { return Exclude_M_HU_Trx_Line_ID; } @Override public void setExclude_M_HU_Trx_Line_ID(final int exclude_M_HU_Trx_Line_ID) { Exclude_M_HU_Trx_Line_ID = exclude_M_HU_Trx_Line_ID; } @Override public int getParent_M_HU_Trx_Line_ID() { return Parent_M_HU_Trx_Line_ID; } @Override public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID) { Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID; } @Override public void setM_HU_Item_ID(final int Ref_HU_Item_ID) { this.Ref_HU_Item_ID = Ref_HU_Item_ID; } @Override public int getM_HU_Item_ID() { return Ref_HU_Item_ID; } @Override public int getAD_Table_ID() { return AD_Table_ID; }
@Override public void setAD_Table_ID(final int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } @Override public void setRecord_ID(final int record_ID) { Record_ID = record_ID; } @Override public void setM_HU_ID(int m_hu_ID) { M_HU_ID = m_hu_ID; } @Override public int getM_HU_ID() { return M_HU_ID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java
1
请完成以下Java代码
public UserOperationLogContextEntryBuilder processInstanceId(String processInstanceId) { entry.setProcessInstanceId(processInstanceId); return this; } public UserOperationLogContextEntryBuilder caseDefinitionId(String caseDefinitionId) { entry.setCaseDefinitionId(caseDefinitionId); return this; } public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) { entry.setDeploymentId(deploymentId); return this; } public UserOperationLogContextEntryBuilder batchId(String batchId) { entry.setBatchId(batchId); return this; } public UserOperationLogContextEntryBuilder taskId(String taskId) { entry.setTaskId(taskId); return this; } public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) {
entry.setCaseInstanceId(caseInstanceId); return this; } public UserOperationLogContextEntryBuilder category(String category) { entry.setCategory(category); return this; } public UserOperationLogContextEntryBuilder annotation(String annotation) { entry.setAnnotation(annotation); return this; } public UserOperationLogContextEntryBuilder tenantId(String tenantId) { entry.setTenantId(tenantId); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class GithubImportSingleSelection extends GithubImportProcess implements IProcessPrecondition { private final IssueRepository issueRepository = SpringContextHolder.instance.getBean(IssueRepository.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (context.getSelectionSize().isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override
protected String doIt() throws Exception { final IssueEntity issueEntity = issueRepository.getById(IssueId.ofRepoId(getRecord_ID())); if (issueEntity.getExternalProjectReferenceId() == null || issueEntity.getExternalIssueNo() == null || issueEntity.getExternalIssueNo().signum() == 0) { throw new AdempiereException("The selected issue was not imported from Github!") .appendParametersToMessage() .setParameter("IssueEntity", issueEntity); } setExternalProjectReferenceId(issueEntity.getExternalProjectReferenceId()); setIssueNumbers(issueEntity.getExternalIssueNo().toString()); return super.doIt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImportSingleSelection.java
2
请在Spring Boot框架中完成以下Java代码
private static ArrayList<JsonRfqQty> toJsonRfqQtysList( @NonNull final Rfq rfq, @NonNull final Locale locale) { final ArrayList<JsonRfqQty> jsonRfqQtys = new ArrayList<>(); for (final LocalDate date : rfq.generateAllDaysSet()) { final RfqQty rfqQty = rfq.getRfqQtyByDate(date); final JsonRfqQty jsonRfqQty = rfqQty != null ? toJsonRfqQty(rfqQty, rfq.getQtyCUInfo(), locale) : toZeroJsonRfqQty(date, rfq.getQtyCUInfo(), locale); jsonRfqQtys.add(jsonRfqQty); } return jsonRfqQtys; } private static JsonRfqQty toJsonRfqQty( @NonNull final RfqQty rfqQty, @NonNull final String uom, @NonNull final Locale locale) { final BigDecimal qtyPromised = rfqQty.getQtyPromisedUserEntered(); return JsonRfqQty.builder() .date(rfqQty.getDatePromised()) .dayCaption(DateUtils.getDayName(rfqQty.getDatePromised(), locale)) .qtyPromised(qtyPromised) .qtyPromisedRendered(renderQty(qtyPromised, uom, locale)) .confirmedByUser(rfqQty.isConfirmedByUser()) .build(); }
private static JsonRfqQty toZeroJsonRfqQty( @NonNull final LocalDate date, @NonNull final String uom, @NonNull final Locale locale) { return JsonRfqQty.builder() .date(date) .dayCaption(DateUtils.getDayName(date, locale)) .qtyPromised(BigDecimal.ZERO) .qtyPromisedRendered(renderQty(BigDecimal.ZERO, uom, locale)) .confirmedByUser(true) .build(); } private static String renderQty( @NonNull final BigDecimal qty, @NonNull final String uom, @NonNull final Locale locale) { final NumberFormat formatter = NumberFormat.getNumberInstance(locale); return formatter.format(qty) + " " + uom; } private static String renderPrice( @NonNull final BigDecimal price, @NonNull final String currencyCode, @NonNull final Locale locale) { final NumberFormat formatter = NumberFormat.getNumberInstance(locale); return formatter.format(price) + " " + currencyCode; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\rfq\RfQRestController.java
2
请在Spring Boot框架中完成以下Java代码
protected void validateCreate(TenantId tenantId, EntityView entityView) { entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName()) .ifPresent(e -> { throw new DataValidationException("Entity view with such name already exists!"); }); } @Override protected EntityView validateUpdate(TenantId tenantId, EntityView entityView) { var opt = entityViewDao.findEntityViewByTenantIdAndName(entityView.getTenantId().getId(), entityView.getName()); opt.ifPresent(e -> { if (!e.getUuidId().equals(entityView.getUuidId())) { throw new DataValidationException("Entity view with such name already exists!"); } }); return opt.orElse(null); } @Override protected void validateDataImpl(TenantId tenantId, EntityView entityView) { validateString("Entity view name", entityView.getName()); validateString("Entity view type", entityView.getType()); if (entityView.getTenantId() == null) { throw new DataValidationException("Entity view should be assigned to tenant!"); } else {
if (!tenantService.tenantExists(entityView.getTenantId())) { throw new DataValidationException("Entity view is referencing to non-existent tenant!"); } } if (entityView.getCustomerId() == null) { entityView.setCustomerId(new CustomerId(NULL_UUID)); } else if (!entityView.getCustomerId().getId().equals(NULL_UUID)) { Customer customer = customerDao.findById(tenantId, entityView.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign entity view to non-existent customer!"); } if (!customer.getTenantId().getId().equals(entityView.getTenantId().getId())) { throw new DataValidationException("Can't assign entity view to customer from different tenant!"); } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\EntityViewDataValidator.java
2
请在Spring Boot框架中完成以下Java代码
public class FlatrateTermEventService implements IFlatrateTermEventService { private static final Logger logger = LogManager.getLogger(FlatrateTermEventService.class); private final Map<String, IFlatrateTermEventListener> typeConditions2handlers = new ConcurrentHashMap<>(); private final IFlatrateTermEventListener fallbackListener = new FallbackFlatrateTermEventListener(); public FlatrateTermEventService() { // Register standard handlers registerEventListenerForConditionsType(new SubscriptionTermEventListener(), SubscriptionTermEventListener.TYPE_CONDITIONS_SUBSCRIPTION); } @Override public synchronized void registerEventListenerForConditionsType(@NonNull final IFlatrateTermEventListener handlerNew, final String typeConditions) { Check.assumeNotEmpty(typeConditions, "typeConditions not empty"); // Validate handler if (handlerNew instanceof CompositeFlatrateTermEventListener) { // enforce immutability of given handler: we are not accepting composite because it might be that on next registerHandler calls will will add a handler inside it. throw new AdempiereException("Composite shall not be used: " + handlerNew); }
// final IFlatrateTermEventListener handlerCurrent = typeConditions2handlers.get(typeConditions); final IFlatrateTermEventListener handlerComposed = CompositeFlatrateTermEventListener.compose(handlerCurrent, handlerNew); typeConditions2handlers.put(typeConditions, handlerComposed); logger.info("Registered {} for TYPE_CONDITIONS={}", handlerNew, typeConditions); } @Override public IFlatrateTermEventListener getHandler(final String typeConditions) { final IFlatrateTermEventListener handlers = typeConditions2handlers.get(typeConditions); if (handlers == null) { logger.debug("No handler found for TYPE_CONDITIONS={}. Returning default: {}", typeConditions, fallbackListener); return fallbackListener; } return handlers; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\FlatrateTermEventService.java
2
请完成以下Java代码
public class SysPositionSelectTreeVo { /** 对应SysDepart中的id字段,前端数据树中的value*/ private String value; /** 对应depart_name字段,前端数据树中的title*/ private String title; private boolean isLeaf; /** 是否显示复选框 */ private boolean checkable; /** 是否禁用 */ private boolean disabled; // 以下所有字段均与SysDepart相同 private String id; /**父级id*/ private String parentId; /**部门类别*/ private String orgCategory; /**部门编码*/ private String orgCode; private List<SysPositionSelectTreeVo> children = new ArrayList<>(); /** * 将SysDepart对象转换成SysDepartTreeModel对象 * @param sysDepart */ public SysPositionSelectTreeVo(SysDepart sysDepart) { this.value = sysDepart.getId(); this.title = sysDepart.getDepartName(); this.id = sysDepart.getId(); this.parentId = sysDepart.getParentId(); this.orgCategory = sysDepart.getOrgCategory(); this.orgCode = sysDepart.getOrgCode(); if(0 == sysDepart.getIzLeaf()){ this.isLeaf = false; }else{ this.isLeaf = true; } if(DepartCategoryEnum.DEPART_CATEGORY_POST.getValue().equals(sysDepart.getOrgCategory())){ this.checkable = true; this.disabled = false; }else{ this.checkable = false; this.disabled = true; }
} public SysPositionSelectTreeVo(SysDepartPositionVo position) { this.value = position.getId(); if(oConvertUtils.isNotEmpty(position.getDepartName())){ this.title = position.getPositionName() + "("+position.getDepartName()+")"; }else{ this.title = position.getPositionName(); } this.id = position.getId(); this.parentId = position.getDepPostParentId(); this.orgCategory = "3"; if(0 == position.getIzLeaf()){ this.isLeaf = false; }else{ this.isLeaf = true; } this.checkable = true; this.disabled = false; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\SysPositionSelectTreeVo.java
1
请在Spring Boot框架中完成以下Java代码
public class ZkDistributedLockService implements DistributedLockService { private final ZkDiscoveryService zkDiscoveryService; @Override public DistributedLock getLock(String key) { return new ZkDistributedLock(key); } @RequiredArgsConstructor private class ZkDistributedLock implements DistributedLock { private final InterProcessLock interProcessLock; public ZkDistributedLock(String key) { this.interProcessLock = new InterProcessMutex(zkDiscoveryService.getClient(), zkDiscoveryService.getZkDir() + "/locks/" + key);
} @SneakyThrows @Override public void lock() { interProcessLock.acquire(); } @SneakyThrows @Override public void unlock() { interProcessLock.release(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\environment\ZkDistributedLockService.java
2
请完成以下Java代码
public static boolean requiresContextSwitch(ProcessApplicationReference processApplicationReference) { final ProcessApplicationReference currentProcessApplication = Context.getCurrentProcessApplication(); if(processApplicationReference == null) { return false; } if(currentProcessApplication == null) { return true; } else { if(!processApplicationReference.getName().equals(currentProcessApplication.getName())) { return true; } else { // check whether the thread context has been manipulated since last context switch. This can happen as a result of // an operation causing the container to switch to a different application. // Example: JavaDelegate implementation (inside PA) invokes an EJB from different application which in turn interacts with the Process engine. ClassLoader processApplicationClassLoader = ProcessApplicationClassloaderInterceptor.getProcessApplicationClassLoader(); ClassLoader currentClassloader = ClassLoaderUtil.getContextClassloader(); return currentClassloader != processApplicationClassLoader; } } } public static void doContextSwitch(final Runnable runnable, ProcessDefinitionEntity contextDefinition) {
ProcessApplicationReference processApplication = getTargetProcessApplication(contextDefinition); if (requiresContextSwitch(processApplication)) { Context.executeWithinProcessApplication(new Callable<Void>() { @Override public Void call() throws Exception { runnable.run(); return null; } }, processApplication); } else { runnable.run(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\ProcessApplicationContextUtil.java
1
请完成以下Java代码
private void assertValidCurrency(final I_C_PaySelectionLine paySelectionLine) { final BankAccountId bankAccountId = BankAccountId.ofRepoIdOrNull(paySelectionLine.getC_BP_BankAccount_ID()); if (bankAccountId == null) { return; } final BankAccount bankAccount = bpBankAccountDAO.getById(bankAccountId); // // Match currency final CurrencyId documentCurrencyId = getDocumentCurrencyId(paySelectionLine); final CurrencyId bankAccountCurrencyId = bankAccount.getCurrencyId(); if (CurrencyId.equals(documentCurrencyId, bankAccountCurrencyId)) { return; } final CurrencyCode documentCurrencyCode = currenciesRepo.getCurrencyCodeById(documentCurrencyId); final CurrencyCode bankAccountCurrencyCode = currenciesRepo.getCurrencyCodeById(bankAccountCurrencyId); throw new AdempiereException(MSG_PaySelectionLine_Document_InvalidCurrency, documentCurrencyCode.toThreeLetterCode(), // Actual bankAccountCurrencyCode.toThreeLetterCode()) // Expected .markAsUserValidationError(); } private CurrencyId getDocumentCurrencyId(final I_C_PaySelectionLine paySelectionLine) { final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(paySelectionLine.getC_Invoice_ID()); final OrderId orderId = OrderId.ofRepoIdOrNull(paySelectionLine.getC_Order_ID()); if (invoiceId != null) { final I_C_Invoice invoice = invoiceBL.getById(invoiceId); return CurrencyId.ofRepoId(invoice.getC_Currency_ID());
} else if (orderId != null) { final I_C_Order order = orderBL.getById(orderId); return CurrencyId.ofRepoId(order.getC_Currency_ID()); } else { throw new AdempiereException("No invoice or order found for " + paySelectionLine); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE }) public void afterNewOrChangeOrDelete(final I_C_PaySelectionLine paySelectionLine) { updatePaySelectionAmount(paySelectionLine); } private void updatePaySelectionAmount(@NonNull final I_C_PaySelectionLine paySelectionLine) { final PaySelectionId paySelectionId = PaySelectionId.ofRepoId(paySelectionLine.getC_PaySelection_ID()); paySelectionDAO.updatePaySelectionTotalAmt(paySelectionId); // make sure the is invalidated *after* the change is visible for everyone trxManager .getCurrentTrxListenerManagerOrAutoCommit() .runAfterCommit(() -> modelCacheInvalidationService.invalidate( CacheInvalidateMultiRequest.fromTableNameAndRecordId(I_C_PaySelection.Table_Name, paySelectionId.getRepoId()), ModelCacheInvalidationTiming.AFTER_CHANGE)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_PaySelectionLine.java
1
请完成以下Java代码
public SecurityInfo getByIdentity(String identity) { readLock.lock(); try { TbLwM2MSecurityInfo securityInfo = securityByIdentity.get(identity); if (securityInfo != null) { return securityInfo.getSecurityInfo(); } else { return null; } } finally { readLock.unlock(); } } @Override public SecurityInfo getByOscoreIdentity(OscoreIdentity oscoreIdentity) { return null; } @Override public void put(TbLwM2MSecurityInfo tbSecurityInfo) throws NonUniqueSecurityInfoException { writeLock.lock(); try { String identity = null; if (tbSecurityInfo.getSecurityInfo() != null) { identity = tbSecurityInfo.getSecurityInfo().getPskIdentity(); if (identity != null) { TbLwM2MSecurityInfo infoByIdentity = securityByIdentity.get(identity); if (infoByIdentity != null && !tbSecurityInfo.getSecurityInfo().getEndpoint().equals(infoByIdentity.getEndpoint())) { throw new NonUniqueSecurityInfoException("PSK Identity " + identity + " is already used"); } securityByIdentity.put(tbSecurityInfo.getSecurityInfo().getPskIdentity(), tbSecurityInfo); } } TbLwM2MSecurityInfo previous = securityByEp.put(tbSecurityInfo.getEndpoint(), tbSecurityInfo);
if (previous != null && previous.getSecurityInfo() != null) { String previousIdentity = previous.getSecurityInfo().getPskIdentity(); if (previousIdentity != null && !previousIdentity.equals(identity)) { securityByIdentity.remove(previousIdentity); } } } finally { writeLock.unlock(); } } @Override public void remove(String endpoint) { writeLock.lock(); try { TbLwM2MSecurityInfo securityInfo = securityByEp.remove(endpoint); if (securityInfo != null && securityInfo.getSecurityInfo() != null && securityInfo.getSecurityInfo().getPskIdentity() != null) { securityByIdentity.remove(securityInfo.getSecurityInfo().getPskIdentity()); } } finally { writeLock.unlock(); } } @Override public TbLwM2MSecurityInfo getTbLwM2MSecurityInfoByEndpoint(String endpoint) { readLock.lock(); try { return securityByEp.get(endpoint); } finally { readLock.unlock(); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemorySecurityStore.java
1
请完成以下Java代码
public static String sha(String data) { // 验证传入的字符串 if (StringUtils.isEmpty(data)) { return ""; } try { // 创建具有指定算法名称的信息摘要 MessageDigest sha = MessageDigest.getInstance(KEY_SHA); // 使用指定的字节数组对摘要进行最后更新 sha.update(data.getBytes("utf-8")); // 完成摘要计算 byte[] bytes = sha.digest(); // 将得到的字节数组变成字符串返回 return byteArrayToHexString(bytes); } catch (Exception e) { logger.error("字符串使用SHA加密失败", e); return null; } } /** * MD5 加密 * * @param data 需要加密的字符串 * @return 加密之后的字符串 */ public static String md5(String source) { // 验证传入的字符串 if (StringUtils.isEmpty(source)) { return ""; } try { MessageDigest md = MessageDigest.getInstance(MD5);
byte[] bytes = md.digest(source.getBytes("utf-8")); return byteArrayToHexString(bytes); } catch (Exception e) { logger.error("字符串使用Md5加密失败" + source + "' to MD5!", e); return null; } } /** * 转换字节数组为十六进制字符串 * * @param bytes * 字节数组 * @return 十六进制字符串 */ private static String byteArrayToHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3)); } return sb.toString(); } /** * 测试方法 * * @param args */ public static void main(String[] args) throws Exception { String key = "123"; System.out.println(sha(key)); System.out.println(md5(key)); } }
repos\spring-boot-student-master\spring-boot-student-encode\src\main\java\com\xiaolyuh\utils\EncodeUtil.java
1
请完成以下Java代码
protected static void invokeJobListener(CommandExecutor commandExecutor, JobFailureCollector jobFailureCollector) { if(jobFailureCollector.getJobId() != null) { if (jobFailureCollector.getFailure() != null) { // the failed job listener is responsible for decrementing the retries and logging the exception to the DB. FailedJobListener failedJobListener = createFailedJobListener(commandExecutor, jobFailureCollector); OptimisticLockingException exception = callFailedJobListenerWithRetries(commandExecutor, failedJobListener); if (exception != null) { throw exception; } } else { SuccessfulJobListener successListener = createSuccessfulJobListener(commandExecutor); commandExecutor.execute(successListener); } } } /** * Calls FailedJobListener, in case of OptimisticLockException retries configured amount of times. * * @return exception or null if succeeded */ private static OptimisticLockingException callFailedJobListenerWithRetries(CommandExecutor commandExecutor, FailedJobListener failedJobListener) { try { commandExecutor.execute(failedJobListener); return null; } catch (OptimisticLockingException ex) { failedJobListener.incrementCountRetries();
if (failedJobListener.getRetriesLeft() > 0) { return callFailedJobListenerWithRetries(commandExecutor, failedJobListener); } return ex; } } protected static void handleJobFailure(final String nextJobId, final JobFailureCollector jobFailureCollector, Throwable exception) { jobFailureCollector.setFailure(exception); } protected static FailedJobListener createFailedJobListener(CommandExecutor commandExecutor, JobFailureCollector jobFailureCollector) { return new FailedJobListener(commandExecutor, jobFailureCollector); } protected static SuccessfulJobListener createSuccessfulJobListener(CommandExecutor commandExecutor) { return new SuccessfulJobListener(); } public interface ExceptionLoggingHandler { void exceptionWhileExecutingJob(String jobId, Throwable exception); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\ExecuteJobHelper.java
1
请完成以下Java代码
public void setStatusDB(final String text, final DataStatusEvent dse) { // log.info( "StatusBar.setStatusDB - " + text + " - " + created + "/" + createdBy); if (text == null || text.length() == 0) { statusDB.setText(""); statusDB.setVisible(false); } else { final StringBuilder sb = new StringBuilder(" "); sb.append(text).append(" "); statusDB.setText(sb.toString()); if (!statusDB.isVisible()) { statusDB.setVisible(true); } } // Save // m_text = text; m_dse = dse; } // setStatusDB /** * Set Status DB Info * * @param text text */ @Override public void setStatusDB(final String text) { setStatusDB(text, null); } // setStatusDB /** * Set Status DB Info * * @param no no */ public void setStatusDB(final int no) { setStatusDB(String.valueOf(no), null); } // setStatusDB /** * Set Info Line * * @param text text */ @Override public void setInfo(final String text) { infoLine.setVisible(true); infoLine.setText(text); } // setInfo /** * Show {@link RecordInfo} dialog */
private void showRecordInfo() { if (m_dse == null) { return; } final int adTableId = m_dse.getAdTableId(); final ComposedRecordId recordId = m_dse.getRecordId(); if (adTableId <= 0 || recordId == null) { return; } if (!Env.getUserRolePermissions().isShowPreference()) { return; } // final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId); AEnv.showCenterScreen(info); } public void removeBorders() { statusLine.setBorder(BorderFactory.createEmptyBorder()); statusDB.setBorder(BorderFactory.createEmptyBorder()); infoLine.setBorder(BorderFactory.createEmptyBorder()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java
1
请完成以下Java代码
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 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
请完成以下Spring Boot application配置
server: port: 8081 # 端口 spring: application: name: multi-datasource-service # 应用名 datasource: # dynamic-datasource-spring-boot-starter 动态数据源的配配项,对应 DynamicDataSourceProperties 类 dynamic: primary: order-ds # 设置默认的数据源或者数据源组,默认值即为 master datasource: # 订单 order 数据源配置 order-ds: url: jdbc:mysql://127.0.0.1:3306/seata_order?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root password: # 账户 pay 数据源配置 account-ds: url: jdbc:mysql://127.0.0.1:3306/seata_account?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root password: # 商品 product 数据源配置 product-ds: url: jdbc:mysql://127.0.0.1:3306/seata_product?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root passw
ord: seata: true # 是否启动对 Seata 的集成 # Seata 配置项,对应 SeataProperties 类 seata: application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name} tx-service-group: ${spring.application.name}-group # Seata 事务组编号,用于 TC 集群名 # 服务配置项,对应 ServiceProperties 类 service: # 虚拟组和分组的映射 vgroup-mapping: multi-datasource-service-group: default # 分组和 Seata 服务的映射 grouplist: default: 127.0.0.1:8091
repos\SpringBoot-Labs-master\lab-52\lab-52-multiple-datasource\src\main\resources\application.yaml
2
请完成以下Java代码
public String dom4jBenchmark() throws DocumentException, TransformerException, SAXException { String path = this.getClass() .getResource("/xml/attribute.xml") .toString(); Dom4jTransformer transformer = new Dom4jTransformer(path); String attribute = "customer"; String oldValue = "true"; String newValue = "false"; return transformer.modifyAttribute(attribute, oldValue, newValue); } @Benchmark public String jooxBenchmark() throws IOException, SAXException { String path = this.getClass() .getResource("/xml/attribute.xml") .toString(); JooxTransformer transformer = new JooxTransformer(path); String attribute = "customer"; String oldValue = "true";
String newValue = "false"; return transformer.modifyAttribute(attribute, oldValue, newValue); } @Benchmark public String jaxpBenchmark() throws TransformerException, ParserConfigurationException, SAXException, IOException, XPathExpressionException { String path = this.getClass() .getResource("/xml/attribute.xml") .toString(); JaxpTransformer transformer = new JaxpTransformer(path); String attribute = "customer"; String oldValue = "true"; String newValue = "false"; return transformer.modifyAttribute(attribute, oldValue, newValue); } }
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\attribute\jmh\AttributeBenchMark.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonService { @Autowired private PersonDao personDao; @Transactional(propagation = Propagation.REQUIRED) public PersonEntity findPersonById(Long id){ Optional<PersonEntity> person = personDao.findById(id); return person.orElse(null); } @Transactional public PersonEntity updatePerson(Long id, PersonEntity person) { PersonEntity foundPerson = findPersonById(id); foundPerson.setDesignation(person.getDesignation()); foundPerson.setMobile(person.getMobile());
foundPerson.setName(person.getName()); return personDao.save(foundPerson); } @Transactional public void createPersons(List<PersonEntity> personList){ personDao.saveAll(personList); } @Transactional public List<PersonEntity> listPersons(){ return personDao.findAll(); } }
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\hibernatejfr\service\PersonService.java
2
请完成以下Java代码
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstance) { List<PlanItemInstanceEntity> childPlanItemInstances = planItemInstance.getChildPlanItemInstances(); if (childPlanItemInstances != null) { for (PlanItemInstanceEntity childPlanItemInstance : childPlanItemInstances) { if (StateTransition.isPossible(planItemInstance, PlanItemTransition.COMPLETE)) { CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(childPlanItemInstance); } } } CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstance); } @Override public void onStateTransition(CommandContext commandContext, DelegatePlanItemInstance planItemInstance, String transition) { if (PlanItemTransition.TERMINATE.equals(transition) || PlanItemTransition.EXIT.equals(transition)) { handleChildPlanItemInstances(commandContext, planItemInstance, transition); } } protected void handleChildPlanItemInstances(CommandContext commandContext, DelegatePlanItemInstance planItemInstance, String transition) { // The stage plan item will be deleted by the regular TerminatePlanItemOperation PlanItemInstanceEntity planItemInstanceEntity = (PlanItemInstanceEntity) planItemInstance;
List<PlanItemInstanceEntity> childPlanItemInstances = planItemInstanceEntity.getChildPlanItemInstances(); if (childPlanItemInstances != null) { for (PlanItemInstanceEntity childPlanItemInstance : childPlanItemInstances) { if (StateTransition.isPossible(childPlanItemInstance, transition)) { // we don't propagate the exit and exit event type to the child plan items as regardless of the parent termination type, children always // get treated the same way if (PlanItemTransition.TERMINATE.equals(transition)) { CommandContextUtil.getAgenda(commandContext).planTerminatePlanItemInstanceOperation(childPlanItemInstance, null, null); } else if (PlanItemTransition.EXIT.equals(transition)) { CommandContextUtil.getAgenda(commandContext).planExitPlanItemInstanceOperation(childPlanItemInstance, null, null, null); } } else if (PlanItemTransition.TERMINATE.equals(transition) || PlanItemTransition.EXIT.equals(transition)) { CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper() .executeLifecycleListeners(commandContext, childPlanItemInstance, childPlanItemInstance.getState(), PlanItemInstanceState.TERMINATED); } } } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\StageActivityBehavior.java
1
请完成以下Java代码
public int getMaxLevel() { return filter.getMaxLevel(); } @Override public boolean isMultiRoot() { return filter.isMultiRoot(); } @Override public boolean isFetchLastLevelOnly() { return filter.isFetchLastLevelOnly(); } @Override protected boolean check(RelationInfo relationInfo) { if (hasFilters) {
for (var f : filter.getFilters()) { if (((!filter.isNegate() && !f.isNegate()) || (filter.isNegate() && f.isNegate())) == f.getRelationType().equals(relationInfo.getType())) { if (f.getEntityTypes() == null || f.getEntityTypes().isEmpty() || f.getEntityTypes().contains(relationInfo.getTarget().getEntityType())) { return super.matches(relationInfo.getTarget()); } } } return false; } else { return super.matches(relationInfo.getTarget()); } } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\query\processor\RelationQueryProcessor.java
1
请完成以下Spring Boot application配置
server: port: 8080 # License 相关配置 license: # 主题 subject: license_demo # 公钥别称 publicAlias: publicCert # 访问公钥的密码 storePass: pubwd123456 # license 位置 licensePath: /Users/liuhaihua/IdeaProjects/springboot-demo/SoftwareLicense/src/main/resources/license/license.lic # licensePath: /root/license-test/license.lic # 公钥位置 publicKeysStorePath: /Users/liuhaih
ua/IdeaProjects/springboot-demo/SoftwareLicense/src/main/resources/license/publicCerts.keystore # publicKeysStorePath: /root/license-test/publicCerts.keystore
repos\springboot-demo-master\SoftwareLicense\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class PPOrderRoutingProductId implements RepoIdAware { PPOrderRoutingActivityId activityId; int repoId; public static PPOrderRoutingProductId ofRepoId(@NonNull final PPOrderRoutingActivityId orderId, final RepoIdAware repoId) { return ofRepoId(orderId, repoId.getRepoId()); } @JsonCreator public static PPOrderRoutingProductId ofRepoId(@NonNull final PPOrderRoutingActivityId orderId, final int repoId) { return new PPOrderRoutingProductId(orderId, repoId); } @Nullable public static PPOrderRoutingProductId ofRepoIdOrNull(@NonNull final PPOrderRoutingActivityId orderId, final int repoId) { return repoId > 0 ? new PPOrderRoutingProductId(orderId, repoId) : null; } public static int toRepoId(@Nullable final PPOrderRoutingProductId id) { return id != null ? id.getRepoId() : -1; } private PPOrderRoutingProductId(@NonNull final PPOrderRoutingActivityId activityId, final int repoId)
{ this.activityId = activityId; this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Node_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final PPOrderRoutingProductId id1, @Nullable final PPOrderRoutingProductId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingProductId.java
2
请完成以下Java代码
void postConstruct() { final IProgramaticCalloutProvider programmaticCalloutProvider = Services.get(IProgramaticCalloutProvider.class); programmaticCalloutProvider.registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_C_BPartner_QuickInput.COLUMNNAME_IsCompany) public void onIsCompanyFlagChanged(@NonNull final I_C_BPartner_QuickInput record) { bpartnerQuickInputService.updateNameAndGreetingNoSave(record); } @CalloutMethod(columnNames = I_C_BPartner_QuickInput.COLUMNNAME_C_Location_ID) public void onLocationChanged(@NonNull final I_C_BPartner_QuickInput record) { final OrgId orgInChangeId = getOrgInChangeViaLocationPostalCode(record); if (orgInChangeId == null) { return; } final boolean userHasOrgPermissions = Env.getUserRolePermissions().isOrgAccess(orgInChangeId, null, Access.WRITE); if (userHasOrgPermissions) { record.setAD_Org_ID(orgInChangeId.getRepoId()); } } @Nullable private OrgId getOrgInChangeViaLocationPostalCode(final @NonNull I_C_BPartner_QuickInput record) { final LocationId locationId = LocationId.ofRepoIdOrNull(record.getC_Location_ID()); if (locationId == null)
{ return null; } final I_C_Location locationRecord = locationDAO.getById(locationId); final PostalId postalId = PostalId.ofRepoIdOrNull(locationRecord.getC_Postal_ID()); if (postalId == null) { return null; } final I_C_Postal postalRecord = locationDAO.getPostalById(postalId); final OrgId orgInChargeId = OrgId.ofRepoId(postalRecord.getAD_Org_InCharge_ID()); return orgInChargeId.isRegular() ? orgInChargeId : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_QuickInput.java
1
请在Spring Boot框架中完成以下Java代码
public List<Batch> findBatchesBySearchKey(String searchKey) { return getBatchEntityManager().findBatchesBySearchKey(searchKey); } @Override public List<Batch> getAllBatches() { return getBatchEntityManager().findAllBatches(); } @Override public List<Batch> findBatchesByQueryCriteria(BatchQuery batchQuery) { return getBatchEntityManager().findBatchesByQueryCriteria((BatchQueryImpl) batchQuery); } @Override public long findBatchCountByQueryCriteria(BatchQuery batchQuery) { return getBatchEntityManager().findBatchCountByQueryCriteria((BatchQueryImpl) batchQuery); } @Override public BatchBuilder createBatchBuilder() { return new BatchBuilderImpl(configuration); } @Override public void insertBatch(Batch batch) { getBatchEntityManager().insert((BatchEntity) batch); } @Override public Batch updateBatch(Batch batch) { return getBatchEntityManager().update((BatchEntity) batch); } @Override public void deleteBatch(String batchId) { getBatchEntityManager().delete(batchId); } @Override public BatchPartEntity getBatchPart(String id) { return getBatchPartEntityManager().findById(id); } @Override public List<BatchPart> findBatchPartsByBatchId(String batchId) { return getBatchPartEntityManager().findBatchPartsByBatchId(batchId); } @Override public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) { return getBatchPartEntityManager().findBatchPartsByBatchIdAndStatus(batchId, status); } @Override public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) { return getBatchPartEntityManager().findBatchPartsByScopeIdAndType(scopeId, scopeType); }
@Override public BatchPart createBatchPart(Batch batch, String status, String scopeId, String subScopeId, String scopeType) { return getBatchPartEntityManager().createBatchPart((BatchEntity) batch, status, scopeId, subScopeId, scopeType); } @Override public BatchPart completeBatchPart(String batchPartId, String status, String resultJson) { return getBatchPartEntityManager().completeBatchPart(batchPartId, status, resultJson); } @Override public Batch completeBatch(String batchId, String status) { return getBatchEntityManager().completeBatch(batchId, status); } public Batch createBatch(BatchBuilder batchBuilder) { return getBatchEntityManager().createBatch(batchBuilder); } public BatchEntityManager getBatchEntityManager() { return configuration.getBatchEntityManager(); } public BatchPartEntityManager getBatchPartEntityManager() { return configuration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void configure() throws Exception { errorHandler(defaultErrorHandler()); onException(Exception.class) .to(direct(MF_ERROR_ROUTE_ID)); from(direct(ATTACH_FILE_TO_BPARTNER_ROUTE_ID)) .routeId(ATTACH_FILE_TO_BPARTNER_ROUTE_ID) .log("Route invoked!") .unmarshal(setupJacksonDataFormatFor(getContext(), JsonBPartnerAttachment.class)) .process(this::buildAndAttachContext) .process(RetrieveExternalSystemRequestBuilder::buildAndAttachRetrieveExternalSystemRequest) .to("{{" + ExternalSystemCamelConstants.MF_GET_EXTERNAL_SYSTEM_INFO + "}}") .unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonExternalSystemInfo.class)) .process(this::processExternalSystemInfo) .process(new BPartnerAttachmentsProcessor()).id(ATTACH_FILE_TO_BPARTNER_PROCESSOR_ID) .to(direct(ExternalSystemCamelConstants.MF_ATTACHMENT_ROUTE_ID)); } private void buildAndAttachContext(@NonNull final Exchange exchange) { final JsonBPartnerAttachment jsonBPartnerAttachment = exchange.getIn().getBody(JsonBPartnerAttachment.class); final BPartnerAttachmentsRouteContext routeContext = BPartnerAttachmentsRouteContext .builder() .jsonBPartnerAttachment(jsonBPartnerAttachment) .build();
exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_ATTACH_FILE_CONTEXT, routeContext); } private void processExternalSystemInfo(@NonNull final Exchange exchange) { final JsonExternalSystemInfo jsonExternalSystemInfo = exchange.getIn().getBody(JsonExternalSystemInfo.class); if (jsonExternalSystemInfo == null) { throw new RuntimeException("Missing external system info!"); } final String exportDirectoriesBasePath = jsonExternalSystemInfo.getParameters().get(PARAM_BasePathForExportDirectories); if (Check.isBlank(exportDirectoriesBasePath)) { throw new RuntimeException(PARAM_BasePathForExportDirectories + " not set for ExternalSystem_Config_ID: " + jsonExternalSystemInfo.getExternalSystemConfigId()); } final BPartnerAttachmentsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_ATTACH_FILE_CONTEXT, BPartnerAttachmentsRouteContext.class); context.setExportDirectoriesBasePath(exportDirectoriesBasePath); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\attachment\BPartnerAttachmentsRouteBuilder.java
2
请完成以下Java代码
public class DeliveryGroupCandidate { /** * A more generic replacement for orderId..needed at least for deliveryRule complete-order */ @NonNull private final DeliveryGroupCandidateGroupId groupId; @NonNull private final String bPartnerAddress; @NonNull private final WarehouseId warehouseId; @NonNull private final Optional<ShipperId> shipperId; @Default private final List<DeliveryLineCandidate> lines = new ArrayList<>(); public DeliveryLineCandidate createAndAddLineCandidate( @NonNull final I_M_ShipmentSchedule shipmentSchedule, @NonNull final CompleteStatus completeStatus) { final DeliveryLineCandidate line = new DeliveryLineCandidate(this, shipmentSchedule, completeStatus); lines.add(line); return line; }
public boolean hasLines() { return !lines.isEmpty(); } public Iterable<DeliveryLineCandidate> getLines() { return lines; } public void removeLine(@NonNull final DeliveryLineCandidate line) { lines.remove(line); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\DeliveryGroupCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public String getHostnameForClients() { return this.hostnameForClients; } public void setHostnameForClients(String hostnameForClients) { this.hostnameForClients = hostnameForClients; } public String getPasswordFile() { return this.passwordFile; } public void setPasswordFile(String passwordFile) { this.passwordFile = passwordFile; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; }
public boolean isStart() { return this.start; } public void setStart(boolean start) { this.start = start; } public int getUpdateRate() { return this.updateRate; } public void setUpdateRate(int updateRate) { this.updateRate = updateRate; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ManagerProperties.java
2
请完成以下Java代码
public I_PA_SLA_Criteria getPA_SLA_Criteria() throws RuntimeException { return (I_PA_SLA_Criteria)MTable.get(getCtx(), I_PA_SLA_Criteria.Table_Name) .getPO(getPA_SLA_Criteria_ID(), get_TrxName()); } /** Set SLA Criteria. @param PA_SLA_Criteria_ID Service Level Agreement Criteria */ public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID) { if (PA_SLA_Criteria_ID < 1) set_Value (COLUMNNAME_PA_SLA_Criteria_ID, null); else set_Value (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID)); } /** Get SLA Criteria. @return Service Level Agreement Criteria */ public int getPA_SLA_Criteria_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SLA Goal. @param PA_SLA_Goal_ID Service Level Agreement Goal */ public void setPA_SLA_Goal_ID (int PA_SLA_Goal_ID) { if (PA_SLA_Goal_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, Integer.valueOf(PA_SLA_Goal_ID)); } /** Get SLA Goal. @return Service Level Agreement Goal */ public int getPA_SLA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** 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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Goal.java
1
请完成以下Java代码
public void updateProcessBusinessKeyInHistory(ExecutionEntity processInstance) { if (isHistoryEnabled()) { if (log.isDebugEnabled()) { log.debug("updateProcessBusinessKeyInHistory : {}", processInstance.getId()); } if (processInstance != null) { HistoricProcessInstanceEntity historicProcessInstance = getHistoricProcessInstanceEntityManager().findById(processInstance.getId()); if (historicProcessInstance != null) { historicProcessInstance.setBusinessKey(processInstance.getProcessInstanceBusinessKey()); getHistoricProcessInstanceEntityManager().update(historicProcessInstance, false); } } } } @Override public void recordVariableRemoved(VariableInstanceEntity variable) { if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) { HistoricVariableInstanceEntity historicProcessVariable = getEntityCache().findInCache( HistoricVariableInstanceEntity.class, variable.getId() ); if (historicProcessVariable == null) { historicProcessVariable = getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceByVariableInstanceId( variable.getId() ); } if (historicProcessVariable != null) { getHistoricVariableInstanceEntityManager().delete(historicProcessVariable); } } } protected String parseActivityType(FlowElement element) {
String elementType = element.getClass().getSimpleName(); elementType = elementType.substring(0, 1).toLowerCase() + elementType.substring(1); return elementType; } protected EntityCache getEntityCache() { return getSession(EntityCache.class); } public HistoryLevel getHistoryLevel() { return historyLevel; } public void setHistoryLevel(HistoryLevel historyLevel) { this.historyLevel = historyLevel; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\history\DefaultHistoryManager.java
1
请完成以下Java代码
public class SysCheckRule { /** * 主键id */ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "主键id") private String id; /** * 规则名称 */ @Excel(name = "规则名称", width = 15) @Schema(description = "规则名称") private String ruleName; /** * 规则Code */ @Excel(name = "规则Code", width = 15) @Schema(description = "规则Code") private String ruleCode; /** * 规则JSON */ @Excel(name = "规则JSON", width = 15) @Schema(description = "规则JSON") private String ruleJson; /** * 规则描述 */ @Excel(name = "规则描述", width = 15) @Schema(description = "规则描述") private String ruleDescription; /**
* 更新人 */ @Excel(name = "更新人", width = 15) @Schema(description = "更新人") private String updateBy; /** * 更新时间 */ @Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Schema(description = "更新时间") private Date updateTime; /** * 创建人 */ @Excel(name = "创建人", width = 15) @Schema(description = "创建人") private String createBy; /** * 创建时间 */ @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Schema(description = "创建时间") private Date createTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysCheckRule.java
1
请完成以下Java代码
public void windowClosed(final WindowEvent e) { // // Re-enable frame parentFrame.setFocusable(true); parentFrame.setEnabled(true); modalFrame.removeWindowListener(this); if (onCloseCallback != null) { onCloseCallback.run(); } parentFrame.toFront(); } }); parentFrame.addWindowListener(new WindowAdapter() { @Override public void windowActivated(final WindowEvent e) { windowGainedFocus(e); } @Override public void windowDeactivated(final WindowEvent e) { // nothing } @Override public void windowGainedFocus(final WindowEvent e) { EventQueue.invokeLater(() -> { if (modalFrame == null || !modalFrame.isVisible() || !modalFrame.isShowing()) { return; } modalFrame.toFront(); modalFrame.repaint(); }); } @Override public void windowLostFocus(final WindowEvent e) { // nothing } });
if (modalFrame instanceof CFrame) { addToWindowManager(modalFrame); } showCenterWindow(parentFrame, modalFrame); } /** * Create a {@link FormFrame} for the given {@link I_AD_Form}. * * @return formFrame which was created or null */ public static FormFrame createForm(final I_AD_Form form) { final FormFrame formFrame = new FormFrame(); if (formFrame.openForm(form)) { formFrame.pack(); return formFrame; } else { formFrame.dispose(); return null; } } } // AEnv
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AEnv.java
1
请完成以下Java代码
public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set 'Value' anzeigen. @param IsValueDisplayed Displays Value column with the Display column */ @Override public void setIsValueDisplayed (boolean IsValueDisplayed) { set_Value (COLUMNNAME_IsValueDisplayed, Boolean.valueOf(IsValueDisplayed)); } /** Get 'Value' anzeigen. @return Displays Value column with the Display column */ @Override public boolean isValueDisplayed () { Object oo = get_Value(COLUMNNAME_IsValueDisplayed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql ORDER BY. @param OrderByClause Fully qualified ORDER BY clause */ @Override public void setOrderByClause (java.lang.String OrderByClause) { set_Value (COLUMNNAME_OrderByClause, OrderByClause); } /** Get Sql ORDER BY. @return Fully qualified ORDER BY clause */ @Override public java.lang.String getOrderByClause ()
{ return (java.lang.String)get_Value(COLUMNNAME_OrderByClause); } /** Set Inaktive Werte anzeigen. @param ShowInactiveValues Inaktive Werte anzeigen */ @Override public void setShowInactiveValues (boolean ShowInactiveValues) { set_Value (COLUMNNAME_ShowInactiveValues, Boolean.valueOf(ShowInactiveValues)); } /** Get Inaktive Werte anzeigen. @return Inaktive Werte anzeigen */ @Override public boolean isShowInactiveValues () { Object oo = get_Value(COLUMNNAME_ShowInactiveValues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ @Override public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableMap<AsyncBatchId, List<OLCandId>> getAsyncBatchId2OLCandIds(@NonNull final Set<OLCandId> olCandIds) { if (olCandIds.isEmpty()) { return ImmutableMap.of(); } final Map<OLCandId, I_C_OLCand> olCandsById = olCandDAO.retrieveByIds(olCandIds); final HashMap<AsyncBatchId, ArrayList<OLCandId>> asyncBatchId2OLCands = new HashMap<>(); for (final I_C_OLCand olCand : olCandsById.values()) { final AsyncBatchId currentAsyncBatchId = AsyncBatchId.ofRepoIdOrNone(olCand.getC_Async_Batch_ID()); final ArrayList<OLCandId> currentOLCands = new ArrayList<>(); currentOLCands.add(OLCandId.ofRepoId(olCand.getC_OLCand_ID())); asyncBatchId2OLCands.merge(currentAsyncBatchId, currentOLCands, CollectionUtils::mergeLists); } Optional.ofNullable(asyncBatchId2OLCands.get(AsyncBatchId.NONE_ASYNC_BATCH_ID)) .ifPresent(noAsyncBatchOLCands -> { // The asyncBatchId will be propagated through C_OLCand, M_ShipmentSchedule and C_Invoice_candidate. // It will be used when we create workpackages (and wait for them!) that in turn create actual the actual orders, shipments and invoices final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch(C_Async_Batch_InternalName_OLCand_Processing); olCandDAO.assignAsyncBatchId(olCandIds, asyncBatchId); asyncBatchId2OLCands.put(asyncBatchId, noAsyncBatchOLCands); asyncBatchId2OLCands.remove(AsyncBatchId.NONE_ASYNC_BATCH_ID); }); return ImmutableMap.copyOf(asyncBatchId2OLCands); } @NonNull public ImmutableSet<ShipmentScheduleId> generateSchedules(@NonNull final OrderId orderId) {
final I_C_Order order = orderDAO.getById(orderId); if (!order.getDocStatus().equals(DOCSTATUS_Completed)) { Loggables.withLogger(logger, Level.INFO).addLog("Returning! Order not COMPLETED!"); return ImmutableSet.of(); } generateMissingShipmentSchedulesFromOrder(order); return shipmentSchedulePA.retrieveScheduleIdsByOrderId(orderId); } private void generateOrdersForBatch( @NonNull final AsyncBatchId asyncBatchId, final boolean propagateAsyncIdsToShipmentSchduleWPs) { final Supplier<IEnqueueResult> action = () -> olCandToOrderEnqueuer.enqueueBatch(asyncBatchId, propagateAsyncIdsToShipmentSchduleWPs); asyncBatchService.executeBatch(action, asyncBatchId); } private void generateMissingShipmentSchedulesFromOrder(@NonNull final I_C_Order order) { final ImmutablePair<AsyncBatchId, I_C_Order> batchIdWithOrder = asyncBatchBL.assignPermAsyncBatchToModelIfMissing(order, C_Async_Batch_InternalName_EnqueueScheduleForOrder); final Supplier<IEnqueueResult> action = () -> CreateMissingShipmentSchedulesWorkpackageProcessor.scheduleIfNotPostponed(batchIdWithOrder.getRight()); asyncBatchService.executeBatch(action, batchIdWithOrder.getLeft()); } }
repos\metasfresh-new_dawn_uat\backend\de-metas-salesorder\src\main\java\de\metas\salesorder\service\OrderService.java
2
请完成以下Java代码
protected CostDetailCreateResult createCostForProjectIssue( @SuppressWarnings("unused") final CostDetailCreateRequest request) { throw new UnsupportedOperationException(); } protected CostDetailCreateResult createCostRevaluationLine( @NonNull final CostDetailCreateRequest request) { if (!request.getQty().isZero()) { throw new AdempiereException("Cost revaluation requests shall have Qty=0"); } final CostAmount explicitCostPrice = request.getExplicitCostPrice(); if (explicitCostPrice == null) { throw new AdempiereException("Cost revaluation requests shall have explicit cost price set"); } final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); currentCosts.setOwnCostPrice(explicitCostPrice); currentCosts.addCumulatedAmt(request.getAmt()); final CostDetailCreateResult result = utils.createCostDetailRecordWithChangedCosts( request, previousCosts); utils.saveCurrentCost(currentCosts); return result; } protected CostDetailCreateResult createCostForMaterialReceipt_NonMaterialCosts(CostDetailCreateRequest request) { throw new AdempiereException("Costing method " + getCostingMethod() + " does not support non material costs receipt") .setParameter("request", request) .appendParametersToMessage(); } protected abstract CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request); @Override public CostDetailAdjustment recalculateCostDetailAmountAndUpdateCurrentCost( @NonNull final CostDetail costDetail, @NonNull final CurrentCost currentCost) { if (costDetail.getDocumentRef().isCostRevaluationLine()) { throw new AdempiereException(MSG_RevaluatingAnotherRevaluationIsNotSupported) .setParameter("costDetail", costDetail); } final CurrencyPrecision precision = currentCost.getPrecision();
final Quantity qty = costDetail.getQty(); final CostAmount oldCostAmount = costDetail.getAmt(); final CostAmount oldCostPrice = qty.signum() != 0 ? oldCostAmount.divide(qty, precision) : oldCostAmount; final CostAmount newCostPrice = currentCost.getCostPrice().toCostAmount(); final CostAmount newCostAmount = qty.signum() != 0 ? newCostPrice.multiply(qty).roundToPrecisionIfNeeded(precision) : newCostPrice.roundToPrecisionIfNeeded(precision); if (costDetail.isInboundTrx()) { currentCost.addWeightedAverage(newCostAmount, qty, utils.getQuantityUOMConverter()); } else { currentCost.addToCurrentQtyAndCumulate(qty, newCostAmount, utils.getQuantityUOMConverter()); } // return CostDetailAdjustment.builder() .costDetailId(costDetail.getId()) .qty(qty) .oldCostPrice(oldCostPrice) .oldCostAmount(oldCostAmount) .newCostPrice(newCostPrice) .newCostAmount(newCostAmount) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostingMethodHandlerTemplate.java
1
请完成以下Java代码
private int computePageSize(final int firstRow) { final int remainingRows = lastRow - firstRow; if (remainingRows <= 0) { return 0; } return Math.min(pageSize, remainingRows); } private int computeNextPageFirstRow(final int firstRow, final int pageSize) { return firstRow + pageSize; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } return currentPageIterator.next(); } public Stream<E> stream() { return IteratorUtils.stream(this); } @lombok.Value public static final class Page<E> { public static <E> Page<E> ofRows(final List<E> rows) { final Integer lastRow = null; return new Page<>(rows, lastRow); } public static <E> Page<E> ofRowsOrNull(final List<E> rows) { return rows != null && !rows.isEmpty() ? ofRows(rows)
: null; } public static <E> Page<E> ofRowsAndLastRowIndex(final List<E> rows, final int lastRowZeroBased) { return new Page<>(rows, lastRowZeroBased); } private final List<E> rows; private final Integer lastRowZeroBased; private Page(final List<E> rows, final Integer lastRowZeroBased) { Check.assumeNotEmpty(rows, "rows is not empty"); Check.assume(lastRowZeroBased == null || lastRowZeroBased >= 0, "lastRow shall be null, positive or zero"); this.rows = rows; this.lastRowZeroBased = lastRowZeroBased; } } /** Loads and provides the requested page */ @FunctionalInterface public interface PageFetcher<E> { /** * @param firstRow (first page is ZERO) * @param pageSize max rows to return * @return page or null in case there is no page */ Page<E> getPage(int firstRow, int pageSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\PagedIterator.java
1
请在Spring Boot框架中完成以下Java代码
AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException { try { URI uri = getPermissionsUri(applicationId); RequestEntity<?> request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build(); Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody(); if (body != null && Boolean.TRUE.equals(body.get("read_sensitive_data"))) { return AccessLevel.FULL; } return AccessLevel.RESTRICTED; } catch (HttpClientErrorException ex) { if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) { throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied"); } throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex); } catch (HttpServerErrorException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable"); } } private URI getPermissionsUri(String applicationId) { try { return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions"); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); } } /** * Return all token keys known by the UAA. * @return a map of token keys */ Map<String, String> fetchTokenKeys() { try { Map<?, ?> response = this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class); Assert.state(response != null, "'response' must not be null"); return extractTokenKeys(response); } catch (HttpStatusCodeException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable"); }
} private Map<String, String> extractTokenKeys(Map<?, ?> response) { Map<String, String> tokenKeys = new HashMap<>(); List<?> keys = (List<?>) response.get("keys"); Assert.state(keys != null, "'keys' must not be null"); for (Object key : keys) { Map<?, ?> tokenKey = (Map<?, ?>) key; tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value")); } return tokenKeys; } /** * Return the URL of the UAA. * @return the UAA url */ String getUaaUrl() { if (this.uaaUrl == null) { try { Map<?, ?> response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class); Assert.state(response != null, "'response' must not be null"); String tokenEndpoint = (String) response.get("token_endpoint"); Assert.state(tokenEndpoint != null, "'tokenEndpoint' must not be null"); this.uaaUrl = tokenEndpoint; } catch (HttpStatusCodeException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Unable to fetch token keys from UAA"); } } return this.uaaUrl; } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\SecurityService.java
2
请完成以下Java代码
public class DeleteHistoricTaskInstanceCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; public DeleteHistoricTaskInstanceCmd(String taskId) { this.taskId = taskId; } @Override public Object execute(CommandContext commandContext) { if (taskId == null) { throw new FlowableIllegalArgumentException("taskId is null"); }
// Check if task is completed HistoricTaskInstanceEntity historicTaskInstance = CommandContextUtil.getHistoricTaskService().getHistoricTask(taskId); if (historicTaskInstance == null) { throw new FlowableObjectNotFoundException("No historic task instance found with id: " + taskId, HistoricTaskInstance.class); } if (historicTaskInstance.getEndTime() == null) { throw new FlowableException("task does not have an endTime, cannot delete " + historicTaskInstance); } CommandContextUtil.getCmmnHistoryManager(commandContext).recordHistoricTaskDeleted(historicTaskInstance); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteHistoricTaskInstanceCmd.java
1
请完成以下Java代码
public void setCompany(CompanyType value) { this.company = value; } /** * Gets the value of the employee property. * * @return * possible object is * {@link EmployeeType } * */ public EmployeeType getEmployee() { return employee; } /** * Sets the value of the employee property. * * @param value * allowed object is * {@link EmployeeType } * */ public void setEmployee(EmployeeType value) { this.employee = value; } /** * Gets the value of the eanParty property. *
* @return * possible object is * {@link String } * */ public String getEanParty() { return eanParty; } /** * Sets the value of the eanParty property. * * @param value * allowed object is * {@link String } * */ public void setEanParty(String value) { this.eanParty = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ContactAddressType.java
1
请在Spring Boot框架中完成以下Java代码
public MobileUIDistributionConfig getConfig() {return configRepository.getConfig();} public ProductInfo getProductInfo(@NonNull final ProductId productId) { return productService.getProductInfo(productId); } public WarehouseInfo getWarehouseInfoByRepoId(final int warehouseRepoId) { return warehouseService.getWarehouseInfoByRepoId(warehouseRepoId); } public LocatorInfo getLocatorInfoByRepoId(final int locatorRepoId) { return warehouseService.getLocatorInfoByRepoId(locatorRepoId); } public Stream<I_DD_Order> stream(@NonNull final DDOrderQuery query) { return ddOrderService.streamDDOrders(query); } public I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrderService.getById(ddOrderId); } public Map<DDOrderId, List<I_DD_OrderLine>> getLinesByDDOrderIds(final Set<DDOrderId> ddOrderIds) { return ddOrderService.streamLinesByDDOrderIds(ddOrderIds) .collect(Collectors.groupingBy(ddOrderLine -> DDOrderId.ofRepoId(ddOrderLine.getDD_Order_ID()), Collectors.toList())); } public Map<DDOrderLineId, List<DDOrderMoveSchedule>> getSchedulesByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds) { if (ddOrderLineIds.isEmpty()) {return ImmutableMap.of();} final Map<DDOrderLineId, List<DDOrderMoveSchedule>> map = ddOrderMoveScheduleService.getByDDOrderLineIds(ddOrderLineIds) .stream() .collect(Collectors.groupingBy(DDOrderMoveSchedule::getDdOrderLineId, Collectors.toList())); return CollectionUtils.fillMissingKeys(map, ddOrderLineIds, ImmutableList.of()); } public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId)
{ return ddOrderMoveScheduleService.hasInTransitSchedules(inTransitLocatorId); } public ZoneId getTimeZone(final OrgId orgId) { return orgDAO.getTimeZone(orgId); } public HUInfo getHUInfo(final HuId huId) {return huService.getHUInfoById(huId);} @Nullable public SalesOrderRef getSalesOderRef(@NonNull final I_DD_Order ddOrder) { final OrderId salesOrderId = OrderId.ofRepoIdOrNull(ddOrder.getC_Order_ID()); return salesOrderId != null ? sourceDocService.getSalesOderRef(salesOrderId) : null; } @Nullable public ManufacturingOrderRef getManufacturingOrderRef(@NonNull final I_DD_Order ddOrder) { final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID()); return ppOrderId != null ? sourceDocService.getManufacturingOrderRef(ppOrderId) : null; } @NonNull public PlantInfo getPlantInfo(@NonNull final ResourceId plantId) { return sourceDocService.getPlantInfo(plantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoaderSupportingServices.java
2
请完成以下Java代码
public void setQtyDeliveredInInvoiceUOM (final @Nullable BigDecimal QtyDeliveredInInvoiceUOM) { set_Value (COLUMNNAME_QtyDeliveredInInvoiceUOM, QtyDeliveredInInvoiceUOM); } @Override public BigDecimal getQtyDeliveredInInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyDeliveredInStockingUOM (final BigDecimal QtyDeliveredInStockingUOM) { set_Value (COLUMNNAME_QtyDeliveredInStockingUOM, QtyDeliveredInStockingUOM); } @Override public BigDecimal getQtyDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setQtyDeliveredInUOM (final BigDecimal QtyDeliveredInUOM) { set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM); } @Override public BigDecimal getQtyDeliveredInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM) { set_Value (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM); } @Override public BigDecimal getQtyEnteredInBPartnerUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine_InOutLine.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Export Processor Type. @param EXP_Processor_Type_ID Export Processor Type */ public void setEXP_Processor_Type_ID (int EXP_Processor_Type_ID) { if (EXP_Processor_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_EXP_Processor_Type_ID, Integer.valueOf(EXP_Processor_Type_ID)); } /** Get Export Processor Type. @return Export Processor Type */ public int getEXP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Java Class. @param JavaClass Java Class */ public void setJavaClass (String JavaClass) { set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */ public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); } /** 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); } /** 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\compiere\model\X_EXP_Processor_Type.java
1
请完成以下Java代码
public class StackWalkerDemo { public void methodOne() { this.methodTwo(); } public void methodTwo() { this.methodThree(); } public void methodThree() { List<StackFrame> stackTrace = StackWalker.getInstance() .walk(this::walkExample); printStackTrace(stackTrace); System.out.println("---------------------------------------------"); stackTrace = StackWalker.getInstance() .walk(this::walkExample2); printStackTrace(stackTrace); System.out.println("---------------------------------------------"); String line = StackWalker.getInstance().walk(this::walkExample3); System.out.println(line); System.out.println("---------------------------------------------"); stackTrace = StackWalker.getInstance(StackWalker.Option.SHOW_REFLECT_FRAMES) .walk(this::walkExample); printStackTrace(stackTrace); System.out.println("---------------------------------------------"); Runnable r = () -> { List<StackFrame> stackTrace2 = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES) .walk(this::walkExample); printStackTrace(stackTrace2); }; r.run(); } public List<StackFrame> walkExample(Stream<StackFrame> stackFrameStream) { return stackFrameStream.collect(Collectors.toList()); }
public List<StackFrame> walkExample2(Stream<StackFrame> stackFrameStream) { return stackFrameStream.filter(frame -> frame.getClassName() .contains("com.baeldung")) .collect(Collectors.toList()); } public String walkExample3(Stream<StackFrame> stackFrameStream) { return stackFrameStream.filter(frame -> frame.getClassName() .contains("com.baeldung") && frame.getClassName() .endsWith("Test")) .findFirst() .map(frame -> frame.getClassName() + "#" + frame.getMethodName() + ", Line " + frame.getLineNumber()) .orElse("Unknown caller"); } public void findCaller() { Class<?> caller = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass(); System.out.println(caller.getCanonicalName()); } public void printStackTrace(List<StackFrame> stackTrace) { for (StackFrame stackFrame : stackTrace) { System.out.println(stackFrame.getClassName() .toString() + "#" + stackFrame.getMethodName() + ", Line " + stackFrame.getLineNumber()); } } }
repos\tutorials-master\core-java-modules\core-java-9-new-features\src\main\java\com\baeldung\java9\stackwalker\StackWalkerDemo.java
1
请完成以下Java代码
public org.compiere.model.I_PP_ComponentGenerator getPP_ComponentGenerator() { return get_ValueAsPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class); } @Override public void setPP_ComponentGenerator(final org.compiere.model.I_PP_ComponentGenerator PP_ComponentGenerator) { set_ValueFromPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class, PP_ComponentGenerator); } @Override public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID) { if (PP_ComponentGenerator_ID < 1) set_Value (COLUMNNAME_PP_ComponentGenerator_ID, null); else set_Value (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID); } @Override public int getPP_ComponentGenerator_ID()
{ return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID); } @Override public void setPP_ComponentGenerator_Param_ID (final int PP_ComponentGenerator_Param_ID) { if (PP_ComponentGenerator_Param_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, PP_ComponentGenerator_Param_ID); } @Override public int getPP_ComponentGenerator_Param_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_Param_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator_Param.java
1
请完成以下Java代码
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (this.defaultFailureUrl == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Sending 401 Unauthorized error since no failure URL is set"); } else { this.logger.debug("Sending 401 Unauthorized error"); } response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); return; } saveException(request, exception); if (this.forwardToDestination) { this.logger.debug("Forwarding to " + this.defaultFailureUrl); request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response); } else { this.redirectStrategy.sendRedirect(request, response, this.defaultFailureUrl); } } /** * Caches the {@code AuthenticationException} for use in view rendering. * <p> * If {@code forwardToDestination} is set to true, request scope will be used, * otherwise it will attempt to store the exception in the session. If there is no * session and {@code allowSessionCreation} is {@code true} a session will be created. * Otherwise the exception will not be stored. */ protected final void saveException(HttpServletRequest request, AuthenticationException exception) { if (this.forwardToDestination) { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); return; } HttpSession session = request.getSession(false); if (session != null || this.allowSessionCreation) { request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); } } /** * The URL which will be used as the failure destination. * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp". */ public void setDefaultFailureUrl(String defaultFailureUrl) { Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), () -> "'" + defaultFailureUrl + "' is not a valid redirect URL"); this.defaultFailureUrl = defaultFailureUrl; } protected boolean isUseForward() { return this.forwardToDestination; } /** * If set to <tt>true</tt>, performs a forward to the failure destination URL instead
* of a redirect. Defaults to <tt>false</tt>. */ public void setUseForward(boolean forwardToDestination) { this.forwardToDestination = forwardToDestination; } /** * Allows overriding of the behaviour when redirecting to a target URL. */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return this.redirectStrategy; } protected boolean isAllowSessionCreation() { return this.allowSessionCreation; } public void setAllowSessionCreation(boolean allowSessionCreation) { this.allowSessionCreation = allowSessionCreation; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SimpleUrlAuthenticationFailureHandler.java
1
请完成以下Java代码
public BigDecimal adjustQty (BigDecimal difference) { BigDecimal diff = difference.setScale(m_precision, BigDecimal.ROUND_HALF_UP); BigDecimal qty = getQty(); BigDecimal max = getMinQty().subtract(qty); BigDecimal remaining = Env.ZERO; if (max.compareTo(diff) > 0) // diff+max are negative { remaining = diff.subtract(max); setQty(qty.add(max)); } else setQty(qty.add(diff)); log.debug("Qty=" + qty + ", Min=" + getMinQty() + ", Max=" + max + ", Diff=" + diff + ", newQty=" + getQty() + ", Remaining=" + remaining); return remaining; } // adjustQty
/** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MDistributionRunDetail[") .append (get_ID ()) .append (";M_DistributionListLine_ID=").append (getM_DistributionListLine_ID()) .append(";Qty=").append(getQty()) .append(";Ratio=").append(getRatio()) .append(";MinQty=").append(getMinQty()) .append ("]"); return sb.toString (); } // toString } // DistributionRunDetail
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDistributionRunDetail.java
1
请完成以下Java代码
final class DocTax { // services private final AccountProvider accountProvider; @NonNull @Getter private final TaxId taxId; @NonNull private final String taxName; @NonNull @Setter private BigDecimal taxBaseAmt; @NonNull @Getter @Setter private BigDecimal taxAmt; @NonNull @Getter @Setter private BigDecimal reverseChargeTaxAmt; @NonNull private BigDecimal includedTaxAmt = BigDecimal.ZERO; private final boolean salesTax; @Getter private final boolean taxIncluded; @Getter private final boolean isReverseCharge; @Builder private DocTax( @NonNull final AccountProvider accountProvider, @NonNull final TaxId taxId, @NonNull final String taxName, @NonNull final BigDecimal taxBaseAmt, @NonNull final BigDecimal taxAmt, @NonNull final BigDecimal reverseChargeTaxAmt, final boolean salesTax, final boolean taxIncluded, final boolean isReverseCharge) { this.accountProvider = accountProvider; this.taxId = taxId; this.taxName = taxName; this.taxBaseAmt = taxBaseAmt; this.taxAmt = taxAmt; this.salesTax = salesTax; this.taxIncluded = taxIncluded; this.isReverseCharge = isReverseCharge; this.reverseChargeTaxAmt = reverseChargeTaxAmt; } public static DocTaxBuilder builderFrom(@NonNull final Tax tax) { return DocTax.builder() .taxId(tax.getTaxId()) .taxName(tax.getName()) .salesTax(tax.isSalesTax()) .isReverseCharge(tax.isReverseCharge()); } @Override public String toString()
{ return "Tax=(" + taxName + " TaxAmt=" + taxAmt + ")"; } @NonNull public Account getTaxCreditOrExpense(@NonNull final AcctSchema as) { return accountProvider.getTaxAccount(as.getId(), taxId, TaxAcctType.getAPTaxType(salesTax)); } @NonNull public Account getTaxDueAcct(@NonNull final AcctSchema as) { return accountProvider.getTaxAccount(as.getId(), taxId, TaxAcctType.TaxDue); } public int getC_Tax_ID() {return taxId.getRepoId();} public String getDescription() {return taxName + " " + taxBaseAmt;} public void addIncludedTax(final BigDecimal amt) { includedTaxAmt = includedTaxAmt.add(amt); } /** * @return tax amount - included tax amount */ public BigDecimal getIncludedTaxDifference() { return taxAmt.subtract(includedTaxAmt); } /** * Included Tax differs from tax amount * * @return true if difference */ public boolean isIncludedTaxDifference() {return getIncludedTaxDifference().signum() != 0;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTax.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPriceStd (final BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } @Override public BigDecimal getPriceStd() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPricingSystem_Value (final @Nullable java.lang.String PricingSystem_Value) { set_Value (COLUMNNAME_PricingSystem_Value, PricingSystem_Value); } @Override public java.lang.String getPricingSystem_Value() { return get_ValueAsString(COLUMNNAME_PricingSystem_Value); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM);
} @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java
1
请完成以下Java代码
public class POValueConverters { @Nullable public static Object convertFromPOValue(@Nullable final Object value, final int displayType, @NonNull final ZoneId zoneId) { if (value == null) { return null; } if (value.getClass().equals(Timestamp.class)) { if (displayType == DisplayType.Time) { return TimeUtil.asLocalTime(value, zoneId); } else if (displayType == DisplayType.Date) { return TimeUtil.asLocalDate(value, zoneId); } else if (displayType == DisplayType.DateTime) { return TimeUtil.asInstant(value, zoneId); } } return value; } @Nullable public static Object convertToPOValue(@Nullable final Object value, @NonNull final Class<?> targetClass, final int displayType,@NonNull final ZoneId zoneId) { if (value == null) { return null; } final Class<?> valueClass = value.getClass(); if (targetClass.isAssignableFrom(valueClass)) { return value; } else if (Integer.class.equals(targetClass)) { if (String.class.equals(valueClass)) { return new BigDecimal((String)value).intValue(); } else if (RepoIdAware.class.isAssignableFrom(valueClass)) { final RepoIdAware repoIdAware = (RepoIdAware)value; return repoIdAware.getRepoId(); } }
else if (String.class.equals(targetClass)) { return String.valueOf(value); } else if (Timestamp.class.equals(targetClass)) { final Object valueDate = DateTimeConverters.fromObject(value, displayType, zoneId); return TimeUtil.asTimestamp(valueDate); } else if (Boolean.class.equals(targetClass)) { if (String.class.equals(valueClass)) { return StringUtils.toBoolean(value); } } else if (BigDecimal.class.equals(targetClass)) { if (Double.class.equals(valueClass)) { return BigDecimal.valueOf((Double)value); } else if (Float.class.equals(valueClass)) { return BigDecimal.valueOf((Float)value); } else if (String.class.equals(valueClass)) { return new BigDecimal((String)value); } else if (Integer.class.equals(valueClass)) { return BigDecimal.valueOf((Integer)value); } } throw new RuntimeException("TargetClass " + targetClass + " does not match any supported classes!"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\POValueConverters.java
1
请完成以下Java代码
public ImmutableSet<ResourceId> getResourceIdsByUserId(@NonNull final UserId userId) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Resource.COLUMNNAME_AD_User_ID, userId) .create() .idsAsSet(ResourceId::ofRepoId); } @Override public ImmutableSet<ResourceId> getResourceIdsByResourceTypeIds(@NonNull final Collection<ResourceTypeId> resourceTypeIds) { if (resourceTypeIds.isEmpty()) { return ImmutableSet.of(); } final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter()
.addInArrayFilter(I_S_Resource.COLUMNNAME_S_ResourceType_ID, resourceTypeIds) .create() .idsAsSet(ResourceId::ofRepoId); } @Override public ImmutableSet<ResourceId> getActivePlantIds() { return queryBL.createQueryBuilder(I_S_Resource.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_Resource.COLUMNNAME_ManufacturingResourceType, X_S_Resource.MANUFACTURINGRESOURCETYPE_Plant) .create() .idsAsSet(ResourceId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\impl\ResourceDAO.java
1
请完成以下Java代码
protected static <T> Deque<T> getStack(ThreadLocal<Deque<T>> threadLocal) { Deque<T> stack = threadLocal.get(); if (stack==null) { stack = new ArrayDeque<T>(); threadLocal.set(stack); } return stack; } public static JobExecutorContext getJobExecutorContext() { return jobExecutorContextThreadLocal.get(); } public static void setJobExecutorContext(JobExecutorContext jobExecutorContext) { jobExecutorContextThreadLocal.set(jobExecutorContext); } public static void removeJobExecutorContext() { jobExecutorContextThreadLocal.remove(); } public static ProcessApplicationReference getCurrentProcessApplication() { Deque<ProcessApplicationReference> stack = getStack(processApplicationContext); if(stack.isEmpty()) { return null; } else { return stack.peek(); } } public static void setCurrentProcessApplication(ProcessApplicationReference reference) { Deque<ProcessApplicationReference> stack = getStack(processApplicationContext); stack.push(reference); } public static void removeCurrentProcessApplication() { Deque<ProcessApplicationReference> stack = getStack(processApplicationContext); stack.pop(); } /** * Use {@link #executeWithinProcessApplication(Callable, ProcessApplicationReference, InvocationContext)} * instead if an {@link InvocationContext} is available. */ public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference) { return executeWithinProcessApplication(callback, processApplicationReference, null); } public static <T> T executeWithinProcessApplication(Callable<T> callback, ProcessApplicationReference processApplicationReference, InvocationContext invocationContext) { String paName = processApplicationReference.getName(); try { ProcessApplicationInterface processApplication = processApplicationReference.getProcessApplication(); setCurrentProcessApplication(processApplicationReference);
try { // wrap callback ProcessApplicationClassloaderInterceptor<T> wrappedCallback = new ProcessApplicationClassloaderInterceptor<T>(callback); // execute wrapped callback return processApplication.execute(wrappedCallback, invocationContext); } catch (Exception e) { // unwrap exception if(e.getCause() != null && e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); }else { throw new ProcessEngineException("Unexpected exeption while executing within process application ", e); } } finally { removeCurrentProcessApplication(); } } catch (ProcessApplicationUnavailableException e) { throw new ProcessEngineException("Cannot switch to process application '"+paName+"' for execution: "+e.getMessage(), e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\context\Context.java
1
请完成以下Java代码
public int read(ByteBuffer dst) throws IOException { assertNotClosed(); int total = 0; while (dst.remaining() > 0) { int count = this.resources.getData().read(dst, this.position); if (count <= 0) { return (total != 0) ? 0 : count; } total += count; this.position += count; } return total; } @Override public int write(ByteBuffer src) throws IOException { throw new NonWritableChannelException(); } @Override public long position() throws IOException { assertNotClosed(); return this.position; } @Override public SeekableByteChannel position(long position) throws IOException { assertNotClosed(); if (position < 0 || position >= this.size) { throw new IllegalArgumentException("Position must be in bounds"); } this.position = position; return this; } @Override public long size() throws IOException { assertNotClosed(); return this.size; } @Override public SeekableByteChannel truncate(long size) throws IOException { throw new NonWritableChannelException(); } private void assertNotClosed() throws ClosedChannelException { if (this.closed) { throw new ClosedChannelException(); } } /** * Resources used by the channel and suitable for registration with a {@link Cleaner}. */ static class Resources implements Runnable { private final ZipContent zipContent; private final CloseableDataBlock data; Resources(Path path, String nestedEntryName) throws IOException { this.zipContent = ZipContent.open(path, nestedEntryName); this.data = this.zipContent.openRawZipData(); } DataBlock getData() { return this.data;
} @Override public void run() { releaseAll(); } private void releaseAll() { IOException exception = null; try { this.data.close(); } catch (IOException ex) { exception = ex; } try { this.zipContent.close(); } catch (IOException ex) { if (exception != null) { ex.addSuppressed(exception); } exception = ex; } if (exception != null) { throw new UncheckedIOException(exception); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java
1
请完成以下Java代码
public Long getActivityId() { return activityId; } public void setActivityId(Long activityId) { this.activityId = activityId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String getAddress() { return address;
} public void setAddress(String address) { this.address = address; } /** * 验证组1 */ public interface ParameterGroup1 { } /** * 验证组2 */ public interface ParameterGroup2 { } }
repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\param\InputParam.java
1
请完成以下Java代码
static MultiValueMap<String, String> getFormParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameterMap.forEach((key, values) -> { String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : ""; // If not query parameter then it's a form parameter if (!queryString.contains(key) && values.length > 0) { for (String value : values) { parameters.add(key, value); } } }); return parameters; }
static MultiValueMap<String, String> getQueryParameters(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameterMap.forEach((key, values) -> { String queryString = StringUtils.hasText(request.getQueryString()) ? request.getQueryString() : ""; if (queryString.contains(key) && values.length > 0) { for (String value : values) { parameters.add(key, value); } } }); return parameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\authentication\OAuth2EndpointUtils.java
1
请完成以下Java代码
public UserOperationLogContextEntryBuilder processDefinitionId(String processDefinitionId) { entry.setProcessDefinitionId(processDefinitionId); return this; } public UserOperationLogContextEntryBuilder processDefinitionKey(String processDefinitionKey) { entry.setProcessDefinitionKey(processDefinitionKey); return this; } public UserOperationLogContextEntryBuilder processInstanceId(String processInstanceId) { entry.setProcessInstanceId(processInstanceId); return this; } public UserOperationLogContextEntryBuilder caseDefinitionId(String caseDefinitionId) { entry.setCaseDefinitionId(caseDefinitionId); return this; } public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) { entry.setDeploymentId(deploymentId); return this; } public UserOperationLogContextEntryBuilder batchId(String batchId) { entry.setBatchId(batchId); return this;
} public UserOperationLogContextEntryBuilder taskId(String taskId) { entry.setTaskId(taskId); return this; } public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) { entry.setCaseInstanceId(caseInstanceId); return this; } public UserOperationLogContextEntryBuilder category(String category) { entry.setCategory(category); return this; } public UserOperationLogContextEntryBuilder annotation(String annotation) { entry.setAnnotation(annotation); return this; } public UserOperationLogContextEntryBuilder tenantId(String tenantId) { entry.setTenantId(tenantId); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java
1
请完成以下Java代码
public class Base64UrlNamingStrategy implements NamingStrategy { private static final int SIXTEEN = 16; /** * The default instance - using {@code spring.gen-} as the prefix. */ public static final Base64UrlNamingStrategy DEFAULT = new Base64UrlNamingStrategy(); private final String prefix; /** * Construct an instance using the default prefix {@code spring.gen-}. */ public Base64UrlNamingStrategy() { this("spring.gen-"); } /** * Construct an instance using the supplied prefix.
* @param prefix The prefix. */ public Base64UrlNamingStrategy(String prefix) { Assert.notNull(prefix, "'prefix' cannot be null; use an empty String "); this.prefix = prefix; } @Override public String generateName() { UUID uuid = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.wrap(new byte[SIXTEEN]); bb.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); // Convert to base64 and remove trailing = return this.prefix + Base64.getUrlEncoder().encodeToString(bb.array()) .replaceAll("=", ""); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\Base64UrlNamingStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public EventDeploymentBuilder addString(String resourceName, String text) { if (text == null) { throw new FlowableException("text is null"); } EventResourceEntity resource = resourceEntityManager.create(); resource.setName(resourceName); resource.setBytes(text.getBytes(StandardCharsets.UTF_8)); deployment.addResource(resource); return this; } @Override public EventDeploymentBuilder addEventDefinitionBytes(String resourceName, byte[] eventDefinitionBytes) { if (eventDefinitionBytes == null) { throw new FlowableException("event definition bytes is null"); } EventResourceEntity resource = resourceEntityManager.create(); resource.setName(resourceName); resource.setBytes(eventDefinitionBytes); deployment.addResource(resource); return this; } @Override public EventDeploymentBuilder addEventDefinition(String resourceName, String eventDefinition) { addString(resourceName, eventDefinition); return this; } @Override public EventDeploymentBuilder addChannelDefinitionBytes(String resourceName, byte[] channelDefinitionBytes) { if (channelDefinitionBytes == null) { throw new FlowableException("channel definition bytes is null"); } EventResourceEntity resource = resourceEntityManager.create(); resource.setName(resourceName); resource.setBytes(channelDefinitionBytes); deployment.addResource(resource); return this; } @Override public EventDeploymentBuilder addChannelDefinition(String resourceName, String channelDefinition) { addString(resourceName, channelDefinition); return this; } @Override public EventDeploymentBuilder name(String name) { deployment.setName(name); return this; } @Override public EventDeploymentBuilder category(String category) { deployment.setCategory(category); return this; } @Override public EventDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this;
} @Override public EventDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public EventDeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this; } @Override public EventDeployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public EventDeploymentEntity getDeployment() { return deployment; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\repository\EventDeploymentBuilderImpl.java
2
请完成以下Java代码
private void setIncoterms( @NonNull final I_C_BPartner bPartnerRecord, @NonNull final I_C_BP_Group bpGroup, @Nullable final I_C_BP_Group bpParentGroup, @NonNull final OrgId orgId, final Function<I_C_BPartner, Integer> bpartnerIncotermsIdGetter, final Function<I_C_BP_Group, Integer> bpGroupIncotermsIdGetter, final Function<I_C_BPartner, String> bpartnerLocationGetter, final Function<I_C_BP_Group, String> bpGroupLocationGetter, final Consumer<Incoterms> incotermsConsumer) { final Incoterms incoterms = getEffectiveValue( bPartnerRecord, bpGroup, bpParentGroup, bpartnerIncotermsIdGetter, bpGroupIncotermsIdGetter, this::getIncoterms, () -> incotermsRepository.getDefaultIncoterms(orgId)); if (incoterms == null) { return; } final String location = getEffectiveValue( bPartnerRecord, bpGroup, bpParentGroup, bpartnerLocationGetter, bpGroupLocationGetter, StringUtils::trimBlankToNull, () -> getDefaultIncotermsLocation(orgId)); incotermsConsumer.accept(incoterms.withLocationEffective(location)); } @Nullable private Incoterms getIncoterms(final int incotermsId) { final IncotermsId id = IncotermsId.ofRepoIdOrNull(incotermsId);
if (id == null) { return null; } return incotermsRepository.getById(id); } @Nullable private String getDefaultIncotermsLocation(@NonNull final OrgId orgId) { final Incoterms incoterms = incotermsRepository.getDefaultIncoterms(orgId); if (incoterms == null) { return null; } return StringUtils.trimBlankToNull(incoterms.getDefaultLocation()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\effective\BPartnerEffectiveBL.java
1
请完成以下Java代码
public static class Builder { private BigDecimal totalNetAmtApproved = BigDecimal.ZERO; private BigDecimal huNetAmtApproved = BigDecimal.ZERO; private BigDecimal cuNetAmtApproved = BigDecimal.ZERO; private BigDecimal totalNetAmtNotApproved = BigDecimal.ZERO; private BigDecimal huNetAmtNotApproved = BigDecimal.ZERO; private BigDecimal cuNetAmtNotApproved = BigDecimal.ZERO; private int countTotalToRecompute = 0; private final ImmutableSet.Builder<String> currencySymbols = ImmutableSet.builder(); private Builder() { } public InvoiceCandidatesAmtSelectionSummary build() { return new InvoiceCandidatesAmtSelectionSummary(this); } public Builder addTotalNetAmt(final BigDecimal amtToAdd, final boolean approved, final boolean isPackingMaterial) { if (approved) { totalNetAmtApproved = totalNetAmtApproved.add(amtToAdd); if (isPackingMaterial) { huNetAmtApproved = huNetAmtApproved.add(amtToAdd); } else { cuNetAmtApproved = cuNetAmtApproved.add(amtToAdd); } } else { totalNetAmtNotApproved = totalNetAmtNotApproved.add(amtToAdd); if (isPackingMaterial)
{ huNetAmtNotApproved = huNetAmtNotApproved.add(amtToAdd); } else { cuNetAmtNotApproved = cuNetAmtNotApproved.add(amtToAdd); } } return this; } @SuppressWarnings("UnusedReturnValue") public Builder addCurrencySymbol(final String currencySymbol) { if (Check.isEmpty(currencySymbol, true)) { // NOTE: prevent adding null values because ImmutableSet.Builder will fail in this case currencySymbols.add("?"); } else { currencySymbols.add(currencySymbol); } return this; } public void addCountToRecompute(final int countToRecomputeToAdd) { Check.assume(countToRecomputeToAdd > 0, "countToRecomputeToAdd > 0"); countTotalToRecompute += countToRecomputeToAdd; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesAmtSelectionSummary.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @GetMapping("/registration") public String getRegistration(Model model) { model.addAttribute("user", new User()); return "registration"; } @GetMapping("/registration-thymeleaf") public String getRegistrationThymeleaf(Model model) { model.addAttribute("user", new User()); return "registration-thymeleaf"; } @GetMapping("/registration-freemarker") public String getRegistrationFreemarker(Model model) { model.addAttribute("user", new User()); return "registration-freemarker"; } @GetMapping("/registration-groovy") public String getRegistrationGroovy(Model model) { model.addAttribute("user", new User()); return "registration-groovy";
} @GetMapping("/registration-jade") public String getRegistrationJade(Model model) { model.addAttribute("user", new User()); return "registration-jade"; } @PostMapping("/register") @ResponseBody public void register(User user){ System.out.println(user.getEmail()); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\UserController.java
2
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Sequence_Audit[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_Sequence getAD_Sequence() throws RuntimeException { return (I_AD_Sequence)MTable.get(getCtx(), I_AD_Sequence.Table_Name) .getPO(getAD_Sequence_ID(), get_TrxName()); } /** Set Sequence. @param AD_Sequence_ID Document Sequence */ public void setAD_Sequence_ID (int AD_Sequence_ID) { if (AD_Sequence_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Sequence_ID, Integer.valueOf(AD_Sequence_ID)); } /** Get Sequence. @return Document Sequence */ public int getAD_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document No. @param DocumentNo Document sequence number of the document
*/ public void setDocumentNo (String DocumentNo) { set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo); } /** Get Document No. @return Document sequence number of the document */ public String getDocumentNo () { return (String)get_Value(COLUMNNAME_DocumentNo); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Sequence_Audit.java
1
请完成以下Java代码
public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", categoryId=").append(categoryId); sb.append(", categoryName=").append(categoryName); sb.append(", isDeleted=").append(isDeleted); sb.append(", createTime=").append(createTime); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsCategory.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceCountryModelAttributeSetInstanceListener implements IModelAttributeSetInstanceListener { private final InvoiceLineCountryModelAttributeSetInstanceListener invoiceLineListener = new InvoiceLineCountryModelAttributeSetInstanceListener(); private static final List<String> sourceColumnNames = Collections.singletonList(I_C_Invoice.COLUMNNAME_C_BPartner_Location_ID); @Override public @NonNull String getSourceTableName() { return I_C_Invoice.Table_Name; } @Override public List<String> getSourceColumnNames() {
return sourceColumnNames; } @Override public void modelChanged(Object model) { final I_C_Invoice invoice = InterfaceWrapperHelper.create(model, I_C_Invoice.class); for (final I_C_InvoiceLine line : Services.get(IInvoiceDAO.class).retrieveLines(invoice)) { invoiceLineListener.modelChanged(line); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\InvoiceCountryModelAttributeSetInstanceListener.java
2
请完成以下Java代码
public static boolean equals(@Nullable final HUReservationDocRef ref1, @Nullable final HUReservationDocRef ref2) {return Objects.equals(ref1, ref2);} public interface CaseMappingFunction<R> { R salesOrderLineId(@NonNull OrderLineId salesOrderLineId); R projectId(@NonNull ProjectId projectId); R pickingJobStepId(@NonNull PickingJobStepId pickingJobStepId); R ddOrderLineId(@NonNull DDOrderLineId ddOrderLineId); } public <R> R map(@NonNull final CaseMappingFunction<R> mappingFunction) { if (salesOrderLineId != null) { return mappingFunction.salesOrderLineId(salesOrderLineId); }
else if (projectId != null) { return mappingFunction.projectId(projectId); } else if (pickingJobStepId != null) { return mappingFunction.pickingJobStepId(pickingJobStepId); } else if (ddOrderLineId != null) { return mappingFunction.ddOrderLineId(ddOrderLineId); } else { throw new IllegalStateException("Unknown state: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationDocRef.java
1
请在Spring Boot框架中完成以下Java代码
public String jwtGrantedAuthoritiesPrefix() { return mappingProps.getAuthoritiesPrefix(); } @Bean public Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter() { MappingJwtGrantedAuthoritiesConverter converter = new MappingJwtGrantedAuthoritiesConverter(mappingProps.getScopes()); if (StringUtils.hasText(mappingProps.getAuthoritiesPrefix())) { converter.setAuthorityPrefix(mappingProps.getAuthoritiesPrefix() .trim()); } if (StringUtils.hasText(mappingProps.getAuthoritiesClaimName())) { converter.setAuthoritiesClaimName(mappingProps.getAuthoritiesClaimName()); } return converter; } @Bean public Converter<Jwt,AbstractAuthenticationToken> customJwtAuthenticationConverter(AccountService accountService) { return new CustomJwtAuthenticationConverter(
accountService, jwtGrantedAuthoritiesConverter(), mappingProps.getPrincipalClaimName()); } @Bean SecurityFilterChain customJwtSecurityChain(HttpSecurity http) throws Exception { // @formatter:off return http.oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwtConfigurer -> jwtConfigurer .jwtAuthenticationConverter(customJwtAuthenticationConverter(accountService)))) .build(); // @formatter:on } }
repos\tutorials-master\spring-security-modules\spring-security-oidc\src\main\java\com\baeldung\openid\oidc\jwtauthorities\config\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
private StringEncryptor createPBEDefault() { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(getRequired(configProps::getPassword, propertyPrefix + ".password")); config.setAlgorithm(get(configProps::getAlgorithm, propertyPrefix + ".algorithm", "PBEWITHHMACSHA512ANDAES_256")); config.setKeyObtentionIterations(get(configProps::getKeyObtentionIterations, propertyPrefix + ".key-obtention-iterations", "1000")); config.setPoolSize(get(configProps::getPoolSize, propertyPrefix + ".pool-size", "1")); config.setProviderName(get(configProps::getProviderName, propertyPrefix + ".provider-name", null)); config.setProviderClassName(get(configProps::getProviderClassName, propertyPrefix + ".provider-class-name", null)); config.setSaltGeneratorClassName(get(configProps::getSaltGeneratorClassname, propertyPrefix + ".salt-generator-classname", "org.jasypt.salt.RandomSaltGenerator")); config.setIvGeneratorClassName(get(configProps::getIvGeneratorClassname, propertyPrefix + ".iv-generator-classname", "org.jasypt.iv.RandomIvGenerator")); config.setStringOutputType(get(configProps::getStringOutputType, propertyPrefix + ".string-output-type", "base64")); encryptor.setConfig(config); return encryptor; } private <T> T getRequired(Supplier<T> supplier, String key) {
T value = supplier.get(); if (value == null) { throw new IllegalStateException(String.format("Required Encryption configuration property missing: %s", key)); } return value; } private <T> T get(Supplier<T> supplier, String key, T defaultValue) { T value = supplier.get(); if (value == defaultValue) { log.info("Encryptor config not found for property {}, using default value: {}", key, value); } return value; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\StringEncryptorBuilder.java
2
请完成以下Java代码
public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setC_DocType_ID (final int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID); } @Override public int getC_DocType_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFeePercentageOfGrandTotal (final BigDecimal FeePercentageOfGrandTotal) { set_Value (COLUMNNAME_FeePercentageOfGrandTotal, FeePercentageOfGrandTotal); } @Override public BigDecimal getFeePercentageOfGrandTotal()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_FeePercentageOfGrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setInvoiceProcessingServiceCompany_BPartnerAssignment_ID (final int InvoiceProcessingServiceCompany_BPartnerAssignment_ID) { if (InvoiceProcessingServiceCompany_BPartnerAssignment_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID, InvoiceProcessingServiceCompany_BPartnerAssignment_ID); } @Override public int getInvoiceProcessingServiceCompany_BPartnerAssignment_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_BPartnerAssignment_ID); } @Override public org.compiere.model.I_InvoiceProcessingServiceCompany getInvoiceProcessingServiceCompany() { return get_ValueAsPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class); } @Override public void setInvoiceProcessingServiceCompany(final org.compiere.model.I_InvoiceProcessingServiceCompany InvoiceProcessingServiceCompany) { set_ValueFromPO(COLUMNNAME_InvoiceProcessingServiceCompany_ID, org.compiere.model.I_InvoiceProcessingServiceCompany.class, InvoiceProcessingServiceCompany); } @Override public void setInvoiceProcessingServiceCompany_ID (final int InvoiceProcessingServiceCompany_ID) { if (InvoiceProcessingServiceCompany_ID < 1) set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, null); else set_ValueNoCheck (COLUMNNAME_InvoiceProcessingServiceCompany_ID, InvoiceProcessingServiceCompany_ID); } @Override public int getInvoiceProcessingServiceCompany_ID() { return get_ValueAsInt(COLUMNNAME_InvoiceProcessingServiceCompany_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_InvoiceProcessingServiceCompany_BPartnerAssignment.java
1
请完成以下Java代码
public class OIView extends AbstractCustomView<OIRow> implements IEditableView { public static OIView cast(IView view) {return (OIView)view;} @NonNull private final ImmutableList<RelatedProcessDescriptor> relatedProcesses; @Getter @NonNull private final SAPGLJournalId sapglJournalId; @Builder private OIView( final @NonNull ViewId viewId, final @NonNull OIViewData rowsData, final @NonNull DocumentFilterDescriptor filterDescriptor, final @NonNull SAPGLJournalId sapglJournalId, final @NonNull @Singular ImmutableList<RelatedProcessDescriptor> relatedProcesses) { super(viewId, null, rowsData, ImmutableDocumentFilterDescriptorsProvider.of(filterDescriptor)); this.sapglJournalId = sapglJournalId; this.relatedProcesses = relatedProcesses; } @Nullable @Override public String getTableNameOrNull(@Nullable final DocumentId documentId) {return null;} @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() {return relatedProcesses;} @Override public DocumentFilterList getFilters() {return DocumentFilterList.ofNullable(getRowsData().getFilter());} @Override protected OIViewData getRowsData() {return OIViewData.cast(super.getRowsData());} @Override public ViewHeaderProperties getHeaderProperties() {return getRowsData().getHeaderProperties();}
public void markRowsAsSelected(final DocumentIdsSelection rowIds) { getRowsData().markRowsAsSelected(rowIds); ViewChangesCollector.getCurrentOrAutoflush().collectRowsAndHeaderPropertiesChanged(this, rowIds); } public boolean hasSelectedRows() { return getRowsData().hasSelectedRows(); } public void clearUserInputAndResetFilter() { final OIViewData rowsData = getRowsData(); rowsData.clearUserInput(); rowsData.clearFilter(); invalidateAll(); } public OIRowUserInputParts getUserInput() {return getRowsData().getUserInput();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIView.java
1
请在Spring Boot框架中完成以下Java代码
public void setTenantIdIn(List<String> tenantIds) { this.tenantIds = tenantIds; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value = "includeDeploymentsWithoutTenantId", converter = BooleanConverter.class) public void setIncludeDeploymentsWithoutTenantId(Boolean includeDeploymentsWithoutTenantId) { this.includeDeploymentsWithoutTenantId = includeDeploymentsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected DeploymentQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createDeploymentQuery(); } @Override protected void applyFilters(DeploymentQuery query) { if (withoutSource != null && withoutSource && source != null) { throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination."); } if (id != null) { query.deploymentId(id); } if (name != null) { query.deploymentName(name); } if (nameLike != null) { query.deploymentNameLike(nameLike); } if (TRUE.equals(withoutSource)) { query.deploymentSource(null);
} if (source != null) { query.deploymentSource(source); } if (before != null) { query.deploymentBefore(before); } if (after != null) { query.deploymentAfter(after); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDeploymentsWithoutTenantId)) { query.includeDeploymentsWithoutTenantId(); } } @Override protected void applySortBy(DeploymentQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByDeploymentName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) { query.orderByDeploymentTime(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentQueryDto.java
2
请完成以下Java代码
public void put(String key, String value) throws InterruptedException { try { writeLock.lock(); logger.info(Thread.currentThread().getName() + " writing"); syncHashMap.put(key, value); sleep(1000); } finally { writeLock.unlock(); } } public String get(String key) { try { readLock.lock(); logger.info(Thread.currentThread().getName() + " reading"); return syncHashMap.get(key); } finally { readLock.unlock(); } } public String remove(String key) { try { writeLock.lock(); return syncHashMap.remove(key); } finally { writeLock.unlock(); } } public boolean containsKey(String key) { try { readLock.lock(); return syncHashMap.containsKey(key); } finally { readLock.unlock(); } } boolean isReadLockAvailable() { return readLock.tryLock(); } public static void main(String[] args) throws InterruptedException { final int threadCount = 3; final ExecutorService service = Executors.newFixedThreadPool(threadCount); SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); service.execute(new Thread(new Writer(object), "Writer")); service.execute(new Thread(new Reader(object), "Reader1"));
service.execute(new Thread(new Reader(object), "Reader2")); service.shutdown(); } private static class Reader implements Runnable { SynchronizedHashMapWithRWLock object; Reader(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { object.get("key" + i); } } } private static class Writer implements Runnable { SynchronizedHashMapWithRWLock object; public Writer(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { try { object.put("key" + i, "value" + i); sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SynchronizedHashMapWithRWLock.java
1
请完成以下Java代码
class TransferableTreeNode implements Transferable { public static DataFlavor TREE_NODE_FLAVOR = new DataFlavor(MTreeNode.class, "Tree Path"); private final DataFlavor flavors[] = { TREE_NODE_FLAVOR }; private final MTreeNode node; public TransferableTreeNode(final MTreeNode node) { super(); this.node = node; } @Override public synchronized DataFlavor[] getTransferDataFlavors() { return flavors; }
@Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return flavor.getRepresentationClass() == MTreeNode.class; } @Override public synchronized Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) { return node; } else { throw new UnsupportedFlavorException(flavor); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\TransferableTreeNode.java
1
请完成以下Java代码
public class AlipayConfig { /** * 支付宝网关 */ private String gatewayUrl; /** * 应用ID */ private String appId; /** * 应用私钥 */ private String appPrivateKey; /** * 支付宝公钥 */ private String alipayPublicKey; /** * 用户确认支付后,支付宝调用的页面返回路径 * 开发环境为:http://localhost:8060/#/pages/money/paySuccess */ private String returnUrl; /**
* 支付成功后,支付宝服务器主动通知商户服务器里的异步通知回调(需要公网能访问) * 开发环境为:http://localhost:8085/alipay/notify */ private String notifyUrl; /** * 参数返回格式,只支持JSON */ private String format = "JSON"; /** * 请求使用的编码格式 */ private String charset = "UTF-8"; /** * 生成签名字符串所使用的签名算法类型 */ private String signType = "RSA2"; }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\config\AlipayConfig.java
1