instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class Constants { /** * The inertia factor encourages a particle to continue moving in its * current direction. */ public static final double INERTIA_FACTOR = 0.729; /** * The cognitive weight encourages a particle to move toward its historical * best-known position. */ public static final double COGNITIVE_WEIGHT = 1.49445; /** * The social weight encourages a particle to move toward the best-known * position found by any of the particle’s swarm-mates. */ public static final double SOCIAL_WEIGHT = 1.49445; /**
* The global weight encourages a particle to move toward the best-known * position found by any particle in any swarm. */ public static final double GLOBAL_WEIGHT = 0.3645; /** * Upper bound for the random generation. We use it to reduce the * computation time since we can rawly estimate it. */ public static final int PARTICLE_UPPER_BOUND = 10000000; /** * Private constructor for utility class. */ private Constants() { } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Constants.java
1
请完成以下Java代码
public String getIdGenerator() { return idGenerator; } public void setIdGenerator(String idGenerator) { this.idGenerator = idGenerator; } public Boolean getJobExecutorAcquireByPriority() { return jobExecutorAcquireByPriority; } public void setJobExecutorAcquireByPriority(Boolean jobExecutorAcquireByPriority) { this.jobExecutorAcquireByPriority = jobExecutorAcquireByPriority; } public Integer getDefaultNumberOfRetries() { return defaultNumberOfRetries; } public void setDefaultNumberOfRetries(Integer defaultNumberOfRetries) { this.defaultNumberOfRetries = defaultNumberOfRetries; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Boolean getGenerateUniqueProcessEngineName() { return generateUniqueProcessEngineName; } public void setGenerateUniqueProcessEngineName(Boolean generateUniqueProcessEngineName) { this.generateUniqueProcessEngineName = generateUniqueProcessEngineName; } public Boolean getGenerateUniqueProcessApplicationName() { return generateUniqueProcessApplicationName; } public void setGenerateUniqueProcessApplicationName(Boolean generateUniqueProcessApplicationName) { this.generateUniqueProcessApplicationName = generateUniqueProcessApplicationName; } @Override public String toString() { return joinOn(this.getClass()) .add("enabled=" + enabled) .add("processEngineName=" + processEngineName)
.add("generateUniqueProcessEngineName=" + generateUniqueProcessEngineName) .add("generateUniqueProcessApplicationName=" + generateUniqueProcessApplicationName) .add("historyLevel=" + historyLevel) .add("historyLevelDefault=" + historyLevelDefault) .add("autoDeploymentEnabled=" + autoDeploymentEnabled) .add("deploymentResourcePattern=" + Arrays.toString(deploymentResourcePattern)) .add("defaultSerializationFormat=" + defaultSerializationFormat) .add("licenseFile=" + licenseFile) .add("metrics=" + metrics) .add("database=" + database) .add("jobExecution=" + jobExecution) .add("webapp=" + webapp) .add("restApi=" + restApi) .add("authorization=" + authorization) .add("genericProperties=" + genericProperties) .add("adminUser=" + adminUser) .add("filter=" + filter) .add("idGenerator=" + idGenerator) .add("jobExecutorAcquireByPriority=" + jobExecutorAcquireByPriority) .add("defaultNumberOfRetries" + defaultNumberOfRetries) .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CamundaBpmProperties.java
1
请完成以下Java代码
public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { throw new IllegalArgumentException ("M_Product_Category_ID is virtual column"); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { throw new IllegalArgumentException ("M_Product_ID is virtual column"); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSerialNo (final @Nullable java.lang.String SerialNo) { throw new IllegalArgumentException ("SerialNo is virtual column"); } @Override public java.lang.String getSerialNo() { return get_ValueAsString(COLUMNNAME_SerialNo); } @Override
public void setServiceContract (final @Nullable java.lang.String ServiceContract) { throw new IllegalArgumentException ("ServiceContract is virtual column"); } @Override public java.lang.String getServiceContract() { return get_ValueAsString(COLUMNNAME_ServiceContract); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU.java
1
请完成以下Java代码
public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; }
public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAssignedUUID\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public class MTaxCategory extends X_C_TaxCategory { /** * */ private static final long serialVersionUID = 2154364435808111060L; /** * Standard Constructor * @param ctx context * @param C_TaxCategory_ID id * @param trxName trx */ public MTaxCategory (Properties ctx, int C_TaxCategory_ID, String trxName) { super (ctx, C_TaxCategory_ID, trxName); } // MTaxCategory /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MTaxCategory (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MTaxCategory /** * Get the default tax id associated with this tax category */ @Deprecated public MTax getDefaultTax() { MTax m_tax = new MTax(getCtx(), 0, get_TrxName()); String whereClause = I_C_Tax.COLUMNNAME_C_TaxCategory_ID+"=? AND "+ I_C_Tax.COLUMNNAME_IsDefault+"='Y'"; List<MTax> list = new Query(getCtx(), MTax.Table_Name, whereClause, get_TrxName()) .setParameters(new Object[]{getC_TaxCategory_ID()}) .list(MTax.class);
if (list.size() == 1) { m_tax = list.get(0); } else { // Error - should only be one default throw new AdempiereException("TooManyDefaults"); } return m_tax; } // getDefaultTax @Override public String toString() { return getClass().getSimpleName()+"["+get_ID() +", Name="+getName() +", IsActive="+isActive() +"]"; } } // MTaxCategory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTaxCategory.java
1
请在Spring Boot框架中完成以下Java代码
public void setForceResponse(boolean forceResponse) { this.forceResponse = forceResponse; } public boolean shouldForce(HttpMessageType type) { Boolean force = (type != HttpMessageType.REQUEST) ? this.forceResponse : this.forceRequest; if (force == null) { force = this.force; } if (force == null) { force = (type == HttpMessageType.REQUEST); } return force; } /** * Type of HTTP message to consider for encoding configuration.
*/ public enum HttpMessageType { /** * HTTP request message. */ REQUEST, /** * HTTP response message. */ RESPONSE } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\ServletEncodingProperties.java
2
请完成以下Java代码
public void destroyInnerInstance(ActivityExecution concurrentExecution) { ActivityExecution scopeExecution = concurrentExecution.getParent(); concurrentExecution.remove(); scopeExecution.forceUpdate(); int nrOfActiveInstances = getLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES); setLoopVariable(scopeExecution, NUMBER_OF_ACTIVE_INSTANCES, nrOfActiveInstances - 1); } @Override public void migrateScope(ActivityExecution scopeExecution) { // migrate already completed instances for (ActivityExecution child : scopeExecution.getExecutions()) { if (!child.isActive()) { ((PvmExecutionImpl) child).setProcessDefinition(((PvmExecutionImpl) scopeExecution).getProcessDefinition()); } } }
@Override public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { ExecutionEntity scopeExecution = migratingInstance.resolveRepresentativeExecution(); List<ActivityExecution> concurrentInActiveExecutions = scopeExecution.findInactiveChildExecutions(getInnerActivity((ActivityImpl) migratingInstance.getSourceScope())); // variables on ended inner instance executions need not be migrated anywhere // since they are also not represented in the tree of migrating instances, we remove // them from the parse context here to avoid a validation exception for (ActivityExecution execution : concurrentInActiveExecutions) { for (VariableInstanceEntity variable : ((ExecutionEntity) execution).getVariablesInternal()) { parseContext.consume(variable); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\ParallelMultiInstanceActivityBehavior.java
1
请完成以下Java代码
public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void initialize(ConfigurableApplicationContext applicationContext) { ContextId contextId = getContextId(applicationContext); applicationContext.setId(contextId.getId()); applicationContext.getBeanFactory().registerSingleton(ContextId.class.getName(), contextId); } private ContextId getContextId(ConfigurableApplicationContext applicationContext) { ApplicationContext parent = applicationContext.getParent(); if (parent != null && parent.containsBean(ContextId.class.getName())) { return parent.getBean(ContextId.class).createChildId(); } return new ContextId(getApplicationId(applicationContext.getEnvironment())); } private String getApplicationId(ConfigurableEnvironment environment) { String name = environment.getProperty("spring.application.name"); return StringUtils.hasText(name) ? name : "application"; }
/** * The ID of a context. */ static class ContextId { private final AtomicLong children = new AtomicLong(); private final String id; ContextId(String id) { this.id = id; } ContextId createChildId() { return new ContextId(this.id + "-" + this.children.incrementAndGet()); } String getId() { return this.id; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\ContextIdApplicationContextInitializer.java
1
请完成以下Java代码
public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @CamundaQueryParam("executionId") public void setExecutionId(String executionId) { this.executionId = executionId; } @CamundaQueryParam("caseDefinitionId") public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @CamundaQueryParam("caseInstanceId") public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @CamundaQueryParam("caseExecutionId") public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } @CamundaQueryParam("taskId") public void setTaskId(String taskId) { this.taskId = taskId; } @CamundaQueryParam("jobId") public void setJobId(String jobId) { this.jobId = jobId; } @CamundaQueryParam("jobDefinitionId") public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } @CamundaQueryParam("batchId") public void setBatchId(String batchId) { this.batchId = batchId; } @CamundaQueryParam("userId") public void setUserId(String userId) { this.userId = userId; } @CamundaQueryParam("operationId") public void setOperationId(String operationId) { this.operationId = operationId; } @CamundaQueryParam("externalTaskId") public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } @CamundaQueryParam("operationType") public void setOperationType(String operationType) { this.operationType = operationType; }
@CamundaQueryParam("entityType") public void setEntityType(String entityType) { this.entityType = entityType; } @CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class) public void setEntityTypeIn(String[] entityTypes) { this.entityTypes = entityTypes; } @CamundaQueryParam("category") public void setcategory(String category) { this.category = category; } @CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class) public void setCategoryIn(String[] categories) { this.categories = categories; } @CamundaQueryParam("property") public void setProperty(String property) { this.property = property; } @CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class) public void setAfterTimestamp(Date after) { this.afterTimestamp = after; } @CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class) public void setBeforeTimestamp(Date before) { this.beforeTimestamp = before; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogQueryDto.java
1
请完成以下Java代码
public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz, Object... param) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); if (ArrayUtils.isEmpty(param)) { list = jdbcTemplate.queryForList(sql, clazz); } else { list = jdbcTemplate.queryForList(sql, clazz, param); } return list; } /** * 支持miniDao语法操作的查询 返回单列数据list * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 类型Long、String等 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); list = namedParameterJdbcTemplate.queryForList(sql, data, clazz); return list; } /** * 直接sql查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持 minidao 语法逻辑 * @param clazz 返回实体类列表的class
* @param param sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntities(final String dbKey, String sql, Class<T> clazz, Object... param) { List<Map<String, Object>> queryList = findList(dbKey, sql, param); return ReflectHelper.transList2Entrys(queryList, clazz); } /** * 支持miniDao语法操作的查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 返回实体类列表的class * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntitiesByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<Map<String, Object>> queryList = findListByHash(dbKey, sql, data); return ReflectHelper.transList2Entrys(queryList, clazz); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DynamicDBUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class TaxAccountsRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<TaxId, ImmutableMap<AcctSchemaId, TaxAccounts>> cache = CCache.<TaxId, ImmutableMap<AcctSchemaId, TaxAccounts>>builder() .tableName(I_C_Tax_Acct.Table_Name) .cacheMapType(CCache.CacheMapType.LRU) .initialCapacity(100) .build(); public TaxAccounts getAccounts(@NonNull final TaxId taxId, @NonNull final AcctSchemaId acctSchemaId) { final ImmutableMap<AcctSchemaId, TaxAccounts> map = cache.getOrLoad(taxId, this::retrieveAccounts); final TaxAccounts accounts = map.get(acctSchemaId); if (accounts == null) { throw new AdempiereException("No Tax accounts defined for " + taxId + " and " + acctSchemaId); } return accounts; } private ImmutableMap<AcctSchemaId, TaxAccounts> retrieveAccounts(@NonNull final TaxId taxId) { return queryBL.createQueryBuilder(I_C_Tax_Acct.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Tax_Acct.COLUMNNAME_C_Tax_ID, taxId) .create() .stream() .map(TaxAccountsRepository::fromRecord) .collect(ImmutableMap.toImmutableMap(TaxAccounts::getAcctSchemaId, accounts -> accounts)); } @NonNull
private static TaxAccounts fromRecord(@NonNull final I_C_Tax_Acct record) { return TaxAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .T_Due_Acct(Account.of(AccountId.ofRepoId(record.getT_Due_Acct()), TaxAcctType.TaxDue)) .T_Liability_Acct(Account.of(AccountId.ofRepoId(record.getT_Liability_Acct()), TaxAcctType.TaxLiability)) .T_Credit_Acct(Account.of(AccountId.ofRepoId(record.getT_Credit_Acct()), TaxAcctType.TaxCredit)) .T_Receivables_Acct(Account.of(AccountId.ofRepoId(record.getT_Receivables_Acct()), TaxAcctType.TaxReceivables)) .T_Expense_Acct(Account.of(AccountId.ofRepoId(record.getT_Expense_Acct()), TaxAcctType.TaxExpense)) .T_Revenue_Acct(Account.optionalOfRepoId(record.getT_Revenue_Acct(), TaxAcctType.T_Revenue_Acct)) .T_PayDiscount_Exp_Acct(Account.optionalOfRepoId(record.getT_PayDiscount_Exp_Acct(), TaxAcctType.T_PayDiscount_Exp_Acct)) .T_PayDiscount_Rev_Acct(Account.optionalOfRepoId(record.getT_PayDiscount_Rev_Acct(), TaxAcctType.T_PayDiscount_Rev_Acct)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\TaxAccountsRepository.java
2
请完成以下Java代码
public Object getSource(VariableScope variableScope) { if (sourceValueProvider instanceof ConstantValueProvider) { String variableName = (String) sourceValueProvider.getValue(variableScope); return variableScope.getVariableTyped(variableName); } else { return sourceValueProvider.getValue(variableScope); } } public void applyTo(VariableScope variableScope, VariableMap variables) { if (readLocal) { variableScope = new VariableScopeLocalAdapter(variableScope); } if (allVariables) { Map<String, Object> allVariables = variableScope.getVariables(); variables.putAll(allVariables); } else { Object value = getSource(variableScope); variables.put(target, value); } } public ParameterValueProvider getSourceValueProvider() { return sourceValueProvider; } public void setSourceValueProvider(ParameterValueProvider source) { this.sourceValueProvider = source; } // target ////////////////////////////////////////////////////////// public String getTarget() { return target; }
public void setTarget(String target) { this.target = target; } // all variables ////////////////////////////////////////////////// public boolean isAllVariables() { return allVariables; } public void setAllVariables(boolean allVariables) { this.allVariables = allVariables; } // local public void setReadLocal(boolean readLocal) { this.readLocal = readLocal; } public boolean isReadLocal() { return readLocal; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElementParameter.java
1
请完成以下Java代码
public class SupplementaryData1 { @XmlElement(name = "PlcAndNm") protected String plcAndNm; @XmlElement(name = "Envlp", required = true) protected SupplementaryDataEnvelope1 envlp; /** * Gets the value of the plcAndNm property. * * @return * possible object is * {@link String } * */ public String getPlcAndNm() { return plcAndNm; } /** * Sets the value of the plcAndNm property. * * @param value * allowed object is * {@link String } * */ public void setPlcAndNm(String value) { this.plcAndNm = value; } /** * Gets the value of the envlp property.
* * @return * possible object is * {@link SupplementaryDataEnvelope1 } * */ public SupplementaryDataEnvelope1 getEnvlp() { return envlp; } /** * Sets the value of the envlp property. * * @param value * allowed object is * {@link SupplementaryDataEnvelope1 } * */ public void setEnvlp(SupplementaryDataEnvelope1 value) { this.envlp = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\SupplementaryData1.java
1
请在Spring Boot框架中完成以下Java代码
private ExplainedOptional<HUInfo> findFirstByWarehouseAndProduct(@NonNull final WarehouseId warehouseId, @NonNull final ProductId productId) { final HuId huId = huService.getFirstHuIdByWarehouseAndProduct(warehouseId, productId).orElse(null); if (huId == null) { return ExplainedOptional.emptyBecause(ERR_NotEnoughTUsFound);// TODO introduce a better AD_Message } return getHUInfoById(huId); } private BooleanWithReason validateQRCode_GTIN( @NonNull final GS1HUQRCode pickFromHUQRCode, @NonNull final ProductId expectedProductId) { final GTIN gtin = pickFromHUQRCode.getGTIN().orElse(null); if (gtin != null) { final ProductId gs1ProductId = productService.getProductIdByGTINStrictlyNotNull(gtin, ClientId.METASFRESH); if (!ProductId.equals(expectedProductId, gs1ProductId)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("GTIN", gtin) // .setParameter("expected", expectedProductId) // .setParameter("actual", gs1ProductId); } } return BooleanWithReason.TRUE; } private BooleanWithReason validateQRCode_EAN13ProductNo( @NonNull final EAN13HUQRCode pickFromQRCode, @NonNull final ProductId expectedProductId,
@NonNull final BPartnerId customerId) { final EAN13 ean13 = pickFromQRCode.unbox(); if (!productService.isValidEAN13Product(ean13, expectedProductId, customerId)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // final String expectedProductNo = productService.getProductValue(expectedProductId); // final EAN13ProductCode ean13ProductNo = ean13.getProductNo(); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("ean13ProductNo", ean13ProductNo) // .setParameter("expectedProductNo", expectedProductNo) // .setParameter("expectedProductId", expectedProductId); } return BooleanWithReason.TRUE; } private BooleanWithReason validateQRCode_ProductNo( @NonNull final CustomHUQRCode customQRCode, @NonNull final ProductId expectedProductId) { final String qrCodeProductNo = customQRCode.getProductNo().orElse(null); if (qrCodeProductNo == null) {return BooleanWithReason.TRUE;} final String expectedProductNo = productService.getProductValue(expectedProductId); if (!Objects.equals(qrCodeProductNo, expectedProductNo)) { return BooleanWithReason.falseBecause(ERR_QR_ProductNotMatching); // throw new AdempiereException(ERR_QR_ProductNotMatching) // .setParameter("qrCodeProductNo", qrCodeProductNo) // .setParameter("expectedProductNo", expectedProductNo) // .setParameter("expectedProductId", expectedProductId); } return BooleanWithReason.TRUE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\PickFromHUQRCodeResolveCommand.java
2
请完成以下Java代码
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 Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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; } @Override public org.compiere.model.I_C_AllocationHdr getReversal() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class); }
@Override public void setReversal(org.compiere.model.I_C_AllocationHdr Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class, Reversal); } /** Set Reversal ID. @param Reversal_ID ID of document reversal */ @Override public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) { set_Value (COLUMNNAME_Reversal_ID, null); } else { set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } } /** Get Reversal ID. @return ID of document reversal */ @Override public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationHdr.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public void setCustomerOrders(Set<CustomerOrder> customerOrders) { this.customerOrders = customerOrders; } @Override public String toString() { return "Patient{" + "id=" + id + ", orders=" + customerOrders + ", email='" + email + '\'' + ", dob=" + dob + ", name='" + name + '\'' + '}'; } public Set<CustomerOrder> getOrders() { return customerOrders; } public void setOrders(Set<CustomerOrder> orders) { this.customerOrders = orders; } @Column private String email; @Column(name = "dob", columnDefinition = "DATE") private LocalDate dob; @Column private String name; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer patient = (Customer) o; return Objects.equals(id, patient.id); } @Override
public int hashCode() { return Objects.hash(id); } public Long getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Customer.java
1
请在Spring Boot框架中完成以下Java代码
public DeploymentBuilder name(String name) { if (nameFromDeployment != null && !nameFromDeployment.isEmpty()) { String message = String.format("Cannot set the deployment name to '%s', because the property 'nameForDeployment' has been already set to '%s'.", name, nameFromDeployment); throw new NotValidException(message); } deployment.setName(name); return this; } public DeploymentBuilder nameFromDeployment(String deploymentId) { String name = deployment.getName(); if (name != null && !name.isEmpty()) { String message = String.format("Cannot set the given deployment id '%s' to get the name from it, because the deployment name has been already set to '%s'.", deploymentId, name); throw new NotValidException(message); } nameFromDeployment = deploymentId; return this; } public DeploymentBuilder enableDuplicateFiltering() { return enableDuplicateFiltering(false); } public DeploymentBuilder enableDuplicateFiltering(boolean deployChangedOnly) { this.isDuplicateFilterEnabled = true; this.deployChangedOnly = deployChangedOnly; return this; } public DeploymentBuilder activateProcessDefinitionsOn(Date date) { this.processDefinitionsActivationDate = date; return this; } public DeploymentBuilder source(String source) { deployment.setSource(source); return this; } public DeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } public Deployment deploy() { return deployWithResult(); } public DeploymentWithDefinitions deployWithResult() { return repositoryService.deployWithResult(this);
} public Collection<String> getResourceNames() { if(deployment.getResources() == null) { return Collections.<String>emptySet(); } else { return deployment.getResources().keySet(); } } // getters and setters ////////////////////////////////////////////////////// public DeploymentEntity getDeployment() { return deployment; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public boolean isDeployChangedOnly() { return deployChangedOnly; } public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; } public String getNameFromDeployment() { return nameFromDeployment; } public Set<String> getDeployments() { return deployments; } public Map<String, Set<String>> getDeploymentResourcesById() { return deploymentResourcesById; } public Map<String, Set<String>> getDeploymentResourcesByName() { return deploymentResourcesByName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeploymentBuilderImpl.java
2
请完成以下Java代码
public static boolean isUseCacheWhenCreatingHUs() { return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_UseCacheWhenCreatingHUs, DEFAULT_UseCacheWhenCreatingHUs); } private HUConstants() { super(); }; /** * Enable/Disable the feature of quickly creating the shipments without any HU generation or something. * * NOTE: this will be a temporary solution until will go live with shipment HUs. * * @task http://dewiki908/mediawiki/index.php/08214_Fix_shipment_schedule_performances */ private static final boolean DEFAULT_QuickShipment = true; private static final String SYSCONFIG_QuickShipment = "de.metas.handlingunits.HUConstants.Fresh_QuickShipment"; public static final boolean isQuickShipment() { return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_QuickShipment, DEFAULT_QuickShipment); } /** * @return true if we shall reset the cache after HUEditor is called, and right before the process lines is called. */ public static final boolean is08793_HUSelectModel_ResetCacheBeforeProcess() { final String SYSCONFIG_08793_HUSelectModel_ResetCacheBeforeProcess = "de.metas.handlingunits.client.terminal.select.model.AbstractHUSelectModel.ResetCacheBeforeProcess"; final boolean DEFAULT_08793_HUSelectModel_ResetCacheBeforeProcess = false; final boolean resetCacheBeforeProcessing = Services.get(ISysConfigBL.class).getBooleanValue( SYSCONFIG_08793_HUSelectModel_ResetCacheBeforeProcess, DEFAULT_08793_HUSelectModel_ResetCacheBeforeProcess); return resetCacheBeforeProcessing; } private static final String SYSCONFIG_AttributeStorageFailOnDisposed = "de.metas.handlingunits.attribute.storage.IAttributeStorage.FailOnDisposed"; private static final boolean DEFAULT_AttributeStorageFailOnDisposed = true;
public static final boolean isAttributeStorageFailOnDisposed() { return Services.get(ISysConfigBL.class).getBooleanValue( SYSCONFIG_AttributeStorageFailOnDisposed, DEFAULT_AttributeStorageFailOnDisposed); } public static final String DIM_PP_Order_ProductAttribute_To_Transfer = "PP_Order_ProductAttribute_Transfer"; public static final String DIM_Barcode_Attributes = "DIM_Barcode_Attributes"; /** * @task http://dewiki908/mediawiki/index.php/09106_Material-Vorgangs-ID_nachtr%C3%A4glich_erfassen_%28101556035702%29 */ public static final String PARAM_CHANGE_HU_MAterial_Tracking_ID = M_Material_Tracking_CreateOrUpdate_ID.class.getSimpleName() + ".CHANGE_HUs"; }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUConstants.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Process_Para getAD_Process_Para() { return get_ValueAsPO(COLUMNNAME_AD_Process_Para_ID, org.compiere.model.I_AD_Process_Para.class); } @Override public void setAD_Process_Para(final org.compiere.model.I_AD_Process_Para AD_Process_Para) { set_ValueFromPO(COLUMNNAME_AD_Process_Para_ID, org.compiere.model.I_AD_Process_Para.class, AD_Process_Para); } @Override public void setAD_Process_Para_ID (final int AD_Process_Para_ID) { if (AD_Process_Para_ID < 1) set_Value (COLUMNNAME_AD_Process_Para_ID, null); else set_Value (COLUMNNAME_AD_Process_Para_ID, AD_Process_Para_ID); } @Override public int getAD_Process_Para_ID() { return get_ValueAsInt(COLUMNNAME_AD_Process_Para_ID); } @Override public void setAD_WF_Node_ID (final int AD_WF_Node_ID) { if (AD_WF_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, AD_WF_Node_ID); } @Override public int getAD_WF_Node_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_ID); } @Override public void setAD_WF_Node_Para_ID (final int AD_WF_Node_Para_ID) { if (AD_WF_Node_Para_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Para_ID, AD_WF_Node_Para_ID); } @Override public int getAD_WF_Node_Para_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Para_ID); } @Override public void setAttributeName (final java.lang.String AttributeName) { set_Value (COLUMNNAME_AttributeName, AttributeName); }
@Override public java.lang.String getAttributeName() { return get_ValueAsString(COLUMNNAME_AttributeName); } @Override public void setAttributeValue (final java.lang.String AttributeValue) { set_Value (COLUMNNAME_AttributeValue, AttributeValue); } @Override public java.lang.String getAttributeValue() { return get_ValueAsString(COLUMNNAME_AttributeValue); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Para.java
1
请在Spring Boot框架中完成以下Java代码
public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the locationdate property. * * @return * possible object is * {@link String }
* */ public String getLOCATIONDATE() { return locationdate; } /** * Sets the value of the locationdate property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONDATE(String value) { this.locationdate = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTRSD1.java
2
请完成以下Java代码
long getCurrentClockNs() { return System.nanoTime(); } /** * Wall clock to send timestamp to an external service * */ long getCurrentTimeMs() { return System.currentTimeMillis(); } void sendToRequestTemplate(Request request, UUID requestId, Integer partition, SettableFuture<Response> future, ResponseMetaData<Response> responseMetaData) { log.trace("[{}] Sending request, key [{}], expTime [{}], request {}", requestId, request.getKey(), responseMetaData.expTime, request); if (messagesStats != null) { messagesStats.incrementTotal(); } TopicPartitionInfo tpi = TopicPartitionInfo.builder() .topic(requestTemplate.getDefaultTopic()) .partition(partition) .build(); requestTemplate.send(tpi, request, new TbQueueCallback() { @Override public void onSuccess(TbQueueMsgMetadata metadata) { if (messagesStats != null) { messagesStats.incrementSuccessful(); } log.trace("[{}] Request sent: {}, request {}", requestId, metadata, request); } @Override public void onFailure(Throwable t) { if (messagesStats != null) { messagesStats.incrementFailed(); }
pendingRequests.remove(requestId); future.setException(t); } }); } @Getter static class ResponseMetaData<T> { private final long submitTime; private final long timeout; private final long expTime; private final SettableFuture<T> future; ResponseMetaData(long ts, SettableFuture<T> future, long submitTime, long timeout) { this.submitTime = submitTime; this.timeout = timeout; this.expTime = ts; this.future = future; } @Override public String toString() { return "ResponseMetaData{" + "submitTime=" + submitTime + ", calculatedExpTime=" + (submitTime + timeout) + ", deltaMs=" + (expTime - submitTime) + ", expTime=" + expTime + ", future=" + future + '}'; } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\DefaultTbQueueRequestTemplate.java
1
请完成以下Java代码
public class UnhandledResourceException extends RuntimeException { /** * Constructs a new instance of {@link UnhandledResourceException} with no {@link String message} * or no known {@link Throwable cause}. */ public UnhandledResourceException() { } /** * Constructs a new instance of {@link UnhandledResourceException} initialized with the given {@link String message} * to describe the error. * * @param message {@link String} describing the {@link RuntimeException}. */ public UnhandledResourceException(String message) { super(message); } /** * Constructs a new instance of {@link UnhandledResourceException} initialized with the given {@link Throwable} * signifying the underlying cause of this {@link RuntimeException}. * * @param cause {@link Throwable} signifying the underlying cause of this {@link RuntimeException}. * @see java.lang.Throwable */ public UnhandledResourceException(Throwable cause) { super(cause);
} /** * Constructs a new instance of {@link UnhandledResourceException} initialized with the given {@link String message} * describing the error along with a {@link Throwable} signifying the underlying cause of this * {@link RuntimeException}. * * @param message {@link String} describing the {@link RuntimeException}. * @param cause {@link Throwable} signifying the underlying cause of this {@link RuntimeException}. * @see java.lang.Throwable */ public UnhandledResourceException(String message, Throwable cause) { super(message, cause); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\UnhandledResourceException.java
1
请完成以下Java代码
public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]); holder[0] = 0; System.out.println(sums.sum()); } /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() { int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0])
.sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请完成以下Java代码
public Quantity getQtyCUsPerTU() {return Check.assumeNotNull(qtyCUsPerTU, "Expecting finite capacity: {}", this);} private void assertProductMatches(@NonNull final ProductId productId) { if (this.productId != null && !ProductId.equals(this.productId, productId)) { throw new AdempiereException("Product ID " + productId + " does not match the product of " + this); } } @NonNull public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId) { return computeQtyTUsOfTotalCUs(totalCUs, productId, QuantityUOMConverters.noConversion()); } @NonNull public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId, @NonNull final QuantityUOMConverter uomConverter) { assertProductMatches(productId); if (totalCUs.signum() <= 0) { return QtyTU.ZERO; } // Infinite capacity if (qtyCUsPerTU == null) { return QtyTU.ONE; } final Quantity totalCUsConv = uomConverter.convertQuantityTo(totalCUs, productId, qtyCUsPerTU.getUomId()); final BigDecimal qtyTUs = totalCUsConv.toBigDecimal().divide(qtyCUsPerTU.toBigDecimal(), 0, RoundingMode.UP); return QtyTU.ofBigDecimal(qtyTUs); }
@NonNull public Quantity computeQtyCUsOfQtyTUs(@NonNull final QtyTU qtyTU) { if (qtyCUsPerTU == null) { throw new AdempiereException("Cannot calculate qty of CUs for infinite capacity"); } return qtyTU.computeTotalQtyCUsUsingQtyCUsPerTU(qtyCUsPerTU); } public Capacity toCapacity() { if (productId == null) { throw new AdempiereException("Cannot convert to Capacity when no product is specified") .setParameter("huPIItemProduct", this); } if (qtyCUsPerTU == null) { throw new AdempiereException("Cannot determine the UOM of " + this) .setParameter("huPIItemProduct", this); } return Capacity.createCapacity(qtyCUsPerTU, productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUPIItemProduct.java
1
请完成以下Java代码
public boolean getParameterAsBool(final String parameterName) { return false; } @Nullable @Override public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue) { return defaultValue; } @Override public Timestamp getParameterAsTimestamp(final String parameterName) { return null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { return null; } @Override public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { return null; } @Nullable @Override public Instant getParameterAsInstant(final String parameterName)
{ return null; } @Override public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice) { return null; } /** * Returns an empty list. */ @Override public Collection<String> getParameterNames() { return ImmutableList.of(); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java
1
请完成以下Java代码
public List<String> getPaymentReason() { if (paymentReason == null) { paymentReason = new ArrayList<String>(); } return this.paymentReason; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) { return "esrQR"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the iban property. * * @return * possible object is * {@link String } * */ public String getIban() { return iban; } /** * Sets the value of the iban property. * * @param value * allowed object is * {@link String } * */ public void setIban(String value) { this.iban = value; } /** * Gets the value of the referenceNumber property. * * @return * possible object is * {@link String } * */ public String getReferenceNumber() { return referenceNumber; } /** * Sets the value of the referenceNumber property.
* * @param value * allowed object is * {@link String } * */ public void setReferenceNumber(String value) { this.referenceNumber = value; } /** * Gets the value of the customerNote property. * * @return * possible object is * {@link String } * */ public String getCustomerNote() { return customerNote; } /** * Sets the value of the customerNote property. * * @param value * allowed object is * {@link String } * */ public void setCustomerNote(String value) { this.customerNote = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\EsrQRType.java
1
请完成以下Java代码
public boolean hasRemovalTime() { return hasRemovalTime; } public SetRemovalTimeBatchConfiguration setHasRemovalTime(boolean hasRemovalTime) { this.hasRemovalTime = hasRemovalTime; return this; } public boolean isHierarchical() { return isHierarchical; } public SetRemovalTimeBatchConfiguration setHierarchical(boolean hierarchical) { isHierarchical = hierarchical; return this; } public boolean isUpdateInChunks() { return updateInChunks; } public SetRemovalTimeBatchConfiguration setUpdateInChunks(boolean updateInChunks) { this.updateInChunks = updateInChunks; return this; } public Integer getChunkSize() { return chunkSize; }
public SetRemovalTimeBatchConfiguration setChunkSize(Integer chunkSize) { this.chunkSize = chunkSize; return this; } public Set<String> getEntities() { return entities; } public SetRemovalTimeBatchConfiguration setEntities(Set<String> entities) { this.entities = entities; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\SetRemovalTimeBatchConfiguration.java
1
请完成以下Java代码
public IDocumentNoBuilder forTableName(@NonNull final String tableName, final int adClientId, final int adOrgId) { Check.assumeNotEmpty(tableName, "Given tableName parameter may not not ne empty"); return createDocumentNoBuilder() .setDocumentSequenceInfo(computeDocumentSequenceInfoByTableName(tableName, adClientId, adOrgId)) .setClientId(ClientId.ofRepoId(adClientId)) .setFailOnError(false); } private DocumentSequenceInfo computeDocumentSequenceInfoByTableName(final String tableName, final int adClientId, final int adOrgId) { Check.assumeNotEmpty(tableName, DocumentNoBuilderException.class, "tableName not empty"); final IDocumentSequenceDAO documentSequenceDAO = Services.get(IDocumentSequenceDAO.class); final String sequenceName = IDocumentNoBuilder.PREFIX_DOCSEQ + tableName; return documentSequenceDAO.retriveDocumentSequenceInfo(sequenceName, adClientId, adOrgId); } @Override public IDocumentNoBuilder forDocType(final int C_DocType_ID, final boolean useDefiniteSequence) { return createDocumentNoBuilder() .setDocumentSequenceByDocTypeId(C_DocType_ID, useDefiniteSequence); } @Override public IDocumentNoBuilder forSequenceId(final DocSequenceId sequenceId) { return createDocumentNoBuilder() .setDocumentSequenceInfoBySequenceId(sequenceId); } @Override public DocumentNoBuilder createDocumentNoBuilder() { return new DocumentNoBuilder(); } @Override public IDocumentNoBuilder createValueBuilderFor(@NonNull final Object modelRecord) { final IClientOrgAware clientOrg = create(modelRecord, IClientOrgAware.class); final ClientId clientId = ClientId.ofRepoId(clientOrg.getAD_Client_ID());
final ProviderResult providerResult = getDocumentSequenceInfo(modelRecord); return createDocumentNoBuilder() .setDocumentSequenceInfo(providerResult.getInfoOrNull()) .setClientId(clientId) .setDocumentModel(modelRecord) .setFailOnError(false); } private ProviderResult getDocumentSequenceInfo(@NonNull final Object modelRecord) { for (final ValueSequenceInfoProvider provider : additionalProviders) { final ProviderResult result = provider.computeValueInfo(modelRecord); if (result.hasInfo()) { return result; } } return tableNameBasedProvider.computeValueInfo(modelRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilderFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getFloor() { return floor; } /** * Sets the value of the floor property. * * @param value * allowed object is * {@link String } * */ public void setFloor(String value) { this.floor = value; } /** * Gets the value of the building property. * * @return * possible object is * {@link String } * */ public String getBuilding() { return building; } /** * Sets the value of the building property. * * @param value * allowed object is * {@link String } * */ public void setBuilding(String value) { this.building = value; } /** * Gets the value of the department property. * * @return * possible object is * {@link String } * */ public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } *
*/ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the phone property. * * @return * possible object is * {@link String } * */ public String getPhone() { return phone; } /** * Sets the value of the phone property. * * @param value * allowed object is * {@link String } * */ public void setPhone(String value) { this.phone = value; } /** * Gets the value of the personId property. * * @return * possible object is * {@link String } * */ public String getPersonId() { return personId; } /** * Sets the value of the personId property. * * @param value * allowed object is * {@link String } * */ public void setPersonId(String value) { this.personId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\PersonalDelivery.java
2
请完成以下Java代码
public Class<?> getCommonPropertyType(ELContext context, Object base) { return getWrappedResolver().getCommonPropertyType(this.context, base); } @Override public Class<?> getType(ELContext context, Object base, Object property) { return getWrappedResolver().getType(this.context, base, property); } @Override public Object getValue(ELContext context, Object base, Object property) { try { Object result = getWrappedResolver().getValue(this.context, base, property); context.setPropertyResolved(result != null); return result; } catch (IllegalStateException e) { // dependent scoped / EJBs Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); context.setPropertyResolved(result != null); return result;
} } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return getWrappedResolver().isReadOnly(this.context, base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { getWrappedResolver().setValue(this.context, base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, java.lang.Class<?>[] paramTypes, Object[] params) { Object result = getWrappedResolver().invoke(this.context, base, method, paramTypes, params); context.setPropertyResolved(result != null); return result; } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\el\CdiResolver.java
1
请完成以下Java代码
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID) { if (ExternalSystem_Service_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID); } @Override public int getExternalSystem_Service_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID); } @Override public void setName (final java.lang.String Name)
{ set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java
1
请完成以下Java代码
public void setExecutionListeners(List<ExecutionListener> executionListeners) { for (ExecutionListener executionListener : executionListeners) { addExecutionListener(executionListener); } } public String toString() { return "("+source.getId()+")--"+(id!=null?id+"-->(":">(")+destination.getId()+")"; } // getters and setters ////////////////////////////////////////////////////// public PvmProcessDefinition getProcessDefinition() { return processDefinition; } protected void setSource(ActivityImpl source) {
this.source = source; } public PvmActivity getDestination() { return destination; } public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\TransitionImpl.java
1
请完成以下Java代码
public void setAD_Image_ID (int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID)); } /** Get Image. @return Image or Icon */ public int getAD_Image_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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 Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Desktop.java
1
请完成以下Java代码
public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null"); this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets the {@link AuthenticationFailureHandler} used for handling an * {@link OAuth2AuthenticationException} and returning the {@link OAuth2Error Error * Response}. * @param authenticationFailureHandler the {@link AuthenticationFailureHandler} used * for handling an {@link OAuth2AuthenticationException} */ public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler; } private Authentication createAuthentication(HttpServletRequest request) { Authentication principal = SecurityContextHolder.getContext().getAuthentication(); return new OidcUserInfoAuthenticationToken(principal); } private void sendUserInfoResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { OidcUserInfoAuthenticationToken userInfoAuthenticationToken = (OidcUserInfoAuthenticationToken) authentication;
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); this.userInfoHttpMessageConverter.write(userInfoAuthenticationToken.getUserInfo(), null, httpResponse); } private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException { OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError(); HttpStatus httpStatus = HttpStatus.BAD_REQUEST; if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_TOKEN)) { httpStatus = HttpStatus.UNAUTHORIZED; } else if (error.getErrorCode().equals(OAuth2ErrorCodes.INSUFFICIENT_SCOPE)) { httpStatus = HttpStatus.FORBIDDEN; } ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(httpStatus); this.errorHttpResponseConverter.write(error, null, httpResponse); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcUserInfoEndpointFilter.java
1
请完成以下Java代码
public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public org.compiere.model.I_AD_Window getOverrides_Window() { return get_ValueAsPO(COLUMNNAME_Overrides_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setOverrides_Window(final org.compiere.model.I_AD_Window Overrides_Window) { set_ValueFromPO(COLUMNNAME_Overrides_Window_ID, org.compiere.model.I_AD_Window.class, Overrides_Window); } @Override public void setOverrides_Window_ID (final int Overrides_Window_ID) { if (Overrides_Window_ID < 1) set_Value (COLUMNNAME_Overrides_Window_ID, null); else set_Value (COLUMNNAME_Overrides_Window_ID, Overrides_Window_ID); } @Override public int getOverrides_Window_ID() { return get_ValueAsInt(COLUMNNAME_Overrides_Window_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } /** * WindowType AD_Reference_ID=108 * Reference name: AD_Window Types */ public static final int WINDOWTYPE_AD_Reference_ID=108; /** Single Record = S */ public static final String WINDOWTYPE_SingleRecord = "S"; /** Maintain = M */ public static final String WINDOWTYPE_Maintain = "M"; /** Transaktion = T */ public static final String WINDOWTYPE_Transaktion = "T";
/** Query Only = Q */ public static final String WINDOWTYPE_QueryOnly = "Q"; @Override public void setWindowType (final java.lang.String WindowType) { set_Value (COLUMNNAME_WindowType, WindowType); } @Override public java.lang.String getWindowType() { return get_ValueAsString(COLUMNNAME_WindowType); } @Override public void setWinHeight (final int WinHeight) { set_Value (COLUMNNAME_WinHeight, WinHeight); } @Override public int getWinHeight() { return get_ValueAsInt(COLUMNNAME_WinHeight); } @Override public void setWinWidth (final int WinWidth) { set_Value (COLUMNNAME_WinWidth, WinWidth); } @Override public int getWinWidth() { return get_ValueAsInt(COLUMNNAME_WinWidth); } @Override public void setZoomIntoPriority (final int ZoomIntoPriority) { set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority); } @Override public int getZoomIntoPriority() { return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
1
请完成以下Java代码
public Properties getContext() { return context; } /** * Invoke this method early on "entry"-threads like the main thread in case of the desktop client.<br> * This is to make sure that the current thread gets its own thread-local context before any child threads are created.<br> * Without calling this method the child thread would get its own empty context, which is not what we want. * * @task 08859 */ @Override public void init() { context.getDelegate(); }
@Override public IAutoCloseable switchContext(final Properties ctx) { return context.switchContext(ctx); } @Override public void reset() { context.dispose(); } void setListener(final IContextProviderListener listener) { context.setListener(listener); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\ThreadLocalContextProvider.java
1
请完成以下Java代码
public <T> IQueryFilter<T> toQueryFilterOrAllowAll() { return !isEmpty() ? TypedSqlQueryFilter.of(sql, sqlParams) : ConstantQueryFilter.of(true); } public SqlAndParams negate() { if (sql.isEmpty()) { return this; } return new SqlAndParams("NOT (" + this.sql + ")", this.sqlParams); } // // // --------------- // // public static class Builder { private StringBuilder sql = null; private ArrayList<Object> sqlParams = null; private Builder() { } /** * @deprecated I think you wanted to call {@link #build()} */ @Override @Deprecated public String toString() { return MoreObjects.toStringHelper(this) .add("sql", sql) .add("sqlParams", sqlParams) .toString(); } public SqlAndParams build() { final String sql = this.sql != null ? this.sql.toString() : ""; final Object[] sqlParamsArray = sqlParams != null ? sqlParams.toArray() : null; return new SqlAndParams(sql, sqlParamsArray); } public Builder clear() { sql = null; sqlParams = null; return this; } public boolean isEmpty() { return length() <= 0 && !hasParameters(); } public int length() { return sql != null ? sql.length() : 0; } public boolean hasParameters() { return sqlParams != null && !sqlParams.isEmpty(); } public int getParametersCount() { return sqlParams != null ? sqlParams.size() : 0; } public Builder appendIfHasParameters(@NonNull final CharSequence sql)
{ if (hasParameters()) { return append(sql); } else { return this; } } public Builder appendIfNotEmpty(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { if (!isEmpty()) { append(sql, sqlParams); } return this; } public Builder append(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { final List<Object> sqlParamsList = sqlParams != null && sqlParams.length > 0 ? Arrays.asList(sqlParams) : null; return append(sql, sqlParamsList); } public Builder append(@NonNull final CharSequence sql, @Nullable final List<Object> sqlParams) { if (sql.length() > 0) { if (this.sql == null) { this.sql = new StringBuilder(); } this.sql.append(sql); } if (sqlParams != null && !sqlParams.isEmpty()) { if (this.sqlParams == null) { this.sqlParams = new ArrayList<>(); } this.sqlParams.addAll(sqlParams); } return this; } public Builder append(@NonNull final SqlAndParams other) { return append(other.sql, other.sqlParams); } public Builder append(@NonNull final SqlAndParams.Builder other) { return append(other.sql, other.sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParams.java
1
请完成以下Java代码
public static MWorkflowProcessor[] getActive(Properties ctx) { List<MWorkflowProcessor> list = new Query(ctx, Table_Name, null, null) .setOnlyActiveRecords(true) .list(MWorkflowProcessor.class); MWorkflowProcessor[] retValue = new MWorkflowProcessor[list.size()]; list.toArray(retValue); return retValue; } // getActive /************************************************************************** * Standard Constructor * * @param ctx context * @param AD_WorkflowProcessor_ID id * @param trxName transaction */ public MWorkflowProcessor(Properties ctx, int AD_WorkflowProcessor_ID, String trxName) { super(ctx, AD_WorkflowProcessor_ID, trxName); } // MWorkflowProcessor /** * Load Constructor * * @param ctx context * @param rs result set * @param trxName transaction */ public MWorkflowProcessor(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MWorkflowProcessor /** * Get Server ID * * @return id */ @Override public String getServerID() { return "WorkflowProcessor" + get_ID(); } // getServerID /** * Get Date Next Run * * @param requery requery * @return date next run */ @Override public Timestamp getDateNextRun(boolean requery) { if (requery) load(get_TrxName());
return getDateNextRun(); } // getDateNextRun /** * Get Logs * * @return logs */ @Override public AdempiereProcessorLog[] getLogs() { List<MWorkflowProcessorLog> list = new Query(getCtx(), MWorkflowProcessorLog.Table_Name, "AD_WorkflowProcessor_ID=?", get_TrxName()) .setParameters(new Object[] { getAD_WorkflowProcessor_ID() }) .setOrderBy("Created DESC") .list(MWorkflowProcessorLog.class); MWorkflowProcessorLog[] retValue = new MWorkflowProcessorLog[list.size()]; list.toArray(retValue); return retValue; } // getLogs /** * Delete old Request Log * * @return number of records */ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_WorkflowProcessorLog " + "WHERE AD_WorkflowProcessor_ID=" + getAD_WorkflowProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MWorkflowProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\wf\MWorkflowProcessor.java
1
请完成以下Java代码
public void setDiscountDays (final int DiscountDays) { set_Value (COLUMNNAME_DiscountDays, DiscountDays); } @Override public int getDiscountDays() { return get_ValueAsInt(COLUMNNAME_DiscountDays); } @Override public void setGraceDays (final int GraceDays) { set_Value (COLUMNNAME_GraceDays, GraceDays); } @Override public int getGraceDays() { return get_ValueAsInt(COLUMNNAME_GraceDays); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } /** * NetDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int NETDAY_AD_Reference_ID=167; /** Sunday = 7 */ public static final String NETDAY_Sunday = "7"; /** Monday = 1 */ public static final String NETDAY_Monday = "1"; /** Tuesday = 2 */ public static final String NETDAY_Tuesday = "2"; /** Wednesday = 3 */ public static final String NETDAY_Wednesday = "3"; /** Thursday = 4 */
public static final String NETDAY_Thursday = "4"; /** Friday = 5 */ public static final String NETDAY_Friday = "5"; /** Saturday = 6 */ public static final String NETDAY_Saturday = "6"; @Override public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay() { return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setPercentage (final BigDecimal Percentage) { set_Value (COLUMNNAME_Percentage, Percentage); } @Override public BigDecimal getPercentage() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySchedule.java
1
请在Spring Boot框架中完成以下Java代码
public String getCONTACTID() { return contactid; } /** * Sets the value of the contactid property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTID(String value) { this.contactid = value; } /** * Gets the value of the contactdesc property. * * @return * possible object is * {@link String } * */ public String getCONTACTDESC() { return contactdesc; } /** * Sets the value of the contactdesc property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTDESC(String value) { this.contactdesc = value; } /** * Gets the value of the contacttelefon property. * * @return * possible object is * {@link String } * */ public String getCONTACTTELEFON() { return contacttelefon; } /** * Sets the value of the contacttelefon property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTTELEFON(String value) { this.contacttelefon = value; } /** * Gets the value of the contacttelefax property. * * @return * possible object is * {@link String } *
*/ public String getCONTACTTELEFAX() { return contacttelefax; } /** * Sets the value of the contacttelefax property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTTELEFAX(String value) { this.contacttelefax = value; } /** * Gets the value of the contactemail property. * * @return * possible object is * {@link String } * */ public String getCONTACTEMAIL() { return contactemail; } /** * Sets the value of the contactemail property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTEMAIL(String value) { this.contactemail = value; } /** * Gets the value of the contactweb property. * * @return * possible object is * {@link String } * */ public String getCONTACTWEB() { return contactweb; } /** * Sets the value of the contactweb property. * * @param value * allowed object is * {@link String } * */ public void setCONTACTWEB(String value) { this.contactweb = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DCTAD1.java
2
请在Spring Boot框架中完成以下Java代码
public Object regionValuesAdvice(ProceedingJoinPoint joinPoint) throws Throwable { return asCollection(joinPoint.proceed()).stream() .map(PdxInstanceWrapper::from) .collect(Collectors.toList()); } public static class RegionEntryWrapper<K, V> implements Region.Entry<K, V> { @SuppressWarnings("unchecked") public static <T, K, V> T from(T value) { return value instanceof Region.Entry ? (T) new RegionEntryWrapper<>((Region.Entry<K, V>) value) : value; } private final Region.Entry<K, V> delegate; protected RegionEntryWrapper(@NonNull Region.Entry<K, V> regionEntry) { Assert.notNull(regionEntry, "Region.Entry must not be null"); this.delegate = regionEntry; } protected @NonNull Region.Entry<K, V> getDelegate() { return this.delegate; } @Override public boolean isDestroyed() { return getDelegate().isDestroyed(); } @Override public boolean isLocal() { return getDelegate().isLocal(); } @Override public K getKey() { return getDelegate().getKey(); } @Override public Region<K, V> getRegion() { return getDelegate().getRegion(); }
@Override public CacheStatistics getStatistics() { return getDelegate().getStatistics(); } @Override public Object setUserAttribute(Object userAttribute) { return getDelegate().setUserAttribute(userAttribute); } @Override public Object getUserAttribute() { return getDelegate().getUserAttribute(); } @Override public V setValue(V value) { return getDelegate().setValue(value); } @Override @SuppressWarnings("unchecked") public V getValue() { return (V) PdxInstanceWrapper.from(getDelegate().getValue()); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java
2
请完成以下Java代码
public Engine getEngine() { return engine; } /** * Sets the {@link #engine}. * * @param engine * the new {@link #engine} */ public void setEngine(Engine engine) { this.engine = engine; } /** * Gets the {@link #brand}. * * @return the {@link #brand}
*/ public Brand getBrand() { return brand; } /** * Sets the {@link #brand}. * * @param brand * the new {@link #brand} */ public void setBrand(Brand brand) { this.brand = brand; } }
repos\tutorials-master\di-modules\dagger\src\main\java\com\baeldung\dagger\intro\Car.java
1
请完成以下Java代码
private static void assertCU(final @NonNull I_M_HU cuHU) { if (!HuPackingInstructionsVersionId.ofRepoId(cuHU.getM_HU_PI_Version_ID()).isVirtual()) { throw new AdempiereException("Expected to be CU: " + cuHU); } } private TULoaderInstanceKey extractTULoaderInstanceKeyFromCU(final I_M_HU cuHU) { return TULoaderInstanceKey.builder() .bpartnerId(IHandlingUnitsBL.extractBPartnerIdOrNull(cuHU)) .bpartnerLocationRepoId(cuHU.getC_BPartner_Location_ID()) .locatorId(warehouseDAO.getLocatorIdByRepoIdOrNull(cuHU.getM_Locator_ID())) .huStatus(cuHU.getHUStatus()) .clearanceStatusInfo(ClearanceStatusInfo.ofHU(cuHU)) .build(); } private TULoaderInstance newTULoaderInstance(@NonNull final TULoaderInstanceKey key) { return TULoaderInstance.builder() .huContext(huContext) .tuPI(tuPI) .capacity(capacity) .bpartnerId(key.getBpartnerId()) .bpartnerLocationRepoId(key.getBpartnerLocationRepoId()) .locatorId(key.getLocatorId()) .huStatus(key.getHuStatus()) .clearanceStatusInfo(key.getClearanceStatusInfo()) .build(); } //
// // @Value private static class TULoaderInstanceKey { @Nullable BPartnerId bpartnerId; int bpartnerLocationRepoId; @Nullable LocatorId locatorId; @Nullable String huStatus; @Nullable ClearanceStatusInfo clearanceStatusInfo; @Builder private TULoaderInstanceKey( @Nullable final BPartnerId bpartnerId, final int bpartnerLocationRepoId, @Nullable final LocatorId locatorId, @Nullable final String huStatus, @Nullable final ClearanceStatusInfo clearanceStatusInfo) { this.bpartnerId = bpartnerId; this.bpartnerLocationRepoId = bpartnerLocationRepoId > 0 ? bpartnerLocationRepoId : -1; this.locatorId = locatorId; this.huStatus = StringUtils.trimBlankToNull(huStatus); this.clearanceStatusInfo = clearanceStatusInfo; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoader.java
1
请完成以下Java代码
public void removeRowsById(@NonNull final DocumentIdsSelection rowIds) { if (rowIds.isEmpty()) { return; } compute(rows -> rows.removingRowIds(rowIds)); } @SuppressWarnings("unused") public void removingIf(@NonNull final Predicate<T> predicate) { compute(rows -> rows.removingIf(predicate)); } public void changeRowById(@NonNull DocumentId rowId, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRow(rowId, rowMapper)); } public void changeRowsByIds(@NonNull DocumentIdsSelection rowIds, @NonNull final UnaryOperator<T> rowMapper) { compute(rows -> rows.changingRows(rowIds, rowMapper)); } public void setRows(@NonNull final List<T> rows) { holder.setValue(ImmutableRowsIndex.of(rows)); } @NonNull private ImmutableRowsIndex<T> getRowsIndex()
{ final ImmutableRowsIndex<T> rowsIndex = holder.getValue(); // shall not happen if (rowsIndex == null) { throw new AdempiereException("rowsIndex shall be set"); } return rowsIndex; } public Predicate<DocumentId> isRelevantForRefreshingByDocumentId() { final ImmutableRowsIndex<T> rows = getRowsIndex(); return rows::isRelevantForRefreshing; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\SynchronizedRowsIndexHolder.java
1
请完成以下Java代码
public final PurchaseView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = newViewId(); final List<PurchaseDemand> demands = getDemands(request); final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands); final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList); final PurchaseView view = PurchaseView.builder() .viewId(viewId) .rowsSupplier(rowsSupplier) .additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors()) .build(); return view; } protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors() { return ImmutableList.of(); } private final PurchaseRowsSupplier createRowsSupplier( final ViewId viewId, final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList) { final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder()
.purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList) .viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff .purchaseRowFactory(purchaseRowFactory) .availabilityCheckService(availabilityCheckService) .build() .createPurchaseRowsSupplier(); return rowsSupplier; } protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass); Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass); return RelatedProcessDescriptor.builder() .processId(processId) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java
1
请完成以下Java代码
public JSONDocumentField setDisplayed(final LogicExpressionResult displayed, String adLanguage) { return setDisplayed(displayed.booleanValue(), extractReason(displayed, adLanguage)); } public JSONDocumentField setDisplayed(final boolean displayed) { setDisplayed(displayed, null); return this; } /* package */ void setLookupValuesStale(final boolean lookupValuesStale, @Nullable final String reason) { this.lookupValuesStale = lookupValuesStale; lookupValuesStaleReason = reason; } /* package */ JSONDocumentField setValidStatus(final JSONDocumentValidStatus validStatus) { this.validStatus = validStatus; return this; } @Nullable public Object getValue() { return value; } @JsonAnyGetter public Map<String, Object> getOtherProperties() { return otherProperties; } @JsonAnySetter public void putOtherProperty(final String name, final Object jsonValue) { otherProperties.put(name, jsonValue); } public JSONDocumentField putDebugProperty(final String name, final Object jsonValue)
{ otherProperties.put("debug-" + name, jsonValue); return this; } public void putDebugProperties(final Map<String, Object> debugProperties) { if (debugProperties == null || debugProperties.isEmpty()) { return; } for (final Map.Entry<String, Object> e : debugProperties.entrySet()) { putDebugProperty(e.getKey(), e.getValue()); } } public JSONDocumentField setViewEditorRenderMode(final ViewEditorRenderMode viewEditorRenderMode) { this.viewEditorRenderMode = viewEditorRenderMode != null ? viewEditorRenderMode.toJson() : null; return this; } public void setFieldWarning(@Nullable final JSONDocumentFieldWarning fieldWarning) { this.fieldWarning = fieldWarning; } public JSONDocumentField setDevices(@Nullable final List<JSONDeviceDescriptor> devices) { this.devices = devices; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentField.java
1
请完成以下Java代码
private IHUPackingAware createQuickInputPackingAware( @NonNull final I_M_Forecast forecast, @NonNull final IForecastLineQuickInput quickInput) { final PlainHUPackingAware huPackingAware = createAndInitHuPackingAware(forecast, quickInput); final BigDecimal quickInputQty = quickInput.getQty(); if (quickInputQty == null || quickInputQty.signum() <= 0) { throw new AdempiereException("Qty shall be greather than zero"); } huPackingAwareBL.computeAndSetQtysForNewHuPackingAware(huPackingAware, quickInputQty); return validateNewHuPackingAware(huPackingAware); } private PlainHUPackingAware createAndInitHuPackingAware( @NonNull final I_M_Forecast forecast, @NonNull final IForecastLineQuickInput quickInput) { final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setC_BPartner_ID(forecast.getC_BPartner_ID()); huPackingAware.setInDispute(false); final ProductAndAttributes productAndAttributes = ProductLookupDescriptor.toProductAndAttributes(quickInput.getM_Product_ID()); final I_M_Product product = load(productAndAttributes.getProductId(), I_M_Product.class); huPackingAware.setM_Product_ID(product.getM_Product_ID()); huPackingAware.setC_UOM_ID(product.getC_UOM_ID()); huPackingAware.setM_AttributeSetInstance_ID(createASI(productAndAttributes)); final int piItemProductId = quickInput.getM_HU_PI_Item_Product_ID(); huPackingAware.setM_HU_PI_Item_Product_ID(piItemProductId); return huPackingAware; } private PlainHUPackingAware validateNewHuPackingAware(@NonNull final PlainHUPackingAware huPackingAware) { if (huPackingAware.getQty() == null || huPackingAware.getQty().signum() <= 0) { throw new AdempiereException("Qty shall be greather than zero"); }
if (huPackingAware.getQtyTU() == null || huPackingAware.getQtyTU().signum() <= 0) { throw new AdempiereException("QtyTU shall be greather than zero"); } return huPackingAware; } private static final int createASI(final ProductAndAttributes productAndAttributes) { final ImmutableAttributeSet attributes = productAndAttributes.getAttributes(); if (attributes.isEmpty()) { return -1; } final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final I_M_AttributeSetInstance asi = asiBL.createASIWithASFromProductAndInsertAttributeSet( productAndAttributes.getProductId(), attributes); return asi.getM_AttributeSetInstance_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\forecastline\ForecastLineQuickInputProcessor.java
1
请完成以下Java代码
protected String getEngineVersion() { return DmnEngine.VERSION; } @Override protected String getSchemaVersionPropertyName() { return "dmn.schema.version"; } @Override protected String getDbSchemaLockName() { return DMN_DB_SCHEMA_LOCK_NAME; } @Override protected String getEngineTableName() { return "ACT_DMN_DECISION"; } @Override protected String getChangeLogTableName() {
return "ACT_DMN_DATABASECHANGELOG"; } @Override protected String getDbVersionForChangelogVersion(String changeLogVersion) { if (StringUtils.isNotEmpty(changeLogVersion) && changeLogVersionMap.containsKey(changeLogVersion)) { return changeLogVersionMap.get(changeLogVersion); } return "5.99.0.0"; } @Override protected String getResourcesRootDirectory() { return "org/flowable/dmn/db/"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\db\DmnDbSchemaManager.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Budget Control. @param GL_BudgetControl_ID Budget Control */ public void setGL_BudgetControl_ID (int GL_BudgetControl_ID) { if (GL_BudgetControl_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_BudgetControl_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_BudgetControl_ID, Integer.valueOf(GL_BudgetControl_ID)); } /** Get Budget Control. @return Budget Control */ public int getGL_BudgetControl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_BudgetControl_ID); if (ii == null) return 0; return ii.intValue(); } public I_GL_Budget getGL_Budget() throws RuntimeException { return (I_GL_Budget)MTable.get(getCtx(), I_GL_Budget.Table_Name) .getPO(getGL_Budget_ID(), get_TrxName()); } /** Set Budget. @param GL_Budget_ID General Ledger Budget */ public void setGL_Budget_ID (int GL_Budget_ID) { if (GL_Budget_ID < 1) set_Value (COLUMNNAME_GL_Budget_ID, null); else set_Value (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); } /** Get Budget. @return General Ledger Budget */ public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_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 Before Approval. @param IsBeforeApproval The Check is before the (manual) approval */
public void setIsBeforeApproval (boolean IsBeforeApproval) { set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval)); } /** Get Before Approval. @return The Check is before the (manual) approval */ public boolean isBeforeApproval () { Object oo = get_Value(COLUMNNAME_IsBeforeApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_BudgetControl.java
1
请完成以下Java代码
static class PersonWriteConverter implements Converter<Contact, String> { public String convert(Contact source) { try { return new ObjectMapper().writeValueAsString(source); } catch (IOException e) { throw new IllegalStateException(e); } } } /** * Read a {@link Contact} from its {@link String} representation. */ static class PersonReadConverter implements Converter<String, Contact> { public Contact convert(String source) { if (StringUtils.hasText(source)) { try { return new ObjectMapper().readValue(source, Contact.class); } catch (IOException e) { throw new IllegalStateException(e); } } return null; } } /** * Perform custom mapping by reading a {@link Row} into a custom class. */
static class CustomAddressbookReadConverter implements Converter<Row, CustomAddressbook> { public CustomAddressbook convert(Row source) { return new CustomAddressbook(source.getString("id"), source.getString("me")); } } enum StringToCurrencyConverter implements Converter<String, Currency> { INSTANCE; @Override public Currency convert(String source) { return Currency.getInstance(source); } } enum CurrencyToStringConverter implements Converter<Currency, String> { INSTANCE; @Override public String convert(Currency source) { return source.getCurrencyCode(); } } }
repos\spring-data-examples-main\cassandra\example\src\main\java\example\springdata\cassandra\convert\ConverterConfiguration.java
1
请完成以下Java代码
public Object run() { String bucketId = getId(RequestContext.getCurrentContext().getRequest()); Bucket bucket = buckets.getProxy(bucketId, getConfigSupplier()); if (bucket.tryConsume(1)) { // the limit is not exceeded log.debug("API rate limit OK for {}", bucketId); } else { // limit is exceeded log.info("API rate limit exceeded for {}", bucketId); apiLimitExceeded(); } return null; } private Supplier<BucketConfiguration> getConfigSupplier() { return () -> { JHipsterProperties.Gateway.RateLimiting rateLimitingProperties = jHipsterProperties.getGateway().getRateLimiting(); return Bucket4j.configurationBuilder() .addLimit(Bandwidth.simple(rateLimitingProperties.getLimit(), Duration.ofSeconds(rateLimitingProperties.getDurationInSeconds())))
.build(); }; } /** * Create a Zuul response error when the API limit is exceeded. */ private void apiLimitExceeded() { RequestContext ctx = RequestContext.getCurrentContext(); ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); if (ctx.getResponseBody() == null) { ctx.setResponseBody("API rate limit exceeded"); ctx.setSendZuulResponse(false); } } /** * The ID that will identify the limit: the user login or the user IP address. */ private String getId(HttpServletRequest httpServletRequest) { return SecurityUtils.getCurrentUserLogin().orElse(httpServletRequest.getRemoteAddr()); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\ratelimiting\RateLimitingFilter.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessInstanceId() { return processInstanceId; } public String getTaskDefinitionKey() { return taskDefinitionKey; } public Date getFollowUp() { return followUp; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseExecutionId() { return caseExecutionId; } public String getCaseInstanceId() { return caseInstanceId; }
public boolean isSuspended() { return suspended; } public String getFormKey() { return formKey; } public CamundaFormRef getCamundaFormRef() { return camundaFormRef; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\task\HalTask.java
1
请完成以下Java代码
static class Variables extends VariableMapper { Map<String, ValueExpression> map = Collections.emptyMap(); @Override public ValueExpression resolveVariable(String variable) { return map.get(variable); } @Override public ValueExpression setVariable(String variable, ValueExpression expression) { if (map.isEmpty()) { map = new HashMap<String, ValueExpression>(); } return map.put(variable, expression); } } private Functions functions; private Variables variables; private ELResolver resolver; /** * Create a context. */ public SimpleContext() { this(null); } /** * Create a context, use the specified resolver. */ public SimpleContext(ELResolver resolver) { this.resolver = resolver; } /** * Define a function. */ public void setFunction(String prefix, String localName, Method method) { if (functions == null) { functions = new Functions(); } functions.setFunction(prefix, localName, method); } /** * Define a variable. */ public ValueExpression setVariable(String name, ValueExpression expression) { if (variables == null) { variables = new Variables(); } return variables.setVariable(name, expression); } /** * Get our function mapper. */ @Override
public FunctionMapper getFunctionMapper() { if (functions == null) { functions = new Functions(); } return functions; } /** * Get our variable mapper. */ @Override public VariableMapper getVariableMapper() { if (variables == null) { variables = new Variables(); } return variables; } /** * Get our resolver. Lazy initialize to a {@link SimpleResolver} if necessary. */ @Override public ELResolver getELResolver() { if (resolver == null) { resolver = new SimpleResolver(); } return resolver; } /** * Set our resolver. * * @param resolver */ public void setELResolver(ELResolver resolver) { this.resolver = resolver; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\SimpleContext.java
1
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTitle() { return title ; } public void setTitle(String openType) { this.title = openType; } public String getContent() { return content; } public void setContent(String content) {
this.content = content; } public static UniPushTypeEnum getByType(String type) { if (oConvertUtils.isEmpty(type)) { return null; } for (UniPushTypeEnum val : values()) { if (val.getType().equals(type)) { return val; } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\UniPushTypeEnum.java
1
请完成以下Java代码
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
1
请在Spring Boot框架中完成以下Java代码
public BPartner getBpartner() { return bpartner; } public void setBpartner(final BPartner bpartner) { this.bpartner = bpartner; } public LocalDate getDateFrom() { return DateUtils.toLocalDate(dateFrom); } public void setDateFrom(@NonNull final LocalDate dateFrom) { this.dateFrom = DateUtils.toSqlDate(dateFrom); } public LocalDate getDateTo() { return DateUtils.toLocalDate(dateTo); } public void setDateTo(@NonNull final LocalDate dateTo) { this.dateTo = DateUtils.toSqlDate(dateTo); } public void setRfq_uuid(final String rfq_uuid) { this.rfq_uuid = rfq_uuid; } public boolean isRfq() { return rfq_uuid != null; } public List<ContractLine> getContractLines() { return Collections.unmodifiableList(contractLines); } @Nullable public ContractLine getContractLineForProductOrNull(final Product product) { for (final ContractLine contractLine : getContractLines()) { if (Product.COMPARATOR_Id.compare(contractLine.getProduct(), product) != 0)
{ continue; } return contractLine; } return null; } public Collection<Product> getProducts() { final Set<Product> products = new TreeSet<>(Product.COMPARATOR_Id); for (final ContractLine contractLine : getContractLines()) { if (contractLine.isDeleted()) { continue; } final Product product = contractLine.getProduct(); if (product.isDeleted()) { continue; } products.add(product); } return products; } public boolean matchesDate(final LocalDate date) { return DateUtils.between(date, getDateFrom(), getDateTo()); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contract.java
2
请完成以下Java代码
public class CacheCorpus extends Corpus { private RandomAccessFile raf; public CacheCorpus(Corpus cloneSrc) throws IOException { super(cloneSrc); raf = new RandomAccessFile(((TextFileCorpus) cloneSrc).cacheFile, "r"); } @Override public String nextWord() throws IOException { return null; } @Override public int readWordIndex() throws IOException { int id = nextId(); while (id == -4) { id = nextId();
} return id; } private int nextId() throws IOException { if (raf.length() - raf.getFilePointer() >= 4) { int id = raf.readInt(); return id < 0 ? id : table[id]; } return -2; } @Override public void rewind(int numThreads, int id) throws IOException { super.rewind(numThreads, id); raf.seek(raf.length() / 4 / numThreads * id * 4); // spilt by id, not by bytes } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\CacheCorpus.java
1
请在Spring Boot框架中完成以下Java代码
List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolverContext context, @Nullable ConfigDataLocation location, @Nullable Profiles profiles) { if (location == null) { return Collections.emptyList(); } for (ConfigDataLocationResolver<?> resolver : getResolvers()) { if (resolver.isResolvable(context, location)) { return resolve(resolver, context, location, profiles); } } throw new UnsupportedConfigDataLocationException(location); } private List<ConfigDataResolutionResult> resolve(ConfigDataLocationResolver<?> resolver, ConfigDataLocationResolverContext context, ConfigDataLocation location, @Nullable Profiles profiles) { List<ConfigDataResolutionResult> resolved = resolve(location, false, () -> resolver.resolve(context, location)); if (profiles == null) { return resolved; } List<ConfigDataResolutionResult> profileSpecific = resolve(location, true, () -> resolver.resolveProfileSpecific(context, location, profiles)); return merge(resolved, profileSpecific); } private List<ConfigDataResolutionResult> resolve(ConfigDataLocation location, boolean profileSpecific, Supplier<List<? extends ConfigDataResource>> resolveAction) { List<ConfigDataResource> resources = nonNullList(resolveAction.get()); List<ConfigDataResolutionResult> resolved = new ArrayList<>(resources.size()); for (ConfigDataResource resource : resources) { resolved.add(new ConfigDataResolutionResult(location, resource, profileSpecific)); } return resolved; }
@SuppressWarnings("unchecked") private <T> List<T> nonNullList(@Nullable List<? extends T> list) { return (list != null) ? (List<T>) list : Collections.emptyList(); } private <T> List<T> merge(List<T> list1, List<T> list2) { List<T> merged = new ArrayList<>(list1.size() + list2.size()); merged.addAll(list1); merged.addAll(list2); return merged; } /** * Return the resolvers managed by this object. * @return the resolvers */ List<ConfigDataLocationResolver<?>> getResolvers() { return this.resolvers; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataLocationResolvers.java
2
请完成以下Java代码
private static IPair<String, Integer> toPrefixAndEntryId(final DocumentId id) { final List<String> idParts = ID_Splitter.splitToList(id.toJson()); if (idParts.size() != 2) { throw new IllegalArgumentException("Invalid attachment ID"); } final String idPrefix = idParts.get(0); final int entryId = Integer.parseInt(idParts.get(1)); return ImmutablePair.of(idPrefix, entryId); } private static DocumentId buildId(final String idPrefix, final int id) { return DocumentId.ofString(ID_Joiner.join(idPrefix, id)); } /** * If the document contains some attachment related tabs, it will send an "stale" notification to frontend. * In this way, frontend will be aware of this and will have to refresh the tab.
*/ private void notifyRelatedDocumentTabsChanged() { final ImmutableSet<DetailId> attachmentRelatedTabIds = entityDescriptor .getIncludedEntities().stream() .filter(includedEntityDescriptor -> Objects.equals(includedEntityDescriptor.getTableNameOrNull(), I_AD_AttachmentEntry.Table_Name)) .map(DocumentEntityDescriptor::getDetailId) .collect(ImmutableSet.toImmutableSet()); if (attachmentRelatedTabIds.isEmpty()) { return; } websocketPublisher.staleTabs(documentPath.getWindowId(), documentPath.getDocumentId(), attachmentRelatedTabIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachments.java
1
请完成以下Java代码
private Optional<DelegatingAppender> getDelegate() { return Optional.ofNullable(this.delegate); } private Optional<ch.qos.logback.classic.Logger> getLogger() { return Optional.ofNullable(this.logger); } private Context resolveContext() { return this.context != null ? this.context : Optional.ofNullable(LoggerFactory.getILoggerFactory()) .filter(Context.class::isInstance) .map(Context.class::cast) .orElse(null); } private String resolveName() { return this.name != null && !this.name.trim().isEmpty() ? this.name : DEFAULT_NAME; } private StringAppenderWrapper resolveStringAppenderWrapper() { return this.useSynchronization ? StringBufferAppenderWrapper.create() : StringBuilderAppenderWrapper.create(); } public StringAppender build() { StringAppender stringAppender = new StringAppender(resolveStringAppenderWrapper()); stringAppender.setContext(resolveContext()); stringAppender.setName(resolveName()); getDelegate().ifPresent(delegate -> { Appender appender = this.replace ? stringAppender : CompositeAppender.compose(delegate.getAppender(), stringAppender); delegate.setAppender(appender); }); getLogger().ifPresent(logger -> logger.addAppender(stringAppender)); return stringAppender; } public StringAppender buildAndStart() { StringAppender stringAppender = build(); stringAppender.start(); return stringAppender; } } private final StringAppenderWrapper stringAppenderWrapper; protected StringAppender(StringAppenderWrapper stringAppenderWrapper) { if (stringAppenderWrapper == null) {
throw new IllegalArgumentException("StringAppenderWrapper must not be null"); } this.stringAppenderWrapper = stringAppenderWrapper; } public String getLogOutput() { return getStringAppenderWrapper().toString(); } protected StringAppenderWrapper getStringAppenderWrapper() { return this.stringAppenderWrapper; } @Override protected void append(ILoggingEvent loggingEvent) { Optional.ofNullable(loggingEvent) .map(event -> preProcessLogMessage(toString(event))) .filter(this::isValidLogMessage) .ifPresent(getStringAppenderWrapper()::append); } protected boolean isValidLogMessage(String message) { return message != null && !message.isEmpty(); } protected String preProcessLogMessage(String message) { return message != null ? message.trim() : null; } protected String toString(ILoggingEvent loggingEvent) { return loggingEvent != null ? loggingEvent.getFormattedMessage() : null; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\StringAppender.java
1
请完成以下Java代码
public void handleEvictEvent(QrCodeSettingsEvictEvent event) { cache.evict(event.getTenantId()); } private QrCodeSettings constructMobileAppSettings(QrCodeSettings qrCodeSettings) { if (qrCodeSettings == null) { qrCodeSettings = new QrCodeSettings(); qrCodeSettings.setUseDefaultApp(true); qrCodeSettings.setAndroidEnabled(true); qrCodeSettings.setIosEnabled(true); QRCodeConfig qrCodeConfig = QRCodeConfig.builder() .showOnHomePage(true) .qrCodeLabelEnabled(true) .qrCodeLabel(DEFAULT_QR_CODE_LABEL) .badgeEnabled(true) .badgePosition(BadgePosition.RIGHT) .badgeEnabled(true) .build();
qrCodeSettings.setQrCodeConfig(qrCodeConfig); qrCodeSettings.setMobileAppBundleId(qrCodeSettings.getMobileAppBundleId()); } if (qrCodeSettings.isUseDefaultApp() || qrCodeSettings.getMobileAppBundleId() == null) { qrCodeSettings.setGooglePlayLink(googlePlayLink); qrCodeSettings.setAppStoreLink(appStoreLink); } else { MobileApp androidApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), ANDROID); MobileApp iosApp = mobileAppService.findByBundleIdAndPlatformType(qrCodeSettings.getTenantId(), qrCodeSettings.getMobileAppBundleId(), IOS); if (androidApp != null && androidApp.getStoreInfo() != null) { qrCodeSettings.setGooglePlayLink(androidApp.getStoreInfo().getStoreLink()); } if (iosApp != null && iosApp.getStoreInfo() != null) { qrCodeSettings.setAppStoreLink(iosApp.getStoreInfo().getStoreLink()); } } return qrCodeSettings; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\QrCodeSettingServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static File getReportsDirOfProjectDirIfExists(final File projectDir) { final File reportsDir = new File(projectDir, "src//main//jasperreports"); if (reportsDir.exists() && reportsDir.isDirectory()) { return reportsDir; } else { return null; } } private static boolean isProjectDir(final File dir) { return dir.isDirectory()
&& new File(dir, "pom.xml").exists() && !isIgnore(dir); } private static boolean isIgnore(final File dir) { return new File(dir, ".ignore-reports").exists(); } private static boolean isMetasfreshRepository(@NonNull final File projectDir) { return "metasfresh".equals(projectDir.getName()) && projectDir.isDirectory(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\util\DevelopmentWorkspaceJasperDirectoriesFinder.java
2
请完成以下Java代码
public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent. @param Parent_ID Parent of Entity */ public void setParent_ID (int Parent_ID) { if (Parent_ID < 1) set_Value (COLUMNNAME_Parent_ID, null); else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent. @return Parent of Entity */ public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first
*/ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); 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_TreeNode.java
1
请完成以下Java代码
private GraphServiceClient<Request> newClient(@NonNull final Mailbox mailbox, @NonNull final ILogger logger) { final MicrosoftGraphConfig microsoftGraphConfig = mailbox.getMicrosoftGraphConfigNotNull(); return GraphServiceClient.builder() .authenticationProvider( new TokenCredentialAuthProvider( ImmutableList.of("https://graph.microsoft.com/.default"), new ClientSecretCredentialBuilder() .clientId(microsoftGraphConfig.getClientId()) .clientSecret(microsoftGraphConfig.getClientSecret()) .tenantId(microsoftGraphConfig.getTenantId()) .build() ) ) .logger(logger) .buildClient(); } private static String toString(@NonNull final Message message) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(message); } catch (final JsonProcessingException e) { return message.toString(); } } // // // // @RequiredArgsConstructor private static class LoggableAsGraphLoggerAdapter implements ILogger { @NonNull private final ILoggable loggable; @NonNull @Getter @Setter private LoggerLevel loggingLevel = LoggerLevel.DEBUG; @Override public void logDebug(@NonNull final String message) { loggable.addLog(message); } @Override public void logError(@NonNull final String message, @Nullable final Throwable throwable) { final StringBuilder finalMessage = new StringBuilder("ERROR: ").append(message); if (throwable != null) { finalMessage.append("\n").append(Util.dumpStackTraceToString(throwable)); } loggable.addLog(finalMessage.toString()); } } @RequiredArgsConstructor private static class SLF4JAsGraphLoggerAdapter implements ILogger { @NonNull private final Logger logger; @Override public void setLoggingLevel(@NonNull final LoggerLevel level) { switch (level) { case ERROR: LogManager.setLoggerLevel(logger, Level.WARN); break; case DEBUG:
default: LogManager.setLoggerLevel(logger, Level.DEBUG); break; } } @Override public @NonNull LoggerLevel getLoggingLevel() { final Level level = LogManager.getLoggerLevel(logger); if (level == null) { return LoggerLevel.DEBUG; } else if (Level.ERROR.equals(level) || Level.WARN.equals(level)) { return LoggerLevel.ERROR; } else { return LoggerLevel.DEBUG; } } @Override public void logDebug(@NonNull final String message) { logger.debug(message); } @Override public void logError(@NonNull final String message, @Nullable final Throwable throwable) { logger.warn(message, throwable); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\sender\MicrosoftGraphMailSender.java
1
请完成以下Java代码
public BPartnerLocationAddressPart toAddress() { return BPartnerLocationAddressPart.builder() .existingLocationId(getExistingLocationId()) .address1(getAddress1()) .address2(getAddress2()) .address3(getAddress3()) .address4(getAddress4()) .poBox(getPoBox()) .postal(getPostal()) .city(getCity()) .region(getRegion()) .district(getDistrict()) .countryCode(getCountryCode()) .build(); } public void setFromAddress(@NonNull final BPartnerLocationAddressPart address) { setExistingLocationId(address.getExistingLocationId()); setAddress1(address.getAddress1()); setAddress2(address.getAddress2()); setAddress3(address.getAddress3()); setAddress4(address.getAddress4()); setCity(address.getCity()); setCountryCode(address.getCountryCode()); setPoBox(address.getPoBox());
setPostal(address.getPostal()); setRegion(address.getRegion()); setDistrict(address.getDistrict()); } @Nullable public LocationId getExistingLocationIdNotNull() { return Check.assumeNotNull(getExistingLocationId(), "existingLocationId not null: {}", this); } /** * Can be used if this instance's ID is known to be not null. */ @NonNull public BPartnerLocationId getIdNotNull() { return Check.assumeNotNull(id, "id may not be null at this point"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocation.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null"); } if (variableName == null) { throw new FlowableIllegalArgumentException("variable name is null"); } CaseInstanceEntity caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceId); if (caseInstanceEntity == null) { throw new FlowableObjectNotFoundException("No case instance found for id " + caseInstanceId, CaseInstanceEntity.class); } caseInstanceEntity.setVariable(variableName, variableValue); CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext); CmmnDeploymentManager deploymentManager = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getDeploymentManager(); CaseDefinition caseDefinition = deploymentManager.findDeployedCaseDefinitionById(caseInstanceEntity.getCaseDefinitionId()); boolean evaluateVariableEventListener = false; if (caseDefinition != null) { CmmnModel cmmnModel = deploymentManager.resolveCaseDefinition(caseDefinition).getCmmnModel(); for (Case caze : cmmnModel.getCases()) { List<VariableEventListener> variableEventListeners = caze.findPlanItemDefinitionsOfType(VariableEventListener.class); for (VariableEventListener variableEventListener : variableEventListeners) { if (variableName.equals(variableEventListener.getVariableName())) {
evaluateVariableEventListener = true; break; } } if (evaluateVariableEventListener) { break; } } } if (evaluateVariableEventListener) { agenda.planEvaluateVariableEventListenersOperation(caseInstanceId); } agenda.planEvaluateCriteriaOperation(caseInstanceId); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetVariableCmd.java
1
请完成以下Java代码
public int getC_CostClassification_Category_ID() { return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_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 setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated()
{ return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CostClassification_Category_Trl.java
1
请完成以下Java代码
public static Map<String, String> parseURLQueryString(@Nullable final String query) { final String queryNorm = trimBlankToNull(query); if (queryNorm == null) { return ImmutableMap.of(); } final HashMap<String, String> params = new HashMap<>(); for (final String param : queryNorm.split("&")) { final String key; final String value; final int idx = param.indexOf("="); if (idx < 0) { key = param; value = null; } else { key = param.substring(0, idx); value = param.substring(idx + 1); } params.put(key, value); } return params; } @Nullable public static String ucFirst(@Nullable final String str) { if (str == null || str.isEmpty()) {
return str; } final char first = str.charAt(0); if (!Character.isLetter(first)) { return str; } final char capital = Character.toUpperCase(first); if(first == capital) { return str; } final StringBuilder sb = new StringBuilder(str); sb.setCharAt(0, capital); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StringUtils.java
1
请在Spring Boot框架中完成以下Java代码
public void setMonitorInterval(long monitorInterval) { this.monitorInterval = monitorInterval; } /** * Each queue runs in its own consumer; set this property to create multiple * consumers for each queue. * If the container is already running, the number of consumers per queue will * be adjusted up or down as necessary. * @param consumersPerQueue the consumers per queue. */ public void setConsumersPerQueue(Integer consumersPerQueue) { this.consumersPerQueue = consumersPerQueue; } /** * Set the number of messages to receive before acknowledging (success). * A failed message will short-circuit this counter. * @param messagesPerAck the number of messages. * @see #setAckTimeout(Long) */ public void setMessagesPerAck(Integer messagesPerAck) { this.messagesPerAck = messagesPerAck; } /** * An approximate timeout; when {@link #setMessagesPerAck(Integer) messagesPerAck} is * greater than 1, and this time elapses since the last ack, the pending acks will be * sent either when the next message arrives, or a short time later if no additional * messages arrive. In that case, the actual time depends on the * {@link #setMonitorInterval(long) monitorInterval}. * @param ackTimeout the timeout in milliseconds (default 20000); * @see #setMessagesPerAck(Integer) */ public void setAckTimeout(Long ackTimeout) { this.ackTimeout = ackTimeout; } @Override protected DirectMessageListenerContainer createContainerInstance() {
return new DirectMessageListenerContainer(); } @Override protected void initializeContainer(DirectMessageListenerContainer instance, @Nullable RabbitListenerEndpoint endpoint) { super.initializeContainer(instance, endpoint); JavaUtils javaUtils = JavaUtils.INSTANCE.acceptIfNotNull(this.taskScheduler, instance::setTaskScheduler) .acceptIfNotNull(this.monitorInterval, instance::setMonitorInterval) .acceptIfNotNull(this.messagesPerAck, instance::setMessagesPerAck) .acceptIfNotNull(this.ackTimeout, instance::setAckTimeout); if (endpoint != null && endpoint.getConcurrency() != null) { try { instance.setConsumersPerQueue(Integer.parseInt(endpoint.getConcurrency())); } catch (NumberFormatException e) { throw new IllegalStateException("Failed to parse concurrency: " + e.getMessage(), e); } } else { javaUtils.acceptIfNotNull(this.consumersPerQueue, instance::setConsumersPerQueue); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\DirectRabbitListenerContainerFactory.java
2
请完成以下Java代码
/* package */ boolean isCreateSelectionOfInsertedRows() { return createSelectionOfInsertedRows; } /* package */String getToKeyColumnName() { return InterfaceWrapperHelper.getKeyColumnName(toModelClass); } /** * @return "To ColumnName" to "From Column" map */ /* package */ Map<String, IQueryInsertFromColumn> getColumnMapping() { return toColumn2fromColumnRO; }
/* package */ boolean isEmpty() { return toColumn2fromColumn.isEmpty(); } /* package */ String getToTableName() { return toTableName; } /* package */ Class<ToModelType> getToModelClass() { return toModelClass; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryInsertExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public ObjectName getObjectName(ExposableJmxEndpoint endpoint) throws MalformedObjectNameException { StringBuilder builder = new StringBuilder(determineDomain()); builder.append(":type=Endpoint"); builder.append(",name=").append(StringUtils.capitalize(endpoint.getEndpointId().toString())); String baseName = builder.toString(); if (this.mBeanServer != null && hasMBean(baseName)) { builder.append(",context=").append(this.contextId); } if (this.jmxProperties.isUniqueNames()) { String identity = ObjectUtils.getIdentityHexString(endpoint); builder.append(",identity=").append(identity); } builder.append(getStaticNames()); return ObjectNameManager.getInstance(builder.toString()); } private String determineDomain() { if (StringUtils.hasText(this.properties.getDomain())) { return this.properties.getDomain(); } if (StringUtils.hasText(this.jmxProperties.getDefaultDomain())) { return this.jmxProperties.getDefaultDomain(); } return "org.springframework.boot";
} private boolean hasMBean(String baseObjectName) throws MalformedObjectNameException { ObjectName query = new ObjectName(baseObjectName + ",*"); Assert.state(this.mBeanServer != null, "'mBeanServer' must not be null"); return !this.mBeanServer.queryNames(query, null).isEmpty(); } private String getStaticNames() { if (this.properties.getStaticNames().isEmpty()) { return ""; } StringBuilder builder = new StringBuilder(); this.properties.getStaticNames() .forEach((name, value) -> builder.append(",").append(name).append("=").append(value)); return builder.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\DefaultEndpointObjectNameFactory.java
2
请完成以下Java代码
public Builder setRecord(final ITableRecordReference record) { putProperty(Event.PROPERTY_Record, record); return this; } public Builder putPropertyFromObject(final String name, @Nullable final Object value) { if (value == null) { properties.remove(name); return this; } else if (value instanceof Integer) { return putProperty(name, value); } else if (value instanceof Long) { return putProperty(name, value); } else if (value instanceof Double) { final double doubleValue = (Double)value; final int intValue = (int)doubleValue; if (doubleValue == intValue) { return putProperty(name, intValue); } else { return putProperty(name, BigDecimal.valueOf(doubleValue)); } } else if (value instanceof String) { return putProperty(name, (String)value); } else if (value instanceof Date) { return putProperty(name, (Date)value); } else if (value instanceof Boolean) { return putProperty(name, value); } else if (value instanceof ITableRecordReference) { return putProperty(name, (ITableRecordReference)value); } else if (value instanceof BigDecimal) { return putProperty(name, (BigDecimal)value); } else if (value instanceof List) { return putProperty(name, (List<?>)value); }
else { throw new AdempiereException("Unknown value type " + name + " = " + value + " (type " + value.getClass() + ")"); } } public Builder setSuggestedWindowId(final int suggestedWindowId) { putProperty(PROPERTY_SuggestedWindowId, suggestedWindowId); return this; } public Builder wasLogged() { this.loggingStatus = LoggingStatus.WAS_LOGGED; return this; } public Builder shallBeLogged() { this.loggingStatus = LoggingStatus.SHALL_BE_LOGGED; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\Event.java
1
请完成以下Java代码
private boolean isFinalActivity(final PPOrderRoutingActivity activity) { return getNextActivityCodes(activity).isEmpty(); } public ImmutableSet<ProductId> getProductIdsByActivityId(@NonNull final PPOrderRoutingActivityId activityId) { return getProducts() .stream() .filter(activityProduct -> activityProduct.getId() != null && PPOrderRoutingActivityId.equals(activityProduct.getId().getActivityId(), activityId)) .map(PPOrderRoutingProduct::getProductId) .collect(ImmutableSet.toImmutableSet()); } public void voidIt() { getActivities().forEach(PPOrderRoutingActivity::voidIt); } public void reportProgress(final PPOrderActivityProcessReport report) { getActivityById(report.getActivityId()).reportProgress(report); } public void completeActivity(final PPOrderRoutingActivityId activityId) {
getActivityById(activityId).completeIt(); } public void closeActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).closeIt(); } public void uncloseActivity(final PPOrderRoutingActivityId activityId) { getActivityById(activityId).uncloseIt(); } @NonNull public RawMaterialsIssueStrategy getIssueStrategyForRawMaterialsActivity() { return activities.stream() .filter(activity -> activity.getType() == PPRoutingActivityType.RawMaterialsIssue) .findFirst() .map(PPOrderRoutingActivity::getRawMaterialsIssueStrategy) .orElse(RawMaterialsIssueStrategy.DEFAULT); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRouting.java
1
请完成以下Java代码
public PayPalOrder getById(@NonNull final PayPalOrderId id) { return paypalOrderRepo.getById(id); } public PayPalOrder getByReservationId(@NonNull final PaymentReservationId reservationId) { return getByReservationIdIfExists(reservationId) .orElseThrow(() -> new AdempiereException("@NotFound@ @PayPal_Order_ID@: " + reservationId)); } public PayPalOrder getByExternalId(@NonNull final PayPalOrderExternalId externalId) { return paypalOrderRepo.getByExternalId(externalId); } public Optional<PayPalOrder> getByReservationIdIfExists(@NonNull final PaymentReservationId reservationId) { return paypalOrderRepo.getByReservationId(reservationId);
} public PayPalOrder create(@NonNull final PaymentReservationId reservationId) { return paypalOrderRepo.create(reservationId); } public PayPalOrder save( @NonNull final PayPalOrderId id, @NonNull final com.paypal.orders.Order apiOrder) { return paypalOrderRepo.save(id, apiOrder); } public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id) { return paypalOrderRepo.markRemoteDeleted(id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderService.java
1
请完成以下Java代码
public final class Util { private Util() { super(); } public static byte[] toByteArray(final InputStream in) throws RuntimeException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { final byte[] buf = new byte[1024 * 4]; int len = -1; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final IOException e) { throw new RuntimeException(e); } return out.toByteArray(); } public static <T> T getInstance(final String classname, final Class<T> interfaceClazz) { if (classname == null) { throw new IllegalArgumentException("classname is null"); } if (interfaceClazz == null) { throw new IllegalArgumentException("interfaceClazz is null"); } try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = Util.class.getClassLoader(); } final Class<?> clazz = classLoader.loadClass(classname); if (!interfaceClazz.isAssignableFrom(clazz)) { throw new RuntimeException("Class " + classname + " doesn't implement " + interfaceClazz); } return clazz.asSubclass(interfaceClazz).newInstance(); } catch (final ClassNotFoundException e) { throw new RuntimeException("Unable to instantiate '" + classname + "'", e); } catch (final InstantiationException e) { throw new RuntimeException("Unable to instantiate '" + classname + "'", e); } catch (final IllegalAccessException e) { throw new RuntimeException("Unable to instantiate '" + classname + "'", e); } } public static String changeFileExtension(final String filename, final String extension) { final int idx = filename.lastIndexOf("."); final StringBuilder sb = new StringBuilder(); if (idx > 0) { sb.append(filename.substring(0, idx)); } else {
sb.append(filename); } if (extension == null || extension.trim().length() == 0) { return sb.toString(); } sb.append(".").append(extension.trim()); return sb.toString(); } /** * * @param filename * @return file extension or null */ public static String getFileExtension(final String filename) { final int idx = filename.lastIndexOf("."); if (idx > 0) { return filename.substring(idx + 1); } return null; } public static void close(final Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (final IOException e) { e.printStackTrace(); } } public static String toString(final InputStream in) { return new String(toByteArray(in), StandardCharsets.UTF_8); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\util\Util.java
1
请完成以下Java代码
public abstract class OpenFormContextMenuAction extends AbstractContextMenuAction { private final int _adFormId; private I_AD_Form _adForm; private boolean _adFormLoaded = false; public OpenFormContextMenuAction(final int adFormId) { super(); this._adFormId = adFormId; } @Override public final String getName() { final I_AD_Form form = getAD_Form(); if (form == null) { return "-"; } return form.getName(); } @Override public final String getTitle() { return getName(); } @Override public final String getIcon() { return null; } @Override public final boolean isAvailable() { final I_AD_Form form = getAD_Form(); return form != null; } @Override public final boolean isRunnable() { final I_AD_Form form = getAD_Form(); if (form == null) { return false; } if (!isFormRunnable()) { return false; } return true; } /** * Check if the form is available and shall be opened in current context. * * To be implemented in extending class. * * @return true if form is available and it shall be opened. */ protected boolean isFormRunnable() { // nothing at this level return true; } @Override public final void run() { final FormFrame formFrame = AEnv.createForm(getAD_Form()); if (formFrame == null) { return; } customizeBeforeOpen(formFrame); AEnv.showCenterWindow(getCallingFrame(), formFrame); } protected void customizeBeforeOpen(final FormFrame formFrame) { // nothing on this level } /** @return the {@link Frame} in which this action was executed or <code>null</code> if not available. */ protected final Frame getCallingFrame()
{ final GridField gridField = getContext().getEditor().getField(); if (gridField == null) { return null; } final int windowNo = gridField.getWindowNo(); final Frame frame = Env.getWindow(windowNo); return frame; } protected final int getAD_Form_ID() { return _adFormId; } private final synchronized I_AD_Form getAD_Form() { if (!_adFormLoaded) { _adForm = retrieveAD_Form(); _adFormLoaded = true; } return _adForm; } private final I_AD_Form retrieveAD_Form() { final IContextMenuActionContext context = getContext(); Check.assumeNotNull(context, "context not null"); final Properties ctx = context.getCtx(); // Check if user has access to Payment Allocation form final int adFormId = getAD_Form_ID(); final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId); if (formAccess == null || !formAccess) { return null; } // Retrieve the form final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None); // Translate it to user's language final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class); return formTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java
1
请完成以下Java代码
public class X_PP_Order_SourceHU extends org.compiere.model.PO implements I_PP_Order_SourceHU, org.compiere.model.I_Persistent { private static final long serialVersionUID = 890056825L; /** Standard Constructor */ public X_PP_Order_SourceHU (final Properties ctx, final int PP_Order_SourceHU_ID, @Nullable final String trxName) { super (ctx, PP_Order_SourceHU_ID, trxName); } /** Load Constructor */ public X_PP_Order_SourceHU (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public org.eevolution.model.I_PP_Order getPP_Order() {
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class); } @Override public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setPP_Order_SourceHU_ID (final int PP_Order_SourceHU_ID) { if (PP_Order_SourceHU_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_SourceHU_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_SourceHU_ID, PP_Order_SourceHU_ID); } @Override public int getPP_Order_SourceHU_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_SourceHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_SourceHU.java
1
请完成以下Spring Boot application配置
server: port: 9090 servlet: session: cookie: name: SSO-SESSIONID # 自定义 Session 的 Cookie 名字,防止冲突。冲突后,会导致 SSO 登陆失败。 security: oauth2: # OAuth2 Client 配置,对应 OAuth2ClientProperties 类 client: client-id: clientapp client-secret: 112233 user-authorization-uri: http://127.0.0.1:8080/oauth/authorize # 获取用户的授权码地址 access-token-uri: http://127.0.0.1:808
0/oauth/token # 获取访问令牌的地址 # OAuth2 Resource 配置,对应 ResourceServerProperties 类 resource: token-info-uri: http://127.0.0.1:8080/oauth/check_token # 校验访问令牌是否有效的地址
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo21-resource-server-on-sso\src\main\resources\application.yml
2
请完成以下Java代码
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) { this.encodeHashAsBase64 = encodeHashAsBase64; } @Override protected String encodeNonNullPassword(String rawPassword) { byte[] salt = this.saltGenerator.generateKey(); byte[] encoded = encodedNonNullPassword(rawPassword, salt); return encodedNonNullPassword(encoded); } private String encodedNonNullPassword(byte[] bytes) { if (this.encodeHashAsBase64) { return Base64.getEncoder().encodeToString(bytes); } return String.valueOf(Hex.encode(bytes)); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { byte[] digested = decode(encodedPassword); byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return MessageDigest.isEqual(digested, encodedNonNullPassword(rawPassword, salt)); } private byte[] decode(String encodedBytes) { if (this.encodeHashAsBase64) { return Base64.getDecoder().decode(encodedBytes); }
return Hex.decode(encodedBytes); } private byte[] encodedNonNullPassword(CharSequence rawPassword, byte[] salt) { try { PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), EncodingUtils.concatenate(salt, this.secret), this.iterations, this.hashWidth); SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm); return EncodingUtils.concatenate(salt, skf.generateSecret(spec).getEncoded()); } catch (GeneralSecurityException ex) { throw new IllegalStateException("Could not create hash", ex); } } /** * The Algorithm used for creating the {@link SecretKeyFactory} * * @since 5.0 */ public enum SecretKeyFactoryAlgorithm { PBKDF2WithHmacSHA1, PBKDF2WithHmacSHA256, PBKDF2WithHmacSHA512 } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Pbkdf2PasswordEncoder.java
1
请完成以下Java代码
public class CaseInsensitiveWorkarounds { private String src; private String dest; private Pattern pattern; public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); } @Setup public void setup() { src = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; dest = "eiusmod"; pattern = Pattern.compile(Pattern.quote(dest), Pattern.CASE_INSENSITIVE); } // toLowerCase() and contains() @Benchmark public boolean lowerCaseContains() { return src.toLowerCase() .contains(dest.toLowerCase()); } // matches() with Regular Expressions @Benchmark public boolean matchesRegularExpression() { return src.matches("(?i).*" + dest + ".*"); } public boolean processRegionMatches(String localSrc, String localDest) { for (int i = localSrc.length() - localDest.length(); i >= 0; i--) if (localSrc.regionMatches(true, i, localDest, 0, localDest.length())) return true; return false; } // String regionMatches()
@Benchmark public boolean regionMatches() { return processRegionMatches(src, dest); } // Pattern CASE_INSENSITIVE with regexp @Benchmark public boolean patternCaseInsensitiveRegexp() { return pattern.matcher(src) .find(); } // Apache Commons StringUtils containsIgnoreCase @Benchmark public boolean apacheCommonsStringUtils() { return org.apache.commons.lang3.StringUtils.containsIgnoreCase(src, dest); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-2\src\main\java\com\baeldung\contains\CaseInsensitiveWorkarounds.java
1
请完成以下Java代码
public final class BuilderHelper { private static ObjectMapper om; static { om = new ObjectMapper(new YAMLFactory()); } private BuilderHelper(){} public static <T extends CustomResource<?,?>> ObjectMetaBuilder fromPrimary(T primary, String component) { return new ObjectMetaBuilder() .withNamespace(primary.getMetadata().getNamespace()) .withManagedFields((List<ManagedFieldsEntry>)null) .addToLabels("component", component) .addToLabels("name", primary.getMetadata().getName()) .withName(primary.getMetadata().getName() + "-" + component) .addToLabels("ManagedBy", Constants.OPERATOR_NAME); } public static <T> T loadTemplate(Class<T> clazz, String resource) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if ( cl == null ) {
cl = BuilderHelper.class.getClassLoader(); } try (InputStream is = cl.getResourceAsStream(resource)){ return loadTemplate(clazz, is); } catch(IOException ioe) { throw new RuntimeException("Unable to load classpath resource '" + resource + "': " + ioe.getMessage()); } } public static <T> T loadTemplate(Class<T> clazz, InputStream is) throws IOException{ return om.readValue(is, clazz); } }
repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\BuilderHelper.java
1
请完成以下Java代码
public T parameter(String name, Object value) { parameters.put(name, value); return (T) this; } protected Map<String, Object> generateParameterMap() { Map<String, Object> parameterMap = new HashMap<>(parameters); parameterMap.put("sql", sqlStatement); parameterMap.put("resultType", resultType.toString()); parameterMap.put("firstResult", firstResult); parameterMap.put("maxResults", maxResults); parameterMap.put("needsPaging", firstResult >= 0); String orderBy = (String) parameterMap.get("orderBy"); if (orderBy != null && !"".equals(orderBy)) { orderBy = "RES." + orderBy; } else { orderBy = "RES.ID_ asc"; } parameterMap.put("orderBy", "order by " + orderBy); parameterMap.put("orderByForWindow", "order by " + orderBy); parameterMap.put("orderByColumns", orderBy);
int firstRow = firstResult + 1; parameterMap.put("firstRow", firstRow); int lastRow = 0; if (maxResults == Integer.MAX_VALUE) { lastRow = maxResults; } else { lastRow = firstResult + maxResults + 1; } parameterMap.put("lastRow", lastRow); return parameterMap; } public Map<String, Object> getParameters() { return parameters; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\BaseNativeQuery.java
1
请完成以下Java代码
public class SbomEndpointWebExtension { private final SbomEndpoint sbomEndpoint; private final SbomProperties properties; private final Map<String, SbomType> detectedMediaTypeCache = new ConcurrentHashMap<>(); public SbomEndpointWebExtension(SbomEndpoint sbomEndpoint, SbomProperties properties) { this.sbomEndpoint = sbomEndpoint; this.properties = properties; } @ReadOperation WebEndpointResponse<Resource> sbom(@Selector String id) { Resource resource = this.sbomEndpoint.sbom(id); if (resource == null) { return new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } MimeType type = getMediaType(id, resource); return (type != null) ? new WebEndpointResponse<>(resource, type) : new WebEndpointResponse<>(resource); } private @Nullable MimeType getMediaType(String id, Resource resource) { if (SbomEndpoint.APPLICATION_SBOM_ID.equals(id) && this.properties.getApplication().getMediaType() != null) { return this.properties.getApplication().getMediaType(); } Sbom sbomProperties = this.properties.getAdditional().get(id); if (sbomProperties != null && sbomProperties.getMediaType() != null) { return sbomProperties.getMediaType(); } return this.detectedMediaTypeCache.computeIfAbsent(id, (ignored) -> { try { return detectSbomType(resource); } catch (IOException ex) { throw new UncheckedIOException("Failed to detect type of resource '%s'".formatted(resource), ex); } }).getMediaType(); } private SbomType detectSbomType(Resource resource) throws IOException { String content = resource.getContentAsString(StandardCharsets.UTF_8); for (SbomType candidate : SbomType.values()) { if (candidate.matches(content)) { return candidate; } } return SbomType.UNKNOWN; } enum SbomType { CYCLONE_DX(MimeType.valueOf("application/vnd.cyclonedx+json")) { @Override boolean matches(String content) { return content.replaceAll("\\s", "").contains("\"bomFormat\":\"CycloneDX\""); } }, SPDX(MimeType.valueOf("application/spdx+json")) { @Override
boolean matches(String content) { return content.contains("\"spdxVersion\""); } }, SYFT(MimeType.valueOf("application/vnd.syft+json")) { @Override boolean matches(String content) { return content.contains("\"FoundBy\"") || content.contains("\"foundBy\""); } }, UNKNOWN(null) { @Override boolean matches(String content) { return false; } }; private final @Nullable MimeType mediaType; SbomType(@Nullable MimeType mediaType) { this.mediaType = mediaType; } @Nullable MimeType getMediaType() { return this.mediaType; } abstract boolean matches(String content); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\sbom\SbomEndpointWebExtension.java
1
请完成以下Java代码
public String getDocument() { return this.document; } @Override public @Nullable String getOperationName() { return this.operationName; } @Override public Map<String, Object> getVariables() { return this.variables; } @Override public Map<String, Object> getExtensions() { return this.extensions; } @Override public Map<String, Object> toMap() { Map<String, Object> map = new LinkedHashMap<>(3); map.put(QUERY_KEY, getDocument()); if (getOperationName() != null) { map.put(OPERATION_NAME_KEY, getOperationName()); } if (!CollectionUtils.isEmpty(getVariables())) { map.put(VARIABLES_KEY, new LinkedHashMap<>(getVariables())); } if (!CollectionUtils.isEmpty(getExtensions())) { map.put(EXTENSIONS_KEY, new LinkedHashMap<>(getExtensions())); } return map; } @Override public boolean equals(Object o) { if (!(o instanceof DefaultGraphQlRequest)) { return false; } DefaultGraphQlRequest other = (DefaultGraphQlRequest) o; return (getDocument().equals(other.getDocument()) && ObjectUtils.nullSafeEquals(getOperationName(), other.getOperationName()) &&
ObjectUtils.nullSafeEquals(getVariables(), other.getVariables()) && ObjectUtils.nullSafeEquals(getExtensions(), other.getExtensions())); } @Override public int hashCode() { return this.document.hashCode() + 31 * ObjectUtils.nullSafeHashCode(this.operationName) + 31 * this.variables.hashCode() + 31 * this.extensions.hashCode(); } @Override public String toString() { return "document='" + getDocument() + "'" + ((getOperationName() != null) ? ", operationName='" + getOperationName() + "'" : "") + (!CollectionUtils.isEmpty(getVariables()) ? ", variables=" + getVariables() : "" + (!CollectionUtils.isEmpty(getExtensions()) ? ", extensions=" + getExtensions() : "")); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\DefaultGraphQlRequest.java
1
请完成以下Java代码
public Map<String, Double> predict(Document document) { AbstractModel model = getModel(); if (model == null) { throw new IllegalStateException("未训练模型!无法执行预测!"); } if (document == null) { throw new IllegalArgumentException("参数 text == null"); } double[] probs = categorize(document); Map<String, Double> scoreMap = new TreeMap<String, Double>(); for (int i = 0; i < probs.length; i++) { scoreMap.put(model.catalog[i], probs[i]); } return scoreMap; } @Override public int label(Document document) throws IllegalArgumentException, IllegalStateException { AbstractModel model = getModel(); if (model == null) { throw new IllegalStateException("未训练模型!无法执行预测!"); } if (document == null) {
throw new IllegalArgumentException("参数 text == null"); } double[] probs = categorize(document); double max = Double.NEGATIVE_INFINITY; int best = -1; for (int i = 0; i < probs.length; i++) { if (probs[i] > max) { max = probs[i]; best = i; } } return best; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\classifiers\AbstractClassifier.java
1
请在Spring Boot框架中完成以下Java代码
protected Step readBooks(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("readBooks", jobRepository) .<Book, Book> chunk(2, transactionManager) .reader(reader()) .writer(writer()) .build(); } @Bean public FlatFileItemReader<Book> reader() { return new FlatFileItemReaderBuilder<Book>().name("bookItemReader") .resource(new ClassPathResource("books.csv")) .delimited() .names(new String[] { "id", "name" }) .fieldSetMapper(new BeanWrapperFieldSetMapper<>() { { setTargetType(Book.class); } }) .build(); }
@Bean public ItemWriter<Book> writer() { return items -> { logger.debug("writer..." + items.size()); for (Book item : items) { logger.debug(item.toString()); } }; } public AtomicInteger getBatchRunCounter() { return batchRunCounter; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batchscheduler\SpringBatchScheduler.java
2
请完成以下Spring Boot application配置
server.port=8088 # basic configuration spring.redis.database=0 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=123456 # pools configuration spring.redis.jedis.pool.max-active=8 spring.redis.j
edis.pool.max-idle=8 spring.redis.jedis.pool.max-wait=-1ms spring.redis.jedis.pool.min-idle=0
repos\springboot-demo-master\oatuth2\src\main\resources\application.properties
2
请完成以下Java代码
public class PickingSlotQueuesSummary { public static final PickingSlotQueuesSummary EMPTY = new PickingSlotQueuesSummary(ImmutableList.of()); private final ImmutableMap<PickingSlotId, PickingSlotQueueSummary> queuesById; private PickingSlotQueuesSummary(@NonNull final Collection<PickingSlotQueueSummary> queues) { this.queuesById = Maps.uniqueIndex(queues, PickingSlotQueueSummary::getPickingSlotId); } public static PickingSlotQueuesSummary ofList(@NonNull final List<PickingSlotQueueSummary> queues) {return queues.isEmpty() ? EMPTY : new PickingSlotQueuesSummary(queues);} public static Collector<PickingSlotQueueSummary, ?, PickingSlotQueuesSummary> collect() {return GuavaCollectors.collectUsingListAccumulator(PickingSlotQueuesSummary::ofList);} public boolean isEmpty() {return queuesById.isEmpty();} public Set<PickingSlotId> getPickingSlotIds() {return queuesById.keySet();} public OptionalInt getCountHUs(@NonNull final PickingSlotId pickingSlotId) { final PickingSlotQueueSummary queue = queuesById.get(pickingSlotId); return queue != null ? OptionalInt.of(queue.getCountHUs()) : OptionalInt.empty(); } public OptionalInt getCountHUs(@NonNull final Set<PickingSlotId> pickingSlotIds) { if (pickingSlotIds.isEmpty()) { return OptionalInt.of(0); }
int countHUs = 0; for (final PickingSlotId pickingSlotId : pickingSlotIds) { final PickingSlotQueueSummary queue = queuesById.get(pickingSlotId); if (queue == null) { return OptionalInt.empty(); } countHUs += queue.getCountHUs(); } return OptionalInt.of(countHUs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotQueuesSummary.java
1
请完成以下Java代码
protected OrgPermissions createPermissionsInstance() { return new OrgPermissions(this); } private AdTreeId getOrgTreeId() { return orgTreeId; } /** * Load Org Access Add Tree to List */ public Builder addPermissionRecursively(final OrgPermission oa) { if (hasPermission(oa)) { return this; } addPermission(oa, CollisionPolicy.Override); // Do we look for trees? final AdTreeId adTreeOrgId = getOrgTreeId(); if (adTreeOrgId == null) { return this; } final OrgResource orgResource = oa.getResource(); if (!orgResource.isGroupingOrg()) { return this; } // Summary Org - Get Dependents final MTree_Base tree = MTree_Base.getById(adTreeOrgId); final String sql = "SELECT "
+ " AD_Client_ID" + ", AD_Org_ID" + ", " + I_AD_Org.COLUMNNAME_IsSummary + " FROM AD_Org " + " WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName() + " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')"; final Object[] sqlParams = new Object[] { tree.getAD_Tree_ID(), orgResource.getOrgId() }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); while (rs.next()) { final ClientId clientId = ClientId.ofRepoId(rs.getInt(1)); final OrgId orgId = OrgId.ofRepoId(rs.getInt(2)); final boolean isGroupingOrg = StringUtils.toBoolean(rs.getString(3)); final OrgResource resource = OrgResource.of(clientId, orgId, isGroupingOrg); final OrgPermission childOrgPermission = oa.copyWithResource(resource); addPermissionRecursively(childOrgPermission); } return this; } catch (final SQLException e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermissions.java
1
请完成以下Java代码
public void refreshFromSource(MViewMetadata mdata, PO sourcePO, RefreshMode[] refreshModes) { final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class); final I_AD_Table_MView mview = mviewBL.fetchForTableName(sourcePO.getCtx(), mdata.getTargetTableName(), sourcePO.get_TrxName()); boolean staled = true; for (RefreshMode refreshMode : refreshModes) { if (mviewBL.isAllowRefresh(mview, sourcePO, refreshMode)) { mviewBL.refresh(mview, sourcePO, refreshMode, sourcePO.get_TrxName()); staled = false; break; } } // // We should do a complete refresh => marking mview as staled if (staled) { mviewBL.setStaled(mview); } } private boolean addMView(I_AD_Table_MView mview, boolean invalidateIfNecessary) {
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class); MViewMetadata mdata = mviewBL.getMetadata(mview); if (mdata == null) { // no metadata found => IGNORE if (invalidateIfNecessary) { mview.setIsValid(false); InterfaceWrapperHelper.save(mview); } return false; } for (String sourceTableName : mdata.getSourceTables()) { engine.addModelChange(sourceTableName, this); } registeredTables.add(mview.getAD_Table_ID()); return true; } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewModelValidator.java
1
请完成以下Java代码
public void setPrescriptionRequestUpdateAt (final @Nullable java.sql.Timestamp PrescriptionRequestUpdateAt) { set_Value (COLUMNNAME_PrescriptionRequestUpdateAt, PrescriptionRequestUpdateAt); } @Override public java.sql.Timestamp getPrescriptionRequestUpdateAt() { return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestUpdateAt); } /** * PrescriptionType AD_Reference_ID=541296 * Reference name: Rezepttyp */ public static final int PRESCRIPTIONTYPE_AD_Reference_ID=541296; /** Arzneimittel = 0 */ public static final String PRESCRIPTIONTYPE_Arzneimittel = "0"; /** Verbandstoffe = 1 */ public static final String PRESCRIPTIONTYPE_Verbandstoffe = "1"; /** BtM-Rezept = 2 */ public static final String PRESCRIPTIONTYPE_BtM_Rezept = "2"; /** Pflegehilfsmittel = 3 */ public static final String PRESCRIPTIONTYPE_Pflegehilfsmittel = "3"; /** Hilfsmittel zum Verbrauch bestimmt = 4 */ public static final String PRESCRIPTIONTYPE_HilfsmittelZumVerbrauchBestimmt = "4"; /** Hilfsmittel zum Gebrauch bestimmt = 5 */ public static final String PRESCRIPTIONTYPE_HilfsmittelZumGebrauchBestimmt = "5"; @Override public void setPrescriptionType (final @Nullable java.lang.String PrescriptionType) { set_Value (COLUMNNAME_PrescriptionType, PrescriptionType); } @Override public java.lang.String getPrescriptionType() { return get_ValueAsString(COLUMNNAME_PrescriptionType); }
@Override public void setStartDate (final @Nullable java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } @Override public java.sql.Timestamp getStartDate() { return get_ValueAsTimestamp(COLUMNNAME_StartDate); } @Override public void setTherapyTypeIds (final @Nullable java.lang.String TherapyTypeIds) { set_Value (COLUMNNAME_TherapyTypeIds, TherapyTypeIds); } @Override public java.lang.String getTherapyTypeIds() { return get_ValueAsString(COLUMNNAME_TherapyTypeIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_PrescriptionRequest.java
1
请完成以下Java代码
public boolean isEnabled() { if (!MigrationScriptFileLoggerHolder.isEnabled()) { return false; } if (!Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_Enabled, SYSCONFIG_Enabled_Default)) { return false; } return true; } @Override public boolean isGenerateComments() { return true; } @Override public I_AD_Migration getMigration(String key) { final Properties ctx = Env.getCtx(); final Integer migrationId = migrationsMap.get(key); if (migrationId == null || migrationId <= 0) { return null; }
I_AD_Migration migration = migrationsCache.get(migrationId); if (migration != null) { return migration; } // We have the ID in out map, but cache expired, which means that maybe somebody deleted this record // Trying to reload migration = Services.get(IMigrationDAO.class).retrieveMigrationOrNull(ctx, migrationId); if (migration != null) { putMigration(key, migration); return migration; } return migration; } @Override public void putMigration(String key, I_AD_Migration migration) { migrationsMap.put(key, migration.getAD_Migration_ID()); migrationsCache.put(migration.getAD_Migration_ID(), migration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\SessionMigrationLoggerContext.java
1
请完成以下Java代码
public final class NullDocLineCopyHandler<LT> implements IDocLineCopyHandler<LT> { /* package */final static NullDocLineCopyHandler<?> instance = new NullDocLineCopyHandler<>(); private NullDocLineCopyHandler() { } /** * Does nothing. */ @Override public void copyPreliminaryValues(LT from, LT to) { // does nothing } /** * Does nothing.
*/ @Override public void copyValues(LT from, LT to) { // does nothing } /** * Throws an {@link UnsupportedOperationException}. */ @Override public Class<LT> getSupportedItemsClass() { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\NullDocLineCopyHandler.java
1
请完成以下Java代码
public BPartnerLocationId getBPartnerLocationId(@Nullable final BPartnerId bPartnerId, @NonNull final Object model) { final Integer locationId = InterfaceWrapperHelper.getValueOrNull(model, COLUMNNAME_C_BPartner_Location_ID); return BPartnerLocationId.ofRepoIdOrNull(bPartnerId, locationId); } public Optional<Language> getBPartnerLanguage(@NonNull final I_C_BPartner bpartner) { return bpartnerBL.getLanguage(bpartner); } public BPartnerPrintFormatMap getBPartnerPrintFormats(final BPartnerId bpartnerId) { return bpartnerBL.getPrintFormats(bpartnerId); } @NonNull public DefaultPrintFormats getDefaultPrintFormats(@NonNull final ClientId clientId) { return defaultPrintFormatsRepository.getByClientId(clientId); } @NonNull public AdProcessId getReportProcessIdByPrintFormatId(@NonNull final PrintFormatId printFormatId) { return getReportProcessIdByPrintFormatIdIfExists(printFormatId).get(); } @NonNull public ExplainedOptional<AdProcessId> getReportProcessIdByPrintFormatIdIfExists(@NonNull final PrintFormatId printFormatId) { final PrintFormat printFormat = printFormatRepository.getById(printFormatId); final AdProcessId reportProcessId = printFormat.getReportProcessId(); return reportProcessId != null ? ExplainedOptional.of(reportProcessId)
: ExplainedOptional.emptyBecause("No report process defined by " + printFormat); } @NonNull public I_C_DocType getDocTypeById(@NonNull final DocTypeId docTypeId) { return docTypeDAO.getById(docTypeId); } public PrintCopies getDocumentCopies( @Nullable final I_C_DocType docType, @Nullable final BPPrintFormatQuery bpPrintFormatQuery) { final BPPrintFormat bpPrintFormat = bpPrintFormatQuery == null ? null : bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery); if(bpPrintFormat == null) { return getDocumentCopies(docType); } return bpPrintFormat.getPrintCopies(); } private static PrintCopies getDocumentCopies(@Nullable final I_C_DocType docType) { return docType != null && !InterfaceWrapperHelper.isNull(docType, I_C_DocType.COLUMNNAME_DocumentCopies) ? PrintCopies.ofInt(docType.getDocumentCopies()) : PrintCopies.ONE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportAdvisorUtil.java
1
请在Spring Boot框架中完成以下Java代码
private Map<InboundEMailConfigId, InboundEMailConfig> getAllConfigsIndexById() { return configsCache.getOrLoad(0, this::retrieveAllConfigsIndexById); } private Map<InboundEMailConfigId, InboundEMailConfig> retrieveAllConfigsIndexById() { return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_InboundMailConfig.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(InboundEMailConfigRepository::toInboundEMailConfig) .collect(GuavaCollectors.toImmutableMapByKey(InboundEMailConfig::getId)); } private static InboundEMailConfig toInboundEMailConfig(final I_C_InboundMailConfig record) {
return InboundEMailConfig.builder() .id(InboundEMailConfigId.ofRepoId(record.getC_InboundMailConfig_ID())) .protocol(InboundEMailProtocol.forCode(record.getProtocol())) .host(record.getHost()) .port(record.getPort()) .folder(record.getFolder()) .username(record.getUserName()) .password(record.getPassword()) .debugProtocol(record.isDebugProtocol()) .adClientId(ClientId.ofRepoId(record.getAD_Client_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .requestTypeId(RequestTypeId.ofRepoIdOrNull(record.getR_RequestType_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\config\InboundEMailConfigRepository.java
2
请完成以下Java代码
public void setAndOr (String AndOr) { set_Value (COLUMNNAME_AndOr, AndOr); } /** Get And/Or. @return Logical operation: AND or OR */ public String getAndOr () { return (String)get_Value(COLUMNNAME_AndOr); } /** Set Find_ID. @param Find_ID Find_ID */ public void setFind_ID (BigDecimal Find_ID) { set_Value (COLUMNNAME_Find_ID, Find_ID); } /** Get Find_ID. @return Find_ID */ public BigDecimal getFind_ID () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Find_ID); if (bd == null) return Env.ZERO; return bd; } /** Operation AD_Reference_ID=205 */ public static final int OPERATION_AD_Reference_ID=205; /** = = == */ public static final String OPERATION_Eq = "=="; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** > = >> */ public static final String OPERATION_Gt = ">>"; /** < = << */ public static final String OPERATION_Le = "<<"; /** ~ = ~~ */ public static final String OPERATION_Like = "~~"; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** |<x>| = AB */ public static final String OPERATION_X = "AB"; /** sql = SQ */ public static final String OPERATION_Sql = "SQ"; /** != = != */ public static final String OPERATION_NotEq = "!="; /** Set Operation. @param Operation Compare Operation */
public void setOperation (String Operation) { set_Value (COLUMNNAME_Operation, Operation); } /** Get Operation. @return Compare Operation */ public String getOperation () { return (String)get_Value(COLUMNNAME_Operation); } /** 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); } /** Set Value To. @param Value2 Value To */ public void setValue2 (String Value2) { set_Value (COLUMNNAME_Value2, Value2); } /** Get Value To. @return Value To */ public String getValue2 () { return (String)get_Value(COLUMNNAME_Value2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Find.java
1
请完成以下Spring Boot application配置
server.port=8080 spring.datasource.url=jdbc:h2:mem:test-database spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=test-username spring.datasource.passwo
rd=test-password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
repos\tutorials-master\spring-security-modules\spring-security-compromised-password\src\main\resources\application.properties
2
请完成以下Java代码
public class TrackFilter implements Filter { Logger logger = TrackLoggerFactory.getLogger(TrackFilter.class); @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 为每个请求设置唯一标示到MDC容器中 setMdc(request); try { // 执行后续操作 chain.doFilter(request, response); } finally { try { MDC.remove(MdcConstant.SESSION_KEY); MDC.remove(MdcConstant.REQUEST_KEY); } catch (Exception e) { logger.warn(e.getMessage(), e); }
} } @Override public void init(FilterConfig arg0) throws ServletException { } /** * 为每个请求设置唯一标示到MDC容器中 */ private void setMdc(ServletRequest request) { try { // 设置SessionId String requestId = UUID.randomUUID().toString().replace("-", ""); MDC.put(MdcConstant.SESSION_KEY, "userId"); MDC.put(MdcConstant.REQUEST_KEY, requestId); } catch (Exception e) { logger.warn(e.getMessage(), e); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\interceptors\TrackFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtTokenProvider jwtTokenProvider; @Override protected void configure(HttpSecurity http) throws Exception { // Disable CSRF (cross site request forgery) http.csrf().disable(); // No session will be created or used by spring security http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Entry points http.authorizeRequests()//0 .antMatchers("/users/signin").permitAll()// .antMatchers("/users/signup").permitAll()// .antMatchers("/h2-console/**/**").permitAll() // Disallow everything else.. .anyRequest().authenticated(); // If a user try to access a resource without having enough permissions http.exceptionHandling().accessDeniedPage("/login"); // Apply JWT http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider)); // Optional, if you want to test the API from a browser // http.httpBasic(); }
@Override public void configure(WebSecurity web) throws Exception { // Allow swagger to be accessed without authentication web.ignoring().antMatchers("/v2/api-docs")// .antMatchers("/swagger-resources/**")// .antMatchers("/swagger-ui.html")// .antMatchers("/configuration/**")// .antMatchers("/webjars/**")// .antMatchers("/public") // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production) .and().ignoring().antMatchers("/h2-console/**/**"); ; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\security\WebSecurityConfig.java
2
请完成以下Java代码
public class LinesWriter implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); private List<Line> lines; private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { ExecutionContext executionContext = stepExecution .getJobExecution() .getExecutionContext(); this.lines = (List<Line>) executionContext.get("lines"); fu = new FileUtils("output.csv"); logger.debug("Lines Writer initialized."); }
@Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { for (Line line : lines) { fu.writeLine(line); logger.debug("Wrote line " + line.toString()); } return RepeatStatus.FINISHED; } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeWriter(); logger.debug("Lines Writer ended."); return ExitStatus.COMPLETED; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\tasklets\LinesWriter.java
1