instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class Person implements CouchbaseEntity { private String id; private String type; private String name; private String homeTown; Person() { } public Person(Builder b) { this.id = b.id; this.type = b.type; this.name = b.name; this.homeTown = b.homeTown; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHomeTown() { return homeTown; } public void setHomeTown(String homeTown) { this.homeTown = homeTown; } public static class Builder { private String id; private String type; private String name; private String homeTown;
public static Builder newInstance() { return new Builder(); } public Person build() { return new Person(this); } public Builder id(String id) { this.id = id; return this; } public Builder type(String type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder homeTown(String homeTown) { this.homeTown = homeTown; return this; } } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\async\person\Person.java
1
请完成以下Java代码
public int hashCode() { return hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ConstantLogicExpression other = (ConstantLogicExpression)obj; return value == other.value; } @Override public boolean isConstant() { return true; } @Override public boolean constantValue() { return value; } @Override public ILogicExpression toConstantExpression(final boolean constantValue) { if (constantValue != value) { throw new ExpressionCompileException("Cannot convert a constant expression to a constant expression of opposite value" + "\n Expression: " + this + "\n Target value: " + constantValue); } return this; } @Override public String getExpressionString() { return expressionString; }
@Override public Set<CtxName> getParameters() { return ImmutableSet.of(); } @Override public String toString() { return toStringValue; } @Override public String getFormatedExpressionString() { return expressionString; } @Override public Boolean evaluate(final Evaluatee ctx, final boolean ignoreUnparsable) { return value; } @Override public Boolean evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) { return value; } @Override public LogicExpressionResult evaluateToResult(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { return value ? LogicExpressionResult.TRUE : LogicExpressionResult.FALSE; } @Override public ILogicExpression evaluatePartial(final Evaluatee ctx) { return this; } @Override public ILogicExpression negate() {return of(!value);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ConstantLogicExpression.java
1
请完成以下Java代码
public boolean isActiva() { return ACCOUNTTYPE_Asset.equals(getAccountType()); } // isActive /** * Is this a Passiva Account * * @return boolean */ public boolean isPassiva() { String accountType = getAccountType(); return (ACCOUNTTYPE_Liability.equals(accountType) || ACCOUNTTYPE_OwnerSEquity.equals(accountType)); } // isPassiva @Override public String toString() { return getValue() + " - " + getName(); } /** * Extended String Representation * * @return info */ public String toStringX() { return "MElementValue[" + get_ID() + "," + getValue() + " - " + getName() + "]"; } @Override protected boolean beforeSave(boolean newRecord) { // // Transform to summary level account if (!newRecord && isSummary() && is_ValueChanged(COLUMNNAME_IsSummary)) { // // Check if we have accounting facts boolean match = new Query(getCtx(), I_Fact_Acct.Table_Name, I_Fact_Acct.COLUMNNAME_Account_ID + "=?", ITrx.TRXNAME_ThreadInherited) .setParameters(getC_ElementValue_ID()) .anyMatch(); if (match) { throw new AdempiereException("@AlreadyPostedTo@"); } // // Check Valid Combinations - teo_sarca FR [ 1883533 ] String whereClause = MAccount.COLUMNNAME_Account_ID + "=?"; POResultSet<MAccount> rs = new Query(getCtx(), MAccount.Table_Name, whereClause, ITrx.TRXNAME_ThreadInherited) .setParameters(getC_ElementValue_ID()) .scroll(); try { while (rs.hasNext()) { rs.next().deleteEx(true);
} } finally { DB.close(rs); } } return true; } // beforeSave @Override protected boolean afterSave(boolean newRecord, boolean success) { // Value/Name change if (!newRecord && (is_ValueChanged(COLUMNNAME_Value) || is_ValueChanged(COLUMNNAME_Name))) { MAccount.updateValueDescription(getCtx(), "Account_ID=" + getC_ElementValue_ID(), get_TrxName()); if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList1.getCode()))) { MAccount.updateValueDescription(getCtx(), "User1_ID=" + getC_ElementValue_ID(), get_TrxName()); } if ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.UserList2.getCode()))) { MAccount.updateValueDescription(getCtx(), "User2_ID=" + getC_ElementValue_ID(), get_TrxName()); } } return success; } // afterSave } // MElementValue
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MElementValue.java
1
请完成以下Java代码
private static class ResourcePatternResolverFactory { ResourcePatternResolver getResourcePatternResolver(AbstractApplicationContext applicationContext, @Nullable ResourceLoader resourceLoader) { ResourceLoader targetResourceLoader = (resourceLoader != null) ? resourceLoader : new ApplicationContextResourceLoader(applicationContext::getProtocolResolvers); return new PathMatchingResourcePatternResolver(targetResourceLoader); } } /** * {@link ResourcePatternResolverFactory} to be used when the classloader can access * {@link WebApplicationContext}. */ private static final class WebResourcePatternResolverFactory extends ResourcePatternResolverFactory { @Override public ResourcePatternResolver getResourcePatternResolver(AbstractApplicationContext applicationContext, @Nullable ResourceLoader resourceLoader) { if (applicationContext instanceof WebApplicationContext) { return getServletContextResourcePatternResolver(applicationContext, resourceLoader); } return super.getResourcePatternResolver(applicationContext, resourceLoader); } private ResourcePatternResolver getServletContextResourcePatternResolver( AbstractApplicationContext applicationContext, @Nullable ResourceLoader resourceLoader) { ResourceLoader targetResourceLoader = (resourceLoader != null) ? resourceLoader : new WebApplicationContextResourceLoader(applicationContext::getProtocolResolvers, (WebApplicationContext) applicationContext); return new ServletContextResourcePatternResolver(targetResourceLoader); } } private static class ApplicationContextResourceLoader extends DefaultResourceLoader { private final Supplier<Collection<ProtocolResolver>> protocolResolvers; ApplicationContextResourceLoader(Supplier<Collection<ProtocolResolver>> protocolResolvers) { super(null); this.protocolResolvers = protocolResolvers; } @Override public Collection<ProtocolResolver> getProtocolResolvers() { return this.protocolResolvers.get(); } }
/** * {@link ResourceLoader} that optionally supports {@link ServletContextResource * ServletContextResources}. */ private static class WebApplicationContextResourceLoader extends ApplicationContextResourceLoader { private final WebApplicationContext applicationContext; WebApplicationContextResourceLoader(Supplier<Collection<ProtocolResolver>> protocolResolvers, WebApplicationContext applicationContext) { super(protocolResolvers); this.applicationContext = applicationContext; } @Override protected Resource getResourceByPath(String path) { if (this.applicationContext.getServletContext() != null) { return new ServletContextResource(this.applicationContext.getServletContext(), path); } return super.getResourceByPath(path); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\ClassLoaderFilesResourcePatternResolver.java
1
请完成以下Java代码
public class ActivateAsyncPlanItemInstanceOperation extends AbstractChangePlanItemInstanceStateOperation { protected String entryCriterionId; public ActivateAsyncPlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity, String entryCriterionId) { super(commandContext, planItemInstanceEntity); this.entryCriterionId = entryCriterionId; } @Override public String getLifeCycleTransition() { return PlanItemTransition.ASYNC_ACTIVATE; } @Override public String getNewState() { return PlanItemInstanceState.ASYNC_ACTIVE; } @Override protected void internalExecute() { planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext)); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity); createAsyncJob((Task) planItemInstanceEntity.getPlanItem().getPlanItemDefinition()); } protected void createAsyncJob(Task task) { CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext); JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService(); JobEntity job = JobUtil.createJob(planItemInstanceEntity, task, AsyncActivatePlanItemInstanceJobHandler.TYPE, cmmnEngineConfiguration); job.setJobHandlerConfiguration(entryCriterionId);
jobService.createAsyncJob(job, task.isExclusive()); jobService.scheduleAsyncJob(job); if (cmmnEngineConfiguration.isLoggingSessionEnabled()) { CmmnLoggingSessionUtil.addAsyncActivityLoggingData("Created async job for " + planItemInstanceEntity.getPlanItemDefinitionId() + ", with job id " + job.getId(), CmmnLoggingSessionConstants.TYPE_SERVICE_TASK_ASYNC_JOB, job, planItemInstanceEntity.getPlanItemDefinition(), planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper()); } } @Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Async activate PlanItem] "); stringBuilder.append(planItem); if (entryCriterionId != null) { stringBuilder.append(" via entry criterion ").append(entryCriterionId); } return stringBuilder.toString(); } @Override public String getOperationName() { return "[Async activate plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ActivateAsyncPlanItemInstanceOperation.java
1
请完成以下Java代码
private static AmountSourceAndAcct extractAmountSourceAndAcct(@NonNull final FactLine factLine, boolean isDR) { return AmountSourceAndAcct.builder() .currencyAndRate(CurrencyAndRate.of(factLine.getCurrencyId(), factLine.getCurrencyRate())) .amtSource(isDR ? factLine.getAmtSourceDr() : factLine.getAmtSourceCr()) .amtAcct(isDR ? factLine.getAmtAcctDr() : factLine.getAmtAcctCr()) .build(); } @Value(staticConstructor = "of") private static class CurrencyAndRate { @NonNull CurrencyId currencyId; @NonNull BigDecimal currencyRate; private CurrencyAndRate(@NonNull final CurrencyId currencyId, @NonNull final BigDecimal currencyRate) { this.currencyId = currencyId; this.currencyRate = NumberUtils.stripTrailingDecimalZeros(currencyRate); } } @Value @Builder(toBuilder = true) private static class AmountSourceAndAcct { @NonNull CurrencyAndRate currencyAndRate; @NonNull BigDecimal amtSource; @NonNull BigDecimal amtAcct; public static AmountSourceAndAcct zero(@NonNull final CurrencyAndRate currencyAndRate) { return builder().currencyAndRate(currencyAndRate).amtSource(BigDecimal.ZERO).amtAcct(BigDecimal.ZERO).build(); } public boolean isZero() { return amtSource.signum() == 0 && amtAcct.signum() == 0; } public boolean isZeroAmtSource() { return amtSource.signum() == 0; } public AmountSourceAndAcct negate() { return isZero() ? this : toBuilder().amtSource(this.amtSource.negate()).amtAcct(this.amtAcct.negate()).build(); } public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other)
{ assertCurrencyAndRateMatching(other); if (other.isZero()) { return this; } else if (this.isZero()) { return other; } else { return toBuilder() .amtSource(this.amtSource.add(other.amtSource)) .amtAcct(this.amtAcct.add(other.amtAcct)) .build(); } } public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other) { return add(other.negate()); } private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other) { if (!Objects.equals(this.currencyAndRate, other.currencyAndRate)) { throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate); } } } } // Doc_Bank
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
1
请在Spring Boot框架中完成以下Java代码
public class LicenseCreatorController { @Autowired private LicenseCreatorService licenseCreatorService; /** * <p>项目名称: true-license-demo </p> * <p>文件名称: LicenseCreatorController.java </p> * <p>方法描述: 获取服务器硬件信息 </p> * <p>创建时间: 2020/10/10 13:39 </p> * * @param osName 系统名称 * @return com.example.demo.license.LicenseCheckModel * @author 方瑞冬 * @version 1.0 */ @GetMapping("/getServerInfos") public LicenseCheckModel getServerInfos(@RequestParam String osName) { return licenseCreatorService.getServerInfos(osName); }
/** * <p>项目名称: true-license-demo </p> * <p>文件名称: LicenseCreatorController.java </p> * <p>方法描述: 生成证书 </p> * <p>创建时间: 2020/10/10 13:42 </p> * * @param param 证书创建参数 * @return java.util.Map<java.lang.String, java.lang.Object> * @author 方瑞冬 * @version 1.0 */ @PostMapping("/generateLicense") public Map<String, Object> generateLicense(@RequestBody LicenseCreatorParam param) { return licenseCreatorService.generateLicense(param); } }
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\controller\LicenseCreatorController.java
2
请完成以下Java代码
public void reverseReturn(final de.metas.handlingunits.model.I_M_InOut returnInOut) { if (!returnsServiceFacade.isVendorReturn(returnInOut)) { return; // nothing to do } final String snapshotId = returnInOut.getSnapshot_UUID(); if (Check.isEmpty(snapshotId, true)) { throw new HUException("@NotFound@ @Snapshot_UUID@ (" + returnInOut + ")"); } final List<I_M_HU> hus = huAssignmentDAO.retrieveTopLevelHUsForModel(returnInOut); if (hus.isEmpty()) { // nothing to do. return; } final IContextAware context = InterfaceWrapperHelper.getContextAware(returnInOut); snapshotDAO.restoreHUs() .setContext(context) .setSnapshotId(snapshotId)
.setDateTrx(returnInOut.getMovementDate()) .setReferencedModel(returnInOut) .addModels(hus) .restoreFromSnapshot(); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE }) public void validateAttributesOnShipmentCompletion(final I_M_InOut shipment) { if (!shipment.isSOTrx()) { // nothing to do return; } huInOutBL.validateMandatoryOnShipmentAttributes(shipment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_InOut.java
1
请完成以下Java代码
public void setCode(final String code) { this.code = code; this.codeSet = true; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setName(final String name) { this.name = name; this.nameSet = true; } public void setName2(final String name2) { this.name2 = name2; this.name2Set = true; } public void setName3(final String name3) { this.name3 = name3; this.name3Set = true; } public void setCompanyName(final String companyName) { this.companyName = companyName; this.companyNameSet = true; } public void setLookupLabel(@Nullable final String lookupLabel) { this.lookupLabel = lookupLabel; this.lookupLabelSet = true; } public void setVendor(final Boolean vendor) { this.vendor = vendor; this.vendorSet = true; } public void setCustomer(final Boolean customer) { this.customer = customer; this.customerSet = true; } public void setParentId(final JsonMetasfreshId parentId) { this.parentId = parentId; this.parentIdSet = true; } public void setPhone(final String phone) { this.phone = phone; this.phoneSet = true; } public void setLanguage(final String language) { this.language = language; this.languageSet = true; }
public void setInvoiceRule(final JsonInvoiceRule invoiceRule) { this.invoiceRule = invoiceRule; this.invoiceRuleSet = true; } public void setPOInvoiceRule(final JsonInvoiceRule invoiceRule) { this.poInvoiceRule = invoiceRule; this.poInvoiceRuleSet = true; } public void setUrl(final String url) { this.url = url; this.urlSet = true; } public void setUrl2(final String url2) { this.url2 = url2; this.url2Set = true; } public void setUrl3(final String url3) { this.url3 = url3; this.url3Set = true; } public void setGroup(final String group) { this.group = group; this.groupSet = true; } public void setGlobalId(final String globalId) { this.globalId = globalId; this.globalIdset = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setVatId(final String vatId) { this.vatId = vatId; this.vatIdSet = true; } public void setMemo(final String memo) { this.memo = memo; this.memoIsSet = true; } public void setPriceListId(@Nullable final JsonMetasfreshId priceListId) { if (JsonMetasfreshId.toValue(priceListId) != null) { this.priceListId = priceListId; this.priceListIdSet = true; } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestBPartner.java
1
请在Spring Boot框架中完成以下Java代码
List<BeanReference> getProviders() { List<BeanReference> providers = new ArrayList<>(); if (this.anonymousProviderRef != null) { providers.add(this.anonymousProviderRef); } if (this.rememberMeProviderRef != null) { providers.add(this.rememberMeProviderRef); } if (this.x509ProviderRef != null) { providers.add(this.x509ProviderRef); } if (this.jeeProviderRef != null) { providers.add(this.jeeProviderRef); } if (this.oauth2LoginAuthenticationProviderRef != null) { providers.add(this.oauth2LoginAuthenticationProviderRef); } if (this.oauth2LoginOidcAuthenticationProviderRef != null) { providers.add(this.oauth2LoginOidcAuthenticationProviderRef); } if (this.authorizationCodeAuthenticationProviderRef != null) { providers.add(this.authorizationCodeAuthenticationProviderRef);
} providers.addAll(this.authenticationProviders); return providers; } private static class CsrfTokenHiddenInputFunction implements Function<HttpServletRequest, Map<String, String>> { @Override public Map<String, String> apply(HttpServletRequest request) { CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (token == null) { return Collections.emptyMap(); } return Collections.singletonMap(token.getParameterName(), token.getToken()); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\AuthenticationConfigBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public Future<User> findUser(Long id) { log.info("获取单个用户信息"); // return new AsyncResult<User>() { // @Override // public User invoke() { // return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id); // } // }; return null; } @HystrixCommand public List<User> findUserBatch(List<Long> ids) { log.info("批量获取用户信息,ids: " + ids); User[] users = restTemplate.getForObject("http://Server-Provider/user/users?ids={1}", User[].class, StringUtils.join(ids, ",")); return Arrays.asList(users); } public String getCacheKey(Long id) { return String.valueOf(id); } @CacheResult(cacheKeyMethod = "getCacheKey") @HystrixCommand(fallbackMethod = "getUserDefault", commandKey = "getUserById", groupKey = "userGroup", threadPoolKey = "getUserThread") public User getUser(Long id) { log.info("获取用户信息"); return restTemplate.getForObject("http://Server-Provider/user/{id}", User.class, id); } @HystrixCommand(fallbackMethod = "getUserDefault2") public User getUserDefault(Long id) { String a = null; // 测试服务降级 a.toString(); User user = new User(); user.setId(-1L); user.setUsername("defaultUser"); user.setPassword("123456"); return user; }
public User getUserDefault2(Long id, Throwable e) { System.out.println(e.getMessage()); User user = new User(); user.setId(-2L); user.setUsername("defaultUser2"); user.setPassword("123456"); return user; } public List<User> getUsers() { return this.restTemplate.getForObject("http://Server-Provider/user", List.class); } public String addUser() { User user = new User(1L, "mrbird", "123456"); HttpStatus status = this.restTemplate.postForEntity("http://Server-Provider/user", user, null).getStatusCode(); if (status.is2xxSuccessful()) { return "新增用户成功"; } else { return "新增用户失败"; } } @CacheRemove(commandKey = "getUserById") @HystrixCommand public void updateUser(@CacheKey("id") User user) { this.restTemplate.put("http://Server-Provider/user", user); } public void deleteUser(@PathVariable Long id) { this.restTemplate.delete("http://Server-Provider/user/{1}", id); } }
repos\SpringAll-master\30.Spring-Cloud-Hystrix-Circuit-Breaker\Ribbon-Consumer\src\main\java\com\example\demo\Service\UserService.java
2
请完成以下Java代码
public void calculateProbabilities(Ant ant) { int i = ant.trail[currentIndex]; double pheromone = 0.0; for (int l = 0; l < numberOfCities; l++) { if (!ant.visited(l)) { pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta); } } for (int j = 0; j < numberOfCities; j++) { if (ant.visited(j)) { probabilities[j] = 0.0; } else { double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta); probabilities[j] = numerator / pheromone; } } } /** * Update trails that ants used */ private void updateTrails() { for (int i = 0; i < numberOfCities; i++) { for (int j = 0; j < numberOfCities; j++) { trails[i][j] *= evaporation; } } for (Ant a : ants) { double contribution = Q / a.trailLength(graph); for (int i = 0; i < numberOfCities - 1; i++) { trails[a.trail[i]][a.trail[i + 1]] += contribution; }
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution; } } /** * Update the best solution */ private void updateBest() { if (bestTourOrder == null) { bestTourOrder = ants.get(0).trail; bestTourLength = ants.get(0) .trailLength(graph); } for (Ant a : ants) { if (a.trailLength(graph) < bestTourLength) { bestTourLength = a.trailLength(graph); bestTourOrder = a.trail.clone(); } } } /** * Clear trails after simulation */ private void clearTrails() { IntStream.range(0, numberOfCities) .forEach(i -> { IntStream.range(0, numberOfCities) .forEach(j -> trails[i][j] = c); }); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\ant_colony\AntColonyOptimization.java
1
请完成以下Java代码
final @Nullable Object bind(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder) { Object result = bindAggregate(name, target, elementBinder); Supplier<?> value = target.getValue(); if (result == null || value == null) { return result; } return merge((Supplier<T>) value, (T) result); } /** * Perform the actual aggregate binding. * @param name the configuration property name to bind * @param target the target to bind * @param elementBinder an element binder * @return the bound result */ protected abstract @Nullable Object bindAggregate(ConfigurationPropertyName name, Bindable<?> target, AggregateElementBinder elementBinder); /** * Merge any additional elements into the existing aggregate. * @param existing the supplier for the existing value * @param additional the additional elements to merge * @return the merged result */ protected abstract T merge(Supplier<T> existing, T additional); /** * Return the context being used by this binder. * @return the context */ protected final Context getContext() { return this.context; } /** * Internal class used to supply the aggregate and cache the value. * * @param <T> the aggregate type
*/ protected static class AggregateSupplier<T> { private final Supplier<T> supplier; private @Nullable T supplied; public AggregateSupplier(Supplier<T> supplier) { this.supplier = supplier; } public T get() { if (this.supplied == null) { this.supplied = this.supplier.get(); } return this.supplied; } public boolean wasSupplied() { return this.supplied != null; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\bind\AggregateBinder.java
1
请完成以下Java代码
public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Credit limit indicator %. @param CreditLimitIndicator Percent of Credit used from the limit */ @Override public void setCreditLimitIndicator (java.lang.String CreditLimitIndicator) { set_Value (COLUMNNAME_CreditLimitIndicator, CreditLimitIndicator); } /** Get Credit limit indicator %. @return Percent of Credit used from the limit */ @Override public java.lang.String getCreditLimitIndicator () { return (java.lang.String)get_Value(COLUMNNAME_CreditLimitIndicator); } /** Set Offene Posten. @param OpenItems Offene Posten */ @Override public void setOpenItems (java.math.BigDecimal OpenItems) { set_Value (COLUMNNAME_OpenItems, OpenItems); } /** Get Offene Posten. @return Offene Posten */ @Override public java.math.BigDecimal getOpenItems () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenItems); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Kredit gewährt. @param SO_CreditUsed Gegenwärtiger Aussenstand */ @Override public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed) { set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed); } /** Get Kredit gewährt. @return Gegenwärtiger Aussenstand */ @Override public java.math.BigDecimal getSO_CreditUsed () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed); if (bd == null) return BigDecimal.ZERO; return bd;
} /** * SOCreditStatus AD_Reference_ID=289 * Reference name: C_BPartner SOCreditStatus */ public static final int SOCREDITSTATUS_AD_Reference_ID=289; /** CreditStop = S */ public static final String SOCREDITSTATUS_CreditStop = "S"; /** CreditHold = H */ public static final String SOCREDITSTATUS_CreditHold = "H"; /** CreditWatch = W */ public static final String SOCREDITSTATUS_CreditWatch = "W"; /** NoCreditCheck = X */ public static final String SOCREDITSTATUS_NoCreditCheck = "X"; /** CreditOK = O */ public static final String SOCREDITSTATUS_CreditOK = "O"; /** NurEineRechnung = I */ public static final String SOCREDITSTATUS_NurEineRechnung = "I"; /** Set Kreditstatus. @param SOCreditStatus Kreditstatus des Geschäftspartners */ @Override public void setSOCreditStatus (java.lang.String SOCreditStatus) { set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus); } /** Get Kreditstatus. @return Kreditstatus des Geschäftspartners */ @Override public java.lang.String getSOCreditStatus () { return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java
1
请完成以下Java代码
public boolean isHUStatusActive() { return huStatus != null && X_M_HU.HUSTATUS_Active.equals(huStatus.getKey()); } @Override public boolean hasAttributes() { return attributesSupplier != null; } @Override public IViewRowAttributes getAttributes() throws EntityNotFoundException { if (attributesSupplier == null) { throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this); } final IViewRowAttributes attributes = attributesSupplier.get(); if (attributes == null) { throw new EntityNotFoundException("This PPOrderLineRow does not support attributes; this=" + this); } return attributes; }
@Override public HuUnitType getHUUnitTypeOrNull() {return huUnitType;} @Override public BPartnerId getBpartnerId() {return huBPartnerId;} @Override public boolean isTopLevel() {return topLevelHU;} @Override public Stream<HUReportAwareViewRow> streamIncludedHUReportAwareRows() {return getIncludedRows().stream().map(PPOrderLineRow::toHUReportAwareViewRow);} private HUReportAwareViewRow toHUReportAwareViewRow() {return this;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineRow.java
1
请完成以下Java代码
public class Flowable5AttachmentWrapper implements Attachment { private org.activiti.engine.task.Attachment activiti5Attachment; public Flowable5AttachmentWrapper(org.activiti.engine.task.Attachment activit5Attachment) { this.activiti5Attachment = activit5Attachment; } @Override public String getId() { return activiti5Attachment.getId(); } @Override public String getName() { return activiti5Attachment.getName(); } @Override public void setName(String name) { activiti5Attachment.setName(name); } @Override public String getDescription() { return activiti5Attachment.getDescription(); } @Override public void setDescription(String description) { activiti5Attachment.setDescription(description); } @Override public String getType() { return activiti5Attachment.getType(); } @Override public String getTaskId() { return activiti5Attachment.getTaskId(); }
@Override public String getProcessInstanceId() { return activiti5Attachment.getProcessInstanceId(); } @Override public String getUrl() { return activiti5Attachment.getUrl(); } @Override public String getUserId() { return activiti5Attachment.getUserId(); } @Override public Date getTime() { return activiti5Attachment.getTime(); } @Override public void setTime(Date time) { activiti5Attachment.setTime(time); } @Override public String getContentId() { return ((AttachmentEntity) activiti5Attachment).getContentId(); } public org.activiti.engine.task.Attachment getRawObject() { return activiti5Attachment; } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5AttachmentWrapper.java
1
请完成以下Java代码
protected String getImportOrderBySql() { return I_I_Replenish.COLUMNNAME_ProductValue; } @Override public I_I_Replenish retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_Replenish(ctx, rs, ITrx.TRXNAME_ThreadInherited); } /* * @param isInsertOnly ignored. This import is only for updates. */ @Override protected ImportRecordResult importRecord( @NonNull final IMutable<Object> state_NOTUSED, @NonNull final I_I_Replenish importRecord, final boolean isInsertOnly_NOTUSED) { if (ReplenishImportHelper.isValidRecordForImport(importRecord)) { return importReplenish(importRecord); } else { throw new AdempiereException(MSG_NoValidRecord); } } private ImportRecordResult importReplenish(@NonNull final I_I_Replenish importRecord) { final ImportRecordResult replenishImportResult;
final I_M_Replenish replenish; if (importRecord.getM_Replenish_ID() <= 0) { replenish = ReplenishImportHelper.createNewReplenish(importRecord); replenishImportResult = ImportRecordResult.Inserted; } else { replenish = ReplenishImportHelper.uppdateReplenish(importRecord); replenishImportResult = ImportRecordResult.Updated; } InterfaceWrapperHelper.save(replenish); importRecord.setM_Replenish_ID(replenish.getM_Replenish_ID()); InterfaceWrapperHelper.save(importRecord); return replenishImportResult; } @Override protected void markImported(@NonNull final I_I_Replenish importRecord) { importRecord.setI_IsImported(X_I_Replenish.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishmentImportProcess.java
1
请完成以下Java代码
private BigDecimal getQtyCUsPerTU() { if (isAllQty) { return getSingleSelectedPickingSlotRow().getHuQtyCU(); } else { final BigDecimal qtyCU = this.qtyCUsPerTU; if (qtyCU == null || qtyCU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } return qtyCU; } } private List<I_M_HU> getSourceCUs() { return getSelectedPickingSlotRows()
.stream() .peek(huRow -> Check.assume(huRow.isCU(), "row {} shall be a CU", huRow)) .map(PickingSlotRow::getHuId) .distinct() .map(huId -> load(huId, I_M_HU.class)) .collect(ImmutableList.toImmutableList()); } private I_M_HU getTargetTU() { final HUEditorRow huRow = getSingleSelectedPackingHUsRow(); Check.assume(huRow.isTU(), "row {} shall be a TU", huRow); return huRow.getM_HU(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutCUsAndAddToTU.java
1
请完成以下Java代码
public java.math.BigDecimal getDiscountAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Generated. @param IsGenerated This Line is generated */ @Override public void setIsGenerated (boolean IsGenerated) { set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated)); } /** Get Generated. @return This Line is generated */ @Override public boolean isGenerated () { Object oo = get_Value(COLUMNNAME_IsGenerated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); }
/** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请完成以下Java代码
public class SignalCmd extends NeedsActiveExecutionCmd<Object> { private static final long serialVersionUID = 1L; protected String signalName; protected Object signalData; protected final Map<String, Object> processVariables; protected Map<String, Object> transientVariables; public SignalCmd(String executionId, String signalName, Object signalData, Map<String, Object> processVariables) { super(executionId); this.signalName = signalName; this.signalData = signalData; this.processVariables = processVariables; } public SignalCmd(String executionId, Map<String, Object> processVariables, Map<String, Object> transientVariables) { super(executionId); this.processVariables = processVariables; this.transientVariables = transientVariables; } @Override protected Object execute(CommandContext commandContext, ExecutionEntity execution) { if (processVariables != null) {
execution.setVariables(processVariables); } if (transientVariables != null) { execution.setTransientVariables(transientVariables); } execution.signal(signalName, signalData); return null; } @Override protected String getSuspendedExceptionMessage() { return "Cannot signal an execution that is suspended"; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SignalCmd.java
1
请完成以下Java代码
public void generateHUsForCustomerReturn(final I_M_InOut customerReturn) { if (!returnsServiceFacade.isCustomerReturn(customerReturn)) { return; // do nothing if the inout is not a customer return } if (inOutBL.isReversal(customerReturn)) { return; // nothing to do } if (returnsServiceFacade.isEmptiesReturn(customerReturn)) { return; // no HUs to generate if the whole InOut is about HUs } final List<I_M_HU> assignedHUs = inOutDAO.retrieveHandlingUnits(customerReturn); if (assignedHUs.isEmpty()) { throw new AdempiereException("No HUs to return assigned"); } // make sure all assigned HUs are active handlingUnitsBL.setHUStatus(assignedHUs, X_M_HU.HUSTATUS_Active); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REVERSECORRECT) public void reverseReturn(final de.metas.handlingunits.model.I_M_InOut returnInOut) { if (!returnsServiceFacade.isVendorReturn(returnInOut)) { return; // nothing to do } final String snapshotId = returnInOut.getSnapshot_UUID(); if (Check.isEmpty(snapshotId, true)) { throw new HUException("@NotFound@ @Snapshot_UUID@ (" + returnInOut + ")"); } final List<I_M_HU> hus = huAssignmentDAO.retrieveTopLevelHUsForModel(returnInOut); if (hus.isEmpty()) { // nothing to do.
return; } final IContextAware context = InterfaceWrapperHelper.getContextAware(returnInOut); snapshotDAO.restoreHUs() .setContext(context) .setSnapshotId(snapshotId) .setDateTrx(returnInOut.getMovementDate()) .setReferencedModel(returnInOut) .addModels(hus) .restoreFromSnapshot(); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE }) public void validateAttributesOnShipmentCompletion(final I_M_InOut shipment) { if (!shipment.isSOTrx()) { // nothing to do return; } huInOutBL.validateMandatoryOnShipmentAttributes(shipment); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_InOut.java
1
请在Spring Boot框架中完成以下Java代码
public AssetProfile save(AssetProfile assetProfile, SecurityUser user) throws Exception { ActionType actionType = assetProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = assetProfile.getTenantId(); try { AssetProfile savedAssetProfile = checkNotNull(assetProfileService.saveAssetProfile(assetProfile)); autoCommit(user, savedAssetProfile.getId()); logEntityActionService.logEntityAction(tenantId, savedAssetProfile.getId(), savedAssetProfile, null, actionType, user); return savedAssetProfile; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET_PROFILE), assetProfile, actionType, user, e); throw e; } } @Override public void delete(AssetProfile assetProfile, User user) { ActionType actionType = ActionType.DELETED; AssetProfileId assetProfileId = assetProfile.getId(); TenantId tenantId = assetProfile.getTenantId(); try { assetProfileService.deleteAssetProfile(tenantId, assetProfileId); logEntityActionService.logEntityAction(tenantId, assetProfileId, assetProfile, null, actionType, user, assetProfileId.toString()); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET_PROFILE), actionType, user, e, assetProfileId.toString()); throw e; }
} @Override public AssetProfile setDefaultAssetProfile(AssetProfile assetProfile, AssetProfile previousDefaultAssetProfile, User user) throws ThingsboardException { TenantId tenantId = assetProfile.getTenantId(); AssetProfileId assetProfileId = assetProfile.getId(); try { if (assetProfileService.setDefaultAssetProfile(tenantId, assetProfileId)) { if (previousDefaultAssetProfile != null) { previousDefaultAssetProfile = assetProfileService.findAssetProfileById(tenantId, previousDefaultAssetProfile.getId()); logEntityActionService.logEntityAction(tenantId, previousDefaultAssetProfile.getId(), previousDefaultAssetProfile, ActionType.UPDATED, user); } assetProfile = assetProfileService.findAssetProfileById(tenantId, assetProfileId); logEntityActionService.logEntityAction(tenantId, assetProfileId, assetProfile, ActionType.UPDATED, user); } return assetProfile; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET_PROFILE), ActionType.UPDATED, user, e, assetProfileId.toString()); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\asset\profile\DefaultTbAssetProfileService.java
2
请完成以下Java代码
private boolean isMandatoryPricingConditions() { final ColorId noPriceConditionsColorId = getNoPriceConditionsColorId(); return noPriceConditionsColorId != null; } private boolean isPricingConditionsMissingButRequired(final I_C_OrderLine orderLine) { // Pricing conditions are not required for packing material line (task 3925) if (orderLine.isPackagingMaterial()) { return false; } return hasPricingConditions(orderLine) == HasPricingConditions.NO; }
private HasPricingConditions hasPricingConditions(final I_C_OrderLine orderLine) { if (orderLine.isTempPricingConditions()) { return HasPricingConditions.TEMPORARY; } else if (orderLine.getM_DiscountSchemaBreak_ID() > 0) { return HasPricingConditions.YES; } else { return HasPricingConditions.NO; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePricingConditions.java
1
请完成以下Java代码
private AllocablePackageable toBOMLineAllocablePackageable(final QtyCalculationsBOMLine bomLine, final AllocablePackageable finishedGoodPackageable) { final Quantity qty = bomLine.computeQtyRequired(finishedGoodPackageable.getQtyToAllocate()); return finishedGoodPackageable.toBuilder() .productId(bomLine.getProductId()) .qtyToAllocateTarget(qty) .issueToBOMLine(IssueToBOMLine.builder() .issueToOrderBOMLineId(Objects.requireNonNull(bomLine.getOrderBOMLineId())) .issueFromHUId(null) // N/A .build()) .build(); } private AllocablePackageable toBOMLineAllocablePackageable(final PickingCandidateIssueToBOMLine candidate, final AllocablePackageable finishedGoodPackageable) { return finishedGoodPackageable.toBuilder() .productId(candidate.getProductId()) .qtyToAllocateTarget(candidate.getQtyToIssue()) .issueToBOMLine(IssueToBOMLine.builder() .issueToOrderBOMLineId(candidate.getIssueToOrderBOMLineId()) .issueFromHUId(candidate.getIssueFromHUId()) .build()) .build(); } private PickingPlanLine updateAlternativeKeys(@NonNull final PickingPlanLine line) { final PickFromHU pickFromHU = line.getPickFromHU(); if (pickFromHU == null) { return line; } final AlternativePickFromKeys alternativeKeys = pickFromHU.getAlternatives() .filter(alternativeKey -> storages.getStorage(alternativeKey.getHuId(), alternativeKey.getProductId()).hasQtyFreeToAllocate()); return line.withPickFromHU(pickFromHU.withAlternatives(alternativeKeys)); } private AlternativePickFromsList getRelevantAlternativesFor(final List<PickingPlanLine> lines) { final HashSet<AlternativePickFromKey> keysConsidered = new HashSet<>(); final ArrayList<AlternativePickFrom> alternatives = new ArrayList<>(); for (final PickingPlanLine line : lines) { final PickFromHU pickFromHU = line.getPickFromHU();
if (pickFromHU == null) { continue; } for (final AlternativePickFromKey key : pickFromHU.getAlternatives()) { if (keysConsidered.add(key)) { storages.getStorage(key.getHuId(), key.getProductId()) .getQtyFreeToAllocate() .filter(Quantity::isPositive) .map(availableQty -> AlternativePickFrom.of(key, availableQty)) .ifPresent(alternatives::add); } } } return AlternativePickFromsList.ofList(alternatives); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\CreatePickingPlanCommand.java
1
请完成以下Java代码
public I_C_Queue_WorkPackage getC_Queue_WorkPackage() { return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage C_Queue_WorkPackage) { set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class, C_Queue_WorkPackage); } @Override public void setC_Queue_WorkPackage_ID (final int C_Queue_WorkPackage_ID) { if (C_Queue_WorkPackage_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, C_Queue_WorkPackage_ID); } @Override public int getC_Queue_WorkPackage_ID() { return get_ValueAsInt(COLUMNNAME_C_Queue_WorkPackage_ID); } @Override public I_C_Queue_WorkPackage getC_Queue_Workpackage_Preceeding() { return get_ValueAsPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class); } @Override public void setC_Queue_Workpackage_Preceeding(final I_C_Queue_WorkPackage C_Queue_Workpackage_Preceeding)
{ set_ValueFromPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class, C_Queue_Workpackage_Preceeding); } @Override public void setC_Queue_Workpackage_Preceeding_ID (final int C_Queue_Workpackage_Preceeding_ID) { throw new IllegalArgumentException ("C_Queue_Workpackage_Preceeding_ID is virtual column"); } @Override public int getC_Queue_Workpackage_Preceeding_ID() { return get_ValueAsInt(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Element.java
1
请完成以下Java代码
public class InOutLineHUPackingMaterialCollectorSource implements IHUPackingMaterialCollectorSource { public static InOutLineHUPackingMaterialCollectorSource of(final I_M_InOutLine inoutLine) { return builder() .inoutLine(inoutLine) .collectHUPipToSource(true) .build(); } private final int productId; private final int recordId; private final I_M_InOutLine inoutLine; private final boolean collectHUPipToSource; @Builder private InOutLineHUPackingMaterialCollectorSource(@NonNull final I_M_InOutLine inoutLine, final boolean collectHUPipToSource) { productId = inoutLine.getM_Product_ID(); recordId = inoutLine.getM_InOutLine_ID(); this.inoutLine = inoutLine; this.collectHUPipToSource = collectHUPipToSource; }
@Override public int getM_Product_ID() { return productId; } @Override public int getRecord_ID() { return recordId; } @Override public boolean isCollectHUPipToSource() { return collectHUPipToSource; } public I_M_InOutLine getM_InOutLine() { return inoutLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\InOutLineHUPackingMaterialCollectorSource.java
1
请完成以下Java代码
public String toString() { return name; } } // helper class ///////////////////////////////////////// public static class SuspensionStateUtil { public static void setSuspensionState(ProcessDefinitionEntity processDefinitionEntity, SuspensionState state) { if (processDefinitionEntity.getSuspensionState() == state.getStateCode()) { throw new ActivitiException( "Cannot set suspension state '" + state + "' for " + processDefinitionEntity + "': already in state '" + state + "'." ); } processDefinitionEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(processDefinitionEntity, state); } public static void setSuspensionState(ExecutionEntity executionEntity, SuspensionState state) { if (executionEntity.getSuspensionState() == state.getStateCode()) { throw new ActivitiException( "Cannot set suspension state '" + state + "' for " + executionEntity + "': already in state '" + state + "'." ); } executionEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(executionEntity, state); } public static void setSuspensionState(TaskEntity taskEntity, SuspensionState state) { if (taskEntity.getSuspensionState() == state.getStateCode()) { throw new ActivitiException( "Cannot set suspension state '" + state + "' for " +
taskEntity + "': already in state '" + state + "'." ); } taskEntity.setSuspensionState(state.getStateCode()); dispatchStateChangeEvent(taskEntity, state); } protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) { if (Context.getCommandContext() != null && Context.getCommandContext().getEventDispatcher().isEnabled()) { ActivitiEventType eventType = null; if (state == SuspensionState.ACTIVE) { eventType = ActivitiEventType.ENTITY_ACTIVATED; } else { eventType = ActivitiEventType.ENTITY_SUSPENDED; } Context.getCommandContext() .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(eventType, entity)); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspensionState.java
1
请在Spring Boot框架中完成以下Java代码
public Class<?> getEntityClass() { return entityClass; } public void setEntityClass(Class<?> entityClass) { this.entityClass = entityClass; } public Method getIdMethod() { return idMethod; } public void setIdMethod(Method idMethod) { this.idMethod = idMethod; idMethod.setAccessible(true); } public Field getIdField() {
return idField; } public void setIdField(Field idField) { this.idField = idField; idField.setAccessible(true); } public Class<?> getIdType() { Class<?> idType = null; if (idField != null) { idType = idField.getType(); } else if (idMethod != null) { idType = idMethod.getReturnType(); } return idType; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\EntityMetaData.java
2
请完成以下Java代码
private Mono<Void> continueFilterChain(ServerWebExchange exchange, WebFilterChain chain) { return Mono.defer(() -> { Mono<CsrfToken> csrfToken = csrfToken(exchange); this.requestHandler.handle(exchange, csrfToken); return chain.filter(exchange); }); } private Mono<CsrfToken> csrfToken(ServerWebExchange exchange) { return this.csrfTokenRepository.loadToken(exchange).switchIfEmpty(generateToken(exchange)); } /** * Constant time comparison to prevent against timing attacks. * @param expected * @param actual * @return */ private static boolean equalsConstantTime(String expected, String actual) { if (expected == actual) { return true; } if (expected == null || actual == null) { return false; } // Encode after ensure that the string is not null byte[] expectedBytes = Utf8.encode(expected); byte[] actualBytes = Utf8.encode(actual); return MessageDigest.isEqual(expectedBytes, actualBytes); } private Mono<CsrfToken> generateToken(ServerWebExchange exchange) { return this.csrfTokenRepository.generateToken(exchange) .delayUntil((token) -> this.csrfTokenRepository.saveToken(exchange, token)) .cache(); }
private static class DefaultRequireCsrfProtectionMatcher implements ServerWebExchangeMatcher { private static final Set<HttpMethod> ALLOWED_METHODS = new HashSet<>( Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.TRACE, HttpMethod.OPTIONS)); @Override public Mono<MatchResult> matches(ServerWebExchange exchange) { return Mono.just(exchange.getRequest()) .flatMap((r) -> Mono.justOrEmpty(r.getMethod())) .filter(ALLOWED_METHODS::contains) .flatMap((m) -> MatchResult.notMatch()) .switchIfEmpty(MatchResult.match()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CsrfWebFilter.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getRemark() {
return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\entity\Picture.java
1
请完成以下Java代码
public String getPassword() { return umsMember.getPassword(); } @Override public String getUsername() { return umsMember.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true;
} @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return umsMember.getStatus()==1; } public UmsMember getUmsMember() { return umsMember; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\domain\MemberDetails.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix. @param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Remote Client. @param Remote_Client_ID Remote Client to be used to replicate / synchronize data with. */ public void setRemote_Client_ID (int Remote_Client_ID) { if (Remote_Client_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID)); } /** Get Remote Client. @return Remote Client to be used to replicate / synchronize data with. */ public int getRemote_Client_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Remote Organization. @param Remote_Org_ID Remote Organization to be used to replicate / synchronize data with. */ public void setRemote_Org_ID (int Remote_Org_ID) { if (Remote_Org_ID < 1) set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null); else set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID)); } /** Get Remote Organization. @return Remote Organization to be used to replicate / synchronize data with. */ public int getRemote_Org_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
1
请完成以下Java代码
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer() { final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine(); final PPOrderBOMLineId coByProductOrderBOMLineId = PPOrderBOMLineId.ofRepoId(coByProductOrderBOMLine.getPP_Order_BOMLine_ID()); final PPOrderId orderId = PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID()); final OrgId orgId = OrgId.ofRepoId(coByProductOrderBOMLine.getAD_Org_ID()); return ReceiptCandidateRequestProducer.builder() .orderId(orderId) .coByProductOrderBOMLineId(coByProductOrderBOMLineId) .orgId(orgId) .date(getMovementDate()) .locatorId(getLocatorId()) .pickingCandidateId(getPickingCandidateId()) .build(); }
@Override protected void addAssignedHUs(final Collection<I_M_HU> hus) { final I_PP_Order_BOMLine bomLine = getCoByProductOrderBOMLine(); huPPOrderBL.addAssignedHandlingUnits(bomLine, hus); } @Override public IPPOrderReceiptHUProducer withPPOrderLocatorId() { final I_PP_Order order = huPPOrderBL.getById(PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID())); return locatorId(LocatorId.ofRepoId(order.getM_Warehouse_ID(), order.getM_Locator_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateCoProductHUProducer.java
1
请完成以下Java代码
public void keyTyped (KeyEvent e) { } @Override public void keyPressed (KeyEvent e) { } @Override public void keyReleased (KeyEvent e) { updateStatusBar(); } // metas: begin public Editor(Frame frame, String header, String text, boolean editable, int maxSize, GridField gridField) { this(frame, header, text, editable, maxSize); BoilerPlateMenu.createFieldMenu(textArea, null, gridField); } private static final GridField getGridField(Container c) { if (c == null) {
return null; } GridField field = null; if (c instanceof VEditor) { VEditor editor = (VEditor)c; field = editor.getField(); } else { try { field = (GridField)c.getClass().getMethod("getField").invoke(c); } catch (Exception e) { final AdempiereException ex = new AdempiereException("Cannot get GridField from " + c, e); log.warn(ex.getLocalizedMessage(), ex); } } return field; } // metas: end } // Editor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Editor.java
1
请完成以下Java代码
public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public void setSuperCaseInstanceId(String superCaseInstanceId) { this.superCaseInstanceId = superCaseInstanceId; } public String getDeleteReason() { return deleteReason; } public void setDeleteReason(String deleteReason) { this.deleteReason = deleteReason; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRestartedProcessInstanceId() { return restartedProcessInstanceId; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { this.restartedProcessInstanceId = restartedProcessInstanceId;
} @Override public String toString() { return this.getClass().getSimpleName() + "[businessKey=" + businessKey + ", startUserId=" + startUserId + ", superProcessInstanceId=" + superProcessInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", superCaseInstanceId=" + superCaseInstanceId + ", deleteReason=" + deleteReason + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", removalTime=" + removalTime + ", endActivityId=" + endActivityId + ", startActivityId=" + startActivityId + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + ", restartedProcessInstanceId=" + restartedProcessInstanceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java
1
请完成以下Java代码
public String setProcessDefinitionKeyToConfiguration(String jobHandlerConfiguration, String processDefinitionKey) { ObjectNode cfgJson = null; try { cfgJson = readJsonValueAsObjectNode(jobHandlerConfiguration); cfgJson.put(PROPERTYNAME_PROCESS_DEFINITION_KEY, processDefinitionKey); return cfgJson.toString(); } catch (JacksonException ex) { return jobHandlerConfiguration; } } public String getProcessDefinitionKeyFromConfiguration(String jobHandlerConfiguration) { try { JsonNode cfgJson = readJsonValue(jobHandlerConfiguration); JsonNode keyNode = cfgJson.get(PROPERTYNAME_PROCESS_DEFINITION_KEY); if (keyNode != null) { return keyNode.asString(); } else { return null; } } catch (JacksonException ex) { return null; } } /** * Before Activiti 5.21, the jobHandlerConfiguration would have as activityId the process definition key (as only one timer start event was supported). In >= 5.21, this changed and in >= 5.21 the * activityId is the REAL activity id. It can be recognized by having the 'processDefinitionKey' in the configuration. A < 5.21 job would not have that. */
public static boolean hasRealActivityId(String jobHandlerConfiguration) { try { JsonNode cfgJson = readJsonValue(jobHandlerConfiguration); JsonNode keyNode = cfgJson.get(PROPERTYNAME_PROCESS_DEFINITION_KEY); if (keyNode != null && !keyNode.isNull()) { return !keyNode.asString().isEmpty(); } else { return false; } } catch (JacksonException ex) { return false; } } protected static ObjectNode createObjectNode() { return Context.getProcessEngineConfiguration().getObjectMapper().createObjectNode(); } protected static ObjectNode readJsonValueAsObjectNode(String config) throws JacksonException { return (ObjectNode) readJsonValue(config); } protected static JsonNode readJsonValue(String config) throws JacksonException { if (Context.getCommandContext() != null) { return Context.getProcessEngineConfiguration().getObjectMapper().readTree(config); } else { return JsonMapper.shared().readTree(config); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerEventHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<UndoDecommissionResponse> undoDecommissionProductIfEligible( @NonNull final SecurPharmProductId productId, @Nullable final InventoryId inventoryId) { final SecurPharmProduct product = productsRepo.getProductById(productId); return undoDecommissionProductIfEligible(product, inventoryId); } public Optional<UndoDecommissionResponse> undoDecommissionProductIfEligible( @NonNull final SecurPharmProduct product, @Nullable final InventoryId inventoryId) { if (!isEligibleForUndoDecommission(product)) { return Optional.empty(); } final SecurPharmClient client = createClient(); final UndoDecommissionClientResponse clientResponse = client.undoDecommission( product.getProductDetails(), product.getDecommissionServerTransactionId()); final UndoDecommissionResponse response = UndoDecommissionResponse.builder() .error(clientResponse.isError()) .inventoryId(inventoryId) .productId(product.getId()) .serverTransactionId(clientResponse.getServerTransactionId()) .build(); actionsRepo.save(response); logsRepo.saveActionLog( clientResponse.getLog(), response.getProductId(), response.getId());
if (!response.isError()) { product.productDecommissionUndo(clientResponse.getServerTransactionId()); productsRepo.save(product); } else { userNotifications.notifyUndoDecommissionFailed(client.getSupportUserId(), response); } return Optional.of(response); } public boolean isEligibleForUndoDecommission(@NonNull final SecurPharmProduct product) { return product.isDecommissioned() // was already decommissioned && !product.isError() // no errors ; } public SecurPharmHUAttributesScanner newHUScanner() { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); final IHandlingUnitsDAO handlingUnitsRepo = Services.get(IHandlingUnitsDAO.class); return SecurPharmHUAttributesScanner.builder() .securPharmService(this) .handlingUnitsBL(handlingUnitsBL) .handlingUnitsRepo(handlingUnitsRepo) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\service\SecurPharmService.java
2
请在Spring Boot框架中完成以下Java代码
public PmsPermission getByPermission(String permission) { return this.getSessionTemplate().selectOne(getStatement("getByPermission"), permission); } /** * 检查权限名称是否已存在(其他id) * * @param permissionName * @param id * @return */ public PmsPermission getByPermissionNameNotEqId(String permissionName, Long id) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("permissionName", permissionName); paramMap.put("id", id);
return this.getSessionTemplate().selectOne(getStatement("getByPermissionNameNotEqId"), paramMap); } /** * 获取叶子菜单下所有的功能权限 * * @param valueOf * @return */ public List<PmsPermission> listAllByMenuId(Long menuId) { Map<String, Object> param = new HashMap<String, Object>(); param.put("menuId", menuId); return this.getSessionTemplate().selectList(getStatement("listAllByMenuId"), param); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsPermissionDaoImpl.java
2
请完成以下Java代码
public static void setTelemetryDataSent(String webappName, String engineName, ServletContext servletContext) { servletContext.setAttribute(buildTelemetrySentAttribute(webappName, engineName), true); } protected static String buildTelemetrySentAttribute(String webappName, String engineName) { return SUCCESSFUL_ET_ATTR_NAME + "." + webappName + "." + engineName; } /** * Sets {@param cacheTimeToLive} in the {@link AuthenticationFilter} to be used on initial login authentication. * See {@link AuthenticationFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} */ public static void setCacheTTLForLogin(long cacheTimeToLive, ServletContext servletContext) { servletContext.setAttribute(AUTH_CACHE_TTL_ATTR_NAME, cacheTimeToLive); }
/** * Returns {@code authCacheValidationTime} from servlet context to be used on initial login authentication. * See {@link UserAuthenticationResource#doLogin(String, String, String, String)} */ public static Date getAuthCacheValidationTime(ServletContext servletContext) { Long cacheTimeToLive = (Long) servletContext.getAttribute(AUTH_CACHE_TTL_ATTR_NAME); if (cacheTimeToLive != null) { return new Date(ClockUtil.getCurrentTime().getTime() + cacheTimeToLive); } else { return null; } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\util\ServletContextUtil.java
1
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isRoute() { return route; } public void setRoute(boolean route) { this.route = route; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public boolean getIsLeaf() { return isLeaf; }
public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal; } public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
private static boolean isValueChanged(final I_AD_Element_Trl adElementTrl, final String columnName) { return InterfaceWrapperHelper.isValueChanged(adElementTrl, columnName); } private enum ADElementTranslatedColumn { Name(I_AD_Element_Trl.COLUMNNAME_Name, I_AD_Element_Trl.COLUMNNAME_Name_Customized), // Description(I_AD_Element_Trl.COLUMNNAME_Description, I_AD_Element_Trl.COLUMNNAME_Description_Customized), // Help(I_AD_Element_Trl.COLUMNNAME_Help, I_AD_Element_Trl.COLUMNNAME_Help_Customized), // PrintName(I_AD_Element.COLUMNNAME_PrintName), // PO_Description(I_AD_Element.COLUMNNAME_PO_Description), // PO_Help(I_AD_Element.COLUMNNAME_PO_Help), // PO_Name(I_AD_Element.COLUMNNAME_PO_Name), // PO_PrintName(I_AD_Element.COLUMNNAME_PO_PrintName), // CommitWarning(I_AD_Element.COLUMNNAME_CommitWarning), // WebuiNameBrowse(I_AD_Element.COLUMNNAME_WEBUI_NameBrowse), // WebuiNameNew(I_AD_Element.COLUMNNAME_WEBUI_NameNew), // WebuiNameNewBreadcrumb(I_AD_Element.COLUMNNAME_WEBUI_NameNewBreadcrumb) // ; @Getter private final String columnName; @Getter private final String customizationColumnName;
ADElementTranslatedColumn(@NonNull final String columnName) { this.columnName = columnName; this.customizationColumnName = null; } ADElementTranslatedColumn( @NonNull final String columnName, @Nullable final String customizationColumnName) { this.columnName = columnName; this.customizationColumnName = customizationColumnName; } public boolean hasCustomizedField() { return getCustomizationColumnName() != null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\interceptor\AD_Element_Trl.java
1
请完成以下Java代码
public class GetHostPort { public static String getHostWithPort(HttpServletRequest request) { String scheme = request.getScheme(); String serverName = request.getServerName(); int serverPort = request.getServerPort(); boolean isDefaultPort = ("http".equals(scheme) && serverPort == 80) || ("https".equals(scheme) && serverPort == 443); if (isDefaultPort) { return String.format("%s://%s", scheme, serverName); } else { return String.format("%s://%s:%d", scheme, serverName, serverPort); } } public static String getBaseUrl() { return ServletUriComponentsBuilder.fromCurrentRequestUri() .replacePath(null) .build() .toUriString(); }
public static String getForwardedHost(HttpServletRequest request) { String forwardedHost = request.getHeader("X-Forwarded-Host"); String forwardedProto = request.getHeader("X-Forwarded-Proto"); String forwardedPort = request.getHeader("X-Forwarded-Port"); String scheme = forwardedProto != null ? forwardedProto : request.getScheme(); String host = forwardedHost != null ? forwardedHost : request.getServerName(); String port = forwardedPort != null ? forwardedPort : String.valueOf(request.getServerPort()); boolean isDefaultPort = ("http".equals(scheme) && "80".equals(port)) || ("https".equals(scheme) && "443".equals(port)); return isDefaultPort ? String.format("%s://%s", scheme, host) : String.format("%s://%s:%s", scheme, host, port); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-5\src\main\java\com\baeldung\hostport\GetHostPort.java
1
请完成以下Java代码
public boolean isRecordsChanged() { return recordsChanged; } public boolean isComplete() { return complete; } public PartitionConfig getConfig() { return config; } public boolean isConfigChanged() { return configChanged; } public int getTargetDLMLevel() { return targetDLMLevel; } public int getCurrentDLMLevel() { return currentDLMLevel; } public Timestamp getNextInspectionDate() { return nextInspectionDate; } public int getDLM_Partition_ID() { return DLM_Partition_ID; } public boolean isAborted() { return aborted; } @Override public String toString() { return "Partition [DLM_Partition_ID=" + DLM_Partition_ID + ", records.size()=" + records.size() + ", recordsChanged=" + recordsChanged + ", configChanged=" + configChanged + ", targetDLMLevel=" + targetDLMLevel + ", currentDLMLevel=" + currentDLMLevel + ", nextInspectionDate=" + nextInspectionDate + "]"; } public static class WorkQueue {
public static WorkQueue of(final I_DLM_Partition_Workqueue workqueueDB) { final ITableRecordReference tableRecordRef = TableRecordReference.ofReferencedOrNull(workqueueDB); final WorkQueue result = new WorkQueue(tableRecordRef); result.setDLM_Partition_Workqueue_ID(workqueueDB.getDLM_Partition_Workqueue_ID()); return result; } public static WorkQueue of(final ITableRecordReference tableRecordRef) { return new WorkQueue(tableRecordRef); } private final ITableRecordReference tableRecordReference; private int dlmPartitionWorkqueueId; private WorkQueue(final ITableRecordReference tableRecordReference) { this.tableRecordReference = tableRecordReference; } public ITableRecordReference getTableRecordReference() { return tableRecordReference; } public int getDLM_Partition_Workqueue_ID() { return dlmPartitionWorkqueueId; } public void setDLM_Partition_Workqueue_ID(final int dlm_Partition_Workqueue_ID) { dlmPartitionWorkqueueId = dlm_Partition_Workqueue_ID; } @Override public String toString() { return "Partition.WorkQueue [DLM_Partition_Workqueue_ID=" + dlmPartitionWorkqueueId + ", tableRecordReference=" + tableRecordReference + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\Partition.java
1
请在Spring Boot框架中完成以下Java代码
public JdbcUserDetailsManagerConfigurer<B> authoritiesByUsernameQuery(String query) { getUserDetailsService().setAuthoritiesByUsernameQuery(query); return this; } /** * An SQL statement to query user's group authorities given a username. For example: * * <code> * select * g.id, g.group_name, ga.authority * from * groups g, group_members gm, group_authorities ga * where * gm.username = ? and g.id = ga.group_id and g.id = gm.group_id * </code> * @param query The query to use for selecting the authorities by group. Must contain * a single parameter for the username. * @return The {@link JdbcUserDetailsManagerConfigurer} used for additional * customizations */ public JdbcUserDetailsManagerConfigurer<B> groupAuthoritiesByUsername(String query) { JdbcUserDetailsManager userDetailsService = getUserDetailsService(); userDetailsService.setEnableGroups(true); userDetailsService.setGroupAuthoritiesByUsernameQuery(query); return this; } /** * A non-empty string prefix that will be added to role strings loaded from persistent * storage (default is ""). * @param rolePrefix * @return The {@link JdbcUserDetailsManagerConfigurer} used for additional * customizations */ public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix) { getUserDetailsService().setRolePrefix(rolePrefix); return this; } /** * Defines the {@link UserCache} to use * @param userCache the {@link UserCache} to use * @return the {@link JdbcUserDetailsManagerConfigurer} for further customizations */ public JdbcUserDetailsManagerConfigurer<B> userCache(UserCache userCache) { getUserDetailsService().setUserCache(userCache); return this; } @Override
protected void initUserDetailsService() { if (!this.initScripts.isEmpty()) { getDataSourceInit().afterPropertiesSet(); } super.initUserDetailsService(); } @Override public JdbcUserDetailsManager getUserDetailsService() { return (JdbcUserDetailsManager) super.getUserDetailsService(); } /** * Populates the default schema that allows users and authorities to be stored. * @return The {@link JdbcUserDetailsManagerConfigurer} used for additional * customizations */ public JdbcUserDetailsManagerConfigurer<B> withDefaultSchema() { this.initScripts.add(new ClassPathResource("org/springframework/security/core/userdetails/jdbc/users.ddl")); return this; } protected DatabasePopulator getDatabasePopulator() { ResourceDatabasePopulator dbp = new ResourceDatabasePopulator(); dbp.setScripts(this.initScripts.toArray(new Resource[0])); return dbp; } private DataSourceInitializer getDataSourceInit() { DataSourceInitializer dsi = new DataSourceInitializer(); dsi.setDatabasePopulator(getDatabasePopulator()); dsi.setDataSource(this.dataSource); return dsi; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\provisioning\JdbcUserDetailsManagerConfigurer.java
2
请完成以下Java代码
public Response intercept(Chain chain) throws IOException { HttpUrl url = chain .request() .url() .newBuilder() .addQueryParameter("api_key", apiKey) .build(); Request request = chain .request() .newBuilder() .url(url) .build(); return chain.proceed(request); } } @JsonAutoDetect(fieldVisibility = ANY) class TopTags { private Map<String, Object> tags; @SuppressWarnings("unchecked") public Set<String> all() { List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag"); return topTags .stream() .map(e -> ((String) e.get("name"))) .collect(Collectors.toSet()); } } @JsonAutoDetect(fieldVisibility = ANY) class Tags { @JsonProperty("toptags") private Map<String, Object> topTags; @SuppressWarnings("unchecked") public Map<String, Double> all() { try { Map<String, Double> all = new HashMap<>(); List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag"); for (Map<String, Object> tag : tags) { all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
} return all; } catch (Exception e) { return Collections.emptyMap(); } } } @JsonAutoDetect(fieldVisibility = ANY) class Artists { private Map<String, Object> artists; @SuppressWarnings("unchecked") public List<String> all() { try { List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist"); return artists .stream() .map(e -> ((String) e.get("name"))) .collect(toList()); } catch (Exception e) { return Collections.emptyList(); } } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\LastFmService.java
1
请完成以下Java代码
public void setM_TU_HU_ID (final int M_TU_HU_ID) { if (M_TU_HU_ID < 1) set_Value (COLUMNNAME_M_TU_HU_ID, null); else set_Value (COLUMNNAME_M_TU_HU_ID, M_TU_HU_ID); } @Override public int getM_TU_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_TU_HU_ID); } @Override public void setProducts (final @Nullable java.lang.String Products) { throw new IllegalArgumentException ("Products is virtual column"); } @Override public java.lang.String getProducts() { return get_ValueAsString(COLUMNNAME_Products); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null);
else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Assignment.java
1
请完成以下Java代码
static String removeAccentsWithApacheCommons(String input) { return StringUtils.stripAccents(input); } static String removeAccents(String input) { return normalize(input).replaceAll("\\p{M}", ""); } static String unicodeValueOfNormalizedString(String input) { return toUnicode(normalize(input)); } private static String normalize(String input) { return input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD); } private static String toUnicode(String input) { if (input.length() == 1) { return toUnicode(input.charAt(0)); } else { StringJoiner stringJoiner = new StringJoiner(" "); for (char c : input.toCharArray()) {
stringJoiner.add(toUnicode(c)); } return stringJoiner.toString(); } } private static String toUnicode(char input) { String hex = Integer.toHexString(input); StringBuilder sb = new StringBuilder(hex); while (sb.length() < 4) { sb.insert(0, "0"); } sb.insert(0, "\\u"); return sb.toString(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-3\src\main\java\com\baeldung\accentsanddiacriticsremoval\StringNormalizer.java
1
请完成以下Java代码
public abstract class AbstractNameValueGatewayFilterFactory extends AbstractGatewayFilterFactory<AbstractNameValueGatewayFilterFactory.NameValueConfig> { public AbstractNameValueGatewayFilterFactory() { super(NameValueConfig.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(GatewayFilter.NAME_KEY, GatewayFilter.VALUE_KEY); } @Validated public static class NameValueConfig { @NotEmpty protected @Nullable String name; @NotEmpty protected @Nullable String value; public @Nullable String getName() { return name; } public NameValueConfig setName(String name) { this.name = name;
return this; } public @Nullable String getValue() { return value; } public NameValueConfig setValue(String value) { this.value = value; return this; } @Override public String toString() { return new ToStringCreator(this).append("name", name).append("value", value).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AbstractNameValueGatewayFilterFactory.java
1
请完成以下Java代码
public static Duration toWorkDuration(final @NonNull BigDecimal duration, final @NonNull TemporalUnit unit) { Check.assumeGreaterOrEqualToZero(duration, "Only positive work durations can be used"); BigDecimal currentDuration = duration; TemporalUnit currentUnit = unit; while (NumberUtils.stripTrailingDecimalZeros(currentDuration).scale() != 0 && !currentUnit.equals(ChronoUnit.NANOS)) { currentDuration = getEquivalentInSmallerTemporalUnit(currentDuration, currentUnit); currentUnit = supportedTemporalUnits.get(supportedTemporalUnits.indexOf(currentUnit) + 1); } final boolean longValueFound = NumberUtils.stripTrailingDecimalZeros(currentDuration).scale() == 0; Check.assume(longValueFound, StringUtils.formatMessage("For {} only natural numbers are supported", unit)); final long durationLong = currentDuration.longValueExact(); return Duration.of(durationLong, currentUnit); } public static Duration toWorkDurationRoundUp(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit) { return toWorkDuration(durationBD.setScale(0, RoundingMode.UP), unit); } public static BigDecimal toBigDecimal(@NonNull final Duration duration, @NonNull final TemporalUnit unit) { return BigDecimal.valueOf(toLong(duration, unit)); } public static Duration fromBigDecimal(@NonNull final BigDecimal duration, @NonNull final TemporalUnit unit) { return Duration.of(duration.longValue(), unit); } public static int toInt(@NonNull final Duration duration, @NonNull final TemporalUnit unit) { return (int)toLong(duration, unit); } public static long toLong(@NonNull final Duration duration, @NonNull final TemporalUnit unit) { if (unit == ChronoUnit.SECONDS) { return duration.getSeconds(); } else if (unit == ChronoUnit.MINUTES) { return duration.toMinutes();
} else if (unit == ChronoUnit.HOURS) { return duration.toHours(); } else if (unit == ChronoUnit.DAYS) { return duration.toDays(); } else { throw Check.newException("Cannot convert " + duration + " to " + unit); } } private static BigDecimal getEquivalentInSmallerTemporalUnit(@NonNull final BigDecimal durationBD, @NonNull final TemporalUnit unit) { if (unit == ChronoUnit.DAYS) { return durationBD.multiply(BigDecimal.valueOf(WORK_HOURS_PER_DAY));// This refers to work hours, not calendar hours } if (unit == ChronoUnit.HOURS) { return durationBD.multiply(BigDecimal.valueOf(60)); } if (unit == ChronoUnit.MINUTES) { return durationBD.multiply(BigDecimal.valueOf(60)); } if (unit == ChronoUnit.SECONDS) { return durationBD.multiply(BigDecimal.valueOf(1000)); } throw Check.newException("No smaller temporal unit defined for {}", unit); } public static boolean isCompleteDays(@NonNull final Duration duration) { if (duration.isZero()) { return true; } final Duration daysAsDuration = Duration.ofDays(duration.toDays()); return daysAsDuration.equals(duration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\DurationUtils.java
1
请完成以下Java代码
public void onSuccess(ValidateDeviceCredentialsResponse msg) { if (!StringUtils.isEmpty(msg.getCredentials())) { deviceCredentialsResponse[0] = msg; } latch.countDown(); } @Override public void onError(Throwable e) { log.error(e.getMessage(), e); latch.countDown(); } }); latch.await(10, TimeUnit.SECONDS); ValidateDeviceCredentialsResponse msg = deviceCredentialsResponse[0]; if (msg != null && strCert.equals(msg.getCredentials())) { DeviceProfile deviceProfile = msg.getDeviceProfile(); if (msg.hasDeviceInfo() && deviceProfile != null) { TbCoapDtlsSessionKey tbCoapDtlsSessionKey = new TbCoapDtlsSessionKey(remotePeer, msg.getCredentials()); tbCoapDtlsSessionInMemoryStorage.put(tbCoapDtlsSessionKey, new TbCoapDtlsSessionInfo(msg, deviceProfile)); } break; } } catch (InterruptedException | CertificateEncodingException | CertificateExpiredException | CertificateNotYetValidException e) { log.error(e.getMessage(), e); AlertMessage alert = new AlertMessage(AlertMessage.AlertLevel.FATAL, AlertMessage.AlertDescription.BAD_CERTIFICATE); throw new HandshakeException("Certificate chain could not be validated", alert); } } return new CertificateVerificationResult(cid, certpath, null);
} catch (HandshakeException e) { log.trace("Certificate validation failed!", e); return new CertificateVerificationResult(cid, e, null); } } @Override public List<X500Principal> getAcceptedIssuers() { return CertPathUtil.toSubjects(null); } @Override public void setResultHandler(HandshakeResultHandler resultHandler) { } public ConcurrentMap<TbCoapDtlsSessionKey, TbCoapDtlsSessionInfo> getTbCoapDtlsSessionsMap() { return tbCoapDtlsSessionInMemoryStorage.getDtlsSessionsMap(); } public void evictTimeoutSessions() { tbCoapDtlsSessionInMemoryStorage.evictTimeoutSessions(); } public long getDtlsSessionReportTimeout() { return tbCoapDtlsSessionInMemoryStorage.getDtlsSessionReportTimeout(); } }
repos\thingsboard-master\common\coap-server\src\main\java\org\thingsboard\server\coapserver\TbCoapDtlsCertificateVerifier.java
1
请完成以下Java代码
public class GetAllEmployeesResponse { @XmlElement(name = "return") protected List<Employee> _return; /** * Gets the value of the return property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the return property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReturn().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link Employee } * * */ public List<Employee> getReturn() { if (_return == null) { _return = new ArrayList<Employee>(); } return this._return; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\GetAllEmployeesResponse.java
1
请完成以下Java代码
public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override protected ShipmentCandidateRows getRowsData() { return ShipmentCandidateRows.cast(super.getRowsData()); } @Override public void close(final ViewCloseAction closeAction) { if (closeAction.isDone())
{ saveChanges(); } } private void saveChanges() { final ShipmentScheduleUserChangeRequestsList userChanges = getRowsData().createShipmentScheduleUserChangeRequestsList().orElse(null); if (userChanges == null) { return; } shipmentScheduleBL.applyUserChangesInTrx(userChanges); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidatesView.java
1
请完成以下Java代码
public CaseInstanceResource getCaseInstance(String caseInstanceId) { return new CaseInstanceResourceImpl(getProcessEngine(), caseInstanceId, getObjectMapper()); } @Override public List<CaseInstanceDto> getCaseInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseInstances(queryDto, firstResult, maxResults); } @Override public List<CaseInstanceDto> queryCaseInstances(CaseInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseInstanceQuery query = queryDto.toQuery(engine); List<CaseInstance> matchingInstances = QueryUtil.list(query, firstResult, maxResults); List<CaseInstanceDto> instanceResults = new ArrayList<CaseInstanceDto>(); for (CaseInstance instance : matchingInstances) { CaseInstanceDto resultInstance = CaseInstanceDto.fromCaseInstance(instance); instanceResults.add(resultInstance); } return instanceResults;
} @Override public CountResultDto getCaseInstancesCount(UriInfo uriInfo) { CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseInstancesCount(queryDto); } @Override public CountResultDto queryCaseInstancesCount(CaseInstanceQueryDto queryDto) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseInstanceQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseInstanceRestServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Binding demo03BindingA() { return BindingBuilder.bind(demo03QueueA()).to(demo03Exchange()); } // 创建 Binding B // Exchange:Demo03Message.EXCHANGE // Queue:Demo03Message.QUEUE_B @Bean public Binding demo03BindingB() { return BindingBuilder.bind(demo03QueueB()).to(demo03Exchange()); } } /** * Headers Exchange 示例的配置类 */ public static class HeadersExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo04Queue() { return new Queue(Demo04Message.QUEUE, // Queue 名字 true, // durable: 是否持久化
false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Headers Exchange @Bean public HeadersExchange demo04Exchange() { return new HeadersExchange(Demo04Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo04Message.EXCHANGE // Queue:Demo04Message.QUEUE // Headers: Demo04Message.HEADER_KEY + Demo04Message.HEADER_VALUE @Bean public Binding demo4Binding() { return BindingBuilder.bind(demo04Queue()).to(demo04Exchange()) .where(Demo04Message.HEADER_KEY).matches(Demo04Message.HEADER_VALUE); // 配置 Headers 匹配 } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public HistoricExternalTaskLogQuery orderByWorkerId() { orderBy(HistoricExternalTaskLogQueryProperty.WORKER_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByActivityId() { orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByActivityInstanceId() { orderBy(HistoricExternalTaskLogQueryProperty.ACTIVITY_INSTANCE_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByExecutionId() { orderBy(HistoricExternalTaskLogQueryProperty.EXECUTION_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessInstanceId() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_INSTANCE_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessDefinitionId() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_ID); return this; } @Override public HistoricExternalTaskLogQuery orderByProcessDefinitionKey() { orderBy(HistoricExternalTaskLogQueryProperty.PROCESS_DEFINITION_KEY); return this; } @Override public HistoricExternalTaskLogQuery orderByTenantId() { orderBy(HistoricExternalTaskLogQueryProperty.TENANT_ID); return this; }
// results ////////////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsCountByQueryCriteria(this); } @Override public List<HistoricExternalTaskLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricExternalTaskLogManager() .findHistoricExternalTaskLogsByQueryCriteria(this, page); } // getters & setters //////////////////////////////////////////////////////////// protected void setState(ExternalTaskState state) { this.state = state; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricExternalTaskLogQueryImpl.java
1
请完成以下Java代码
public Bookauthor as(String alias) { return new Bookauthor(DSL.name(alias), this); } @Override public Bookauthor as(Name alias) { return new Bookauthor(alias, this); } @Override public Bookauthor as(Table<?> alias) { return new Bookauthor(alias.getQualifiedName(), this); } /** * Rename this table */ @Override public Bookauthor rename(String name) { return new Bookauthor(DSL.name(name), null); } /** * Rename this table */ @Override public Bookauthor rename(Name name) { return new Bookauthor(name, null); } /** * Rename this table */ @Override public Bookauthor rename(Table<?> name) { return new Bookauthor(name.getQualifiedName(), null); } /** * Create an inline derived table from this table */ @Override public Bookauthor where(Condition condition) { return new Bookauthor(getQualifiedName(), aliased() ? this : null, null, condition); } /** * Create an inline derived table from this table */ @Override public Bookauthor where(Collection<? extends Condition> conditions) { return where(DSL.and(conditions)); } /** * Create an inline derived table from this table */ @Override public Bookauthor where(Condition... conditions) { return where(DSL.and(conditions)); } /** * Create an inline derived table from this table */ @Override public Bookauthor where(Field<Boolean> condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Bookauthor where(SQL condition) { return where(DSL.condition(condition)); }
/** * Create an inline derived table from this table */ @Override @PlainSQL public Bookauthor where(@Stringly.SQL String condition) { return where(DSL.condition(condition)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Bookauthor where(@Stringly.SQL String condition, Object... binds) { return where(DSL.condition(condition, binds)); } /** * Create an inline derived table from this table */ @Override @PlainSQL public Bookauthor where(@Stringly.SQL String condition, QueryPart... parts) { return where(DSL.condition(condition, parts)); } /** * Create an inline derived table from this table */ @Override public Bookauthor whereExists(Select<?> select) { return where(DSL.exists(select)); } /** * Create an inline derived table from this table */ @Override public Bookauthor whereNotExists(Select<?> select) { return where(DSL.notExists(select)); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Bookauthor.java
1
请完成以下Java代码
public class JsonToJavaClassConversion { public static void main(String[] args) { String packageName = "com.baeldung.jsontojavaclass.pojo"; String basePath = "src/main/resources"; File inputJson = new File(basePath + File.separator + "input.json"); File outputPojoDirectory = new File(basePath + File.separator + "convertedPojo"); outputPojoDirectory.mkdirs(); try { new JsonToJavaClassConversion().convertJsonToJavaClass(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", "")); } catch (IOException e) { System.out.println("Encountered issue while converting to pojo: " + e.getMessage()); e.printStackTrace(); } } public void convertJsonToJavaClass(URL inputJsonUrl, File outputJavaClassDirectory, String packageName, String javaClassName) throws IOException { JCodeModel jcodeModel = new JCodeModel(); GenerationConfig config = new DefaultGenerationConfig() { @Override public boolean isGenerateBuilders() { return true;
} @Override public SourceType getSourceType() { return SourceType.JSON; } }; SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator()); mapper.generate(jcodeModel, javaClassName, packageName, inputJsonUrl); jcodeModel.build(outputJavaClassDirectory); } }
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsontojavaclass\JsonToJavaClassConversion.java
1
请完成以下Java代码
public String warehouse(final ICalloutField calloutField) { final I_C_OrderLine orderLine = calloutField.getModel(I_C_OrderLine.class); final I_C_Order order = InterfaceWrapperHelper.create(orderLine.getC_Order(), I_C_Order.class); if (orderLine.getM_Warehouse_ID() == order.getM_Warehouse_ID()) { // warehouse of order and order line are the same; nothing to do return NO_ERROR; } final IOrgDAO orgsRepo = Services.get(IOrgDAO.class); final OrgId orgId = OrgId.ofRepoId(order.getAD_Org_ID()); final WarehouseId orgDropShipWarehouseId = orgsRepo.getOrgDropshipWarehouseId(orgId); if (orgDropShipWarehouseId != null && orderLine.getM_Warehouse_ID() == orgDropShipWarehouseId.getRepoId()) { // order line's warehouse is the dropship warehouse; nothing to do return NO_ERROR; } // correcting order line's warehouse id orderLine.setM_Warehouse_ID(order.getM_Warehouse_ID()); return NO_ERROR; } /** * Called for: C_OrderLine.IsPriceManual */
public String chkManualPrice(final ICalloutField calloutField) { final I_C_OrderLine orderLine = calloutField.getModel(I_C_OrderLine.class); if (orderLine.isManualPrice()) { return NO_ERROR; } if (orderLine.getM_Product_ID() <= 0) { return NO_ERROR; // if we don't even have a product yet, then there is nothing to update } Services.get(IOrderLineBL.class).updatePrices(orderLine); return NO_ERROR; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\OrderLine.java
1
请完成以下Java代码
public void checkType(final I_ExternalSystem_Config_GRSSignum grsConfig) { final String parentType = externalSystemConfigRepo.getParentTypeById(ExternalSystemParentConfigId.ofRepoId(grsConfig.getExternalSystem_Config_ID())); if (!ExternalSystemType.GRSSignum.getValue().equals(parentType)) { throw new AdempiereException("Invalid external system type: " + parentType); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void generateAndSetUUID(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (grsConfig.getCamelHttpResourceAuthKey() == null) { grsConfig.setCamelHttpResourceAuthKey(UUID.randomUUID().toString()); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW }) public void createExternalSystemInstance(final I_ExternalSystem_Config_GRSSignum grsConfig) { final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(grsConfig.getExternalSystem_Config_ID()); externalServices.initializeServiceInstancesIfRequired(parentConfigId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsSyncBPartnersToRestEndpoint) public void updateIsAutoFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (!grsConfig.isSyncBPartnersToRestEndpoint()) { grsConfig.setIsAutoSendVendors(false);
grsConfig.setIsAutoSendCustomers(false); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsCreateBPartnerFolders, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BasePathForExportDirectories, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BPartnerExportDirectories }) public void checkIsCreateBPartnerFoldersFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (!grsConfig.isCreateBPartnerFolders()) { return; } if (Check.isBlank(grsConfig.getBPartnerExportDirectories()) || Check.isBlank(grsConfig.getBasePathForExportDirectories())) { throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!") .appendParametersToMessage() .setParameter("ExternalSystem_Config_GRSSignum_ID", grsConfig.getExternalSystem_Config_GRSSignum_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\interceptor\ExternalSystem_Config_GRSSignum.java
1
请完成以下Java代码
public String getApid() { return apid; } /** * Sets the value of the apid property. * * @param value * allowed object is * {@link String } * */ public void setApid(String value) { this.apid = value; } /** * Gets the value of the acid property. * * @return * possible object is * {@link String } * */
public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TreatmentType.java
1
请完成以下Java代码
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 gender property. * * @return * possible object is * {@link String } * */ public String getGender() { return gender; } /** * Sets the value of the gender property. * * @param value * allowed object is * {@link String }
* */ public void setGender(String value) { this.gender = value; } /** * Gets the value of the created property. * * @return * possible object is * {@link String } * */ public Calendar getCreated() { return created; } /** * Sets the value of the created property. * * @param value * allowed object is * {@link String } * */ public void setCreated(Calendar value) { this.created = value; } }
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\gen\UserResponse.java
1
请完成以下Java代码
public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus) { documentChanges(documentPath) .collectDocumentSaveStatusChanged(documentSaveStatus); } @Override public void collectDeleted(final DocumentPath documentPath) { documentChanges(documentPath) .collectDeleted(); } @Override public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId) { rootDocumentChanges(rootDocumentPath) .includedDetailInfo(detailId) .setStale(); } @Override public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew) { rootDocumentChanges(rootDocumentPath) .includedDetailInfo(detailId) .setAllowNew(allowNew); } @Override public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete) { rootDocumentChanges(rootDocumentPath) .includedDetailInfo(detailId) .setAllowDelete(allowDelete); } private boolean isStaleDocumentChanges(final DocumentChanges documentChanges) { final DocumentPath documentPath = documentChanges.getDocumentPath(); if (!documentPath.isSingleIncludedDocument()) {
return false; } final DocumentPath rootDocumentPath = documentPath.getRootDocumentPath(); final DetailId detailId = documentPath.getDetailId(); return documentChangesIfExists(rootDocumentPath) .flatMap(rootDocumentChanges -> rootDocumentChanges.includedDetailInfoIfExists(detailId)) .map(IncludedDetailInfo::isStale) .orElse(false); } @Override public void collectEvent(final IDocumentFieldChangedEvent event) { documentChanges(event.getDocumentPath()) .collectEvent(event); } @Override public void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { documentChanges(documentField) .collectFieldWarning(documentField, fieldWarning); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChangesCollector.java
1
请完成以下Java代码
public Customer findByCustomerId3(Long id) { String sql = "SELECT * FROM CUSTOMER WHERE ID = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> new Customer( rs.getLong("id"), rs.getString("name"), rs.getInt("age"), rs.getTimestamp("created_date").toLocalDateTime() )); } public List<Customer> findAll() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = new ArrayList<>(); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) { Customer obj = new Customer(); obj.setID(((Integer) row.get("ID")).longValue()); //obj.setID(((Long) row.get("ID"))); no, ClassCastException obj.setName((String) row.get("NAME")); obj.setAge(((BigDecimal) row.get("AGE")).intValue()); // Spring returns BigDecimal, need convert obj.setCreatedDate(((Timestamp) row.get("CREATED_DATE")).toLocalDateTime()); customers.add(obj); } return customers; } public List<Customer> findAll2() { String sql = "SELECT * FROM CUSTOMER"; List<Customer> customers = jdbcTemplate.query( sql, new CustomerRowMapper()); return customers; } public List<Customer> findAll3() { String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = jdbcTemplate.query( sql, new BeanPropertyRowMapper(Customer.class)); return customers; } public List<Customer> findAll4() { String sql = "SELECT * FROM CUSTOMER"; return jdbcTemplate.query( sql, (rs, rowNum) -> new Customer( rs.getLong("id"), rs.getString("name"), rs.getInt("age"), rs.getTimestamp("created_date").toLocalDateTime() ) ); } public String findCustomerNameById(Long id) { String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?"; return jdbcTemplate.queryForObject( sql, new Object[]{id}, String.class); } public int count() { String sql = "SELECT COUNT(*) FROM CUSTOMER"; // queryForInt() is Deprecated // https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/ //int total = jdbcTemplate.queryForInt(sql); return jdbcTemplate.queryForObject(sql, Integer.class); } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\customer\CustomerRepository.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_ClientShare[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Client Share. @param AD_ClientShare_ID Force (not) sharing of client/org entities */ public void setAD_ClientShare_ID (int AD_ClientShare_ID) { if (AD_ClientShare_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_ClientShare_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_ClientShare_ID, Integer.valueOf(AD_ClientShare_ID)); } /** Get Client Share. @return Force (not) sharing of client/org entities */ public int getAD_ClientShare_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_ClientShare_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set 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 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()); } /** ShareType AD_Reference_ID=365 */ public static final int SHARETYPE_AD_Reference_ID=365; /** Client (all shared) = C */ public static final String SHARETYPE_ClientAllShared = "C"; /** Org (not shared) = O */ public static final String SHARETYPE_OrgNotShared = "O"; /** Client or Org = x */ public static final String SHARETYPE_ClientOrOrg = "x"; /** Set Share Type. @param ShareType Type of sharing */ public void setShareType (String ShareType) { set_Value (COLUMNNAME_ShareType, ShareType); } /** Get Share Type. @return Type of sharing */ public String getShareType () { return (String)get_Value(COLUMNNAME_ShareType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ClientShare.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderDetailRepository { @Autowired private JdbcTemplate jdbcTemplate; public Order getOrderDetail(Integer orderId) { String orderDetailQuery = "select * from orderdetail where orderid = ? "; Order order = new Order(); jdbcTemplate.query(orderDetailQuery, new Object[] { orderId }, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { order.setCustomerId(rs.getInt("customerid")); order.setOrderId(rs.getInt("orderid")); order.setItemId(rs.getInt("itemid")); order.setQuantity(rs.getInt("quantity")); } }); return order; } public double getOrderPrice(Integer orderId) {
String orderItemJoinQuery = "select * from ( select * from orderdetail where orderid = ? ) o left join item on o.itemid = ITEM.itemid"; Order order = new Order(); Item item = new Item(); jdbcTemplate.query(orderItemJoinQuery, new Object[] { orderId }, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { order.setCustomerId(rs.getInt("customerid")); order.setOrderId(rs.getInt("orderid")); order.setItemId(rs.getInt("itemid")); order.setQuantity(rs.getInt("quantity")); item.setItemDesc("itemdesc"); item.setItemId(rs.getInt("itemid")); item.setItemPrice(rs.getDouble("price")); } }); return order.getQuantity() * item.getItemPrice(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\multiplecachemanager\repository\OrderDetailRepository.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_R_InterestArea[") .append(get_ID()).append("]"); return sb.toString(); } /** 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 Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); 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()); } /** Set Interest Area. @param R_InterestArea_ID Interest Area or Topic */ public void setR_InterestArea_ID (int R_InterestArea_ID) { if (R_InterestArea_ID < 1) set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null); else set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID)); } /** Get Interest Area. @return Interest Area or Topic */ public int getR_InterestArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_InterestArea.java
1
请完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReferrer (final @Nullable java.lang.String Referrer) { set_Value (COLUMNNAME_Referrer, Referrer); } @Override public java.lang.String getReferrer() {
return get_ValueAsString(COLUMNNAME_Referrer); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput.java
1
请完成以下Java代码
public class OrderConfirmedEvent { private final String orderId; public OrderConfirmedEvent(String orderId) { this.orderId = orderId; } public String getOrderId() { return orderId; } @Override public int hashCode() { return Objects.hash(orderId); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final OrderConfirmedEvent other = (OrderConfirmedEvent) obj; return Objects.equals(this.orderId, other.orderId); } @Override public String toString() { return "OrderConfirmedEvent{" + "orderId='" + orderId + '\'' + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\events\OrderConfirmedEvent.java
1
请完成以下Java代码
public void setUmsatzsteuerID(String value) { this.umsatzsteuerID = value; } /** * Gets the value of the steuernummer property. * * @return * possible object is * {@link String } * */ public String getSteuernummer() { return steuernummer; } /** * Sets the value of the steuernummer property. * * @param value * allowed object is * {@link String } * */ public void setSteuernummer(String value) { this.steuernummer = value; } /** * Gets the value of the bankname property. * * @return * possible object is * {@link String } * */ public String getBankname() { return bankname; } /** * Sets the value of the bankname property. * * @param value * allowed object is * {@link String } * */ public void setBankname(String value) { this.bankname = value; } /** * Gets the value of the bic property. * * @return * possible object is * {@link String } * */ public String getBIC() {
return bic; } /** * Sets the value of the bic property. * * @param value * allowed object is * {@link String } * */ public void setBIC(String value) { this.bic = 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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungType.java
1
请完成以下Java代码
private final Map<String, IAttributeStorage> getInnerChildrenAttributeStoragesMap(final boolean loadIfNeeded) { if (childrenAttributeStoragesMap == null) { if (!loadIfNeeded) { return Collections.emptyMap(); } childrenAttributeStoragesMap = retrieveChildrenAttributeStorages(); } return childrenAttributeStoragesMap; } @Override public final Collection<IAttributeStorage> getChildAttributeStorages(final boolean loadIfNeeded) { final Map<String, IAttributeStorage> childrenAttributeStoragesMap = getInnerChildrenAttributeStoragesMap(loadIfNeeded); return Collections.unmodifiableCollection(childrenAttributeStoragesMap.values()); } private final Map<String, IAttributeStorage> retrieveChildrenAttributeStorages() { final IAttributeStorageFactory storageFactory = getAttributeStorageFactory(); final IHandlingUnitsDAO handlingUnitsDAO = getHandlingUnitsDAO(); final Map<String, IAttributeStorage> childrenAttributeSetStorages = new LinkedHashMap<>(); final I_M_HU hu = getM_HU(); if (hu == null) { return childrenAttributeSetStorages; } // Retrieve HU items and get children HUs final List<I_M_HU_Item> huItems = handlingUnitsDAO.retrieveItems(hu); final boolean saveOnChange = isSaveOnChange(); for (final I_M_HU_Item item : huItems) { final List<I_M_HU> childrenHU = handlingUnitsDAO.retrieveIncludedHUs(item); for (final I_M_HU childHU : childrenHU) { final IAttributeStorage childAttributeSetStorage = storageFactory.getAttributeStorage(childHU); childAttributeSetStorage.setSaveOnChange(saveOnChange); // propagate saveOnChange to child childrenAttributeSetStorages.put(childAttributeSetStorage.getId(), childAttributeSetStorage); } } return childrenAttributeSetStorages; }
/** * Add the given <code>childAttributeStorage</code> to this storage's children. If children were not yet loaded, then this method also loads them. * * @param childAttributeStorage */ @Override protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) { final Map<String, IAttributeStorage> childrenAttributeStoragesMap = getInnerChildrenAttributeStoragesMap(true); childrenAttributeStoragesMap.put(childAttributeStorage.getId(), childAttributeStorage); } /** * Removes the given <code>childAttributeStorage</code> from this storage's children. If children were not yet loaded, then this method also loads them. * * @param childAttributeStorage */ @Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) { final Map<String, IAttributeStorage> childrenAttributeStoragesMap = getInnerChildrenAttributeStoragesMap(true); return childrenAttributeStoragesMap.remove(childAttributeStorage.getId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeStorage.java
1
请完成以下Java代码
public class Server { private static final Logger LOG = LoggerFactory.getLogger(Server.class); private final Disposable server; private final DataPublisher dataPublisher = new DataPublisher(); private final GameController gameController; public Server() { this.server = RSocketFactory.receive() .acceptor((setupPayload, reactiveSocket) -> Mono.just(new RSocketImpl())) .transport(TcpServerTransport.create("localhost", TCP_PORT)) .start() .doOnNext(x -> LOG.info("Server started")) .subscribe(); this.gameController = new GameController("Server Player"); } public void dispose() { dataPublisher.complete(); this.server.dispose(); } /** * RSocket implementation */ private class RSocketImpl extends AbstractRSocket { /** * Handle Request/Response messages * * @param payload Message payload * @return payload response */ @Override public Mono<Payload> requestResponse(Payload payload) { try { return Mono.just(payload); // reflect the payload back to the sender } catch (Exception x) { return Mono.error(x); } } /** * Handle Fire-and-Forget messages * * @param payload Message payload * @return nothing */ @Override public Mono<Void> fireAndForget(Payload payload) { try { dataPublisher.publish(payload); // forward the payload return Mono.empty();
} catch (Exception x) { return Mono.error(x); } } /** * Handle Request/Stream messages. Each request returns a new stream. * * @param payload Payload that can be used to determine which stream to return * @return Flux stream containing simulated measurement data */ @Override public Flux<Payload> requestStream(Payload payload) { String streamName = payload.getDataUtf8(); if (DATA_STREAM_NAME.equals(streamName)) { return Flux.from(dataPublisher); } return Flux.error(new IllegalArgumentException(streamName)); } /** * Handle request for bidirectional channel * * @param payloads Stream of payloads delivered from the client * @return */ @Override public Flux<Payload> requestChannel(Publisher<Payload> payloads) { Flux.from(payloads) .subscribe(gameController::processPayload); Flux<Payload> channel = Flux.from(gameController); return channel; } } }
repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\Server.java
1
请完成以下Java代码
public Object get(Object key) { Object result = null; if(wrappedBindings.containsKey(key)) { result = wrappedBindings.get(key); } else { if (key instanceof String) { TypedValue resolvedValue = variableContext.resolve((String) key); result = unpack(resolvedValue); } } return result; } /** * Dedicated implementation which does not fall back on the {@link #calculateBindingMap()} for performance reasons */ public Object put(String name, Object value) { // only write to the wrapped bindings return wrappedBindings.put(name, value); } public Set<Entry<String, Object>> entrySet() { return calculateBindingMap().entrySet(); } public Set<String> keySet() { return calculateBindingMap().keySet(); } public int size() { return calculateBindingMap().size(); } public Collection<Object> values() { return calculateBindingMap().values(); } public void putAll(Map< ? extends String, ?> toMerge) { for (Entry<? extends String, ?> entry : toMerge.entrySet()) { put(entry.getKey(), entry.getValue()); } } public Object remove(Object key) {
return wrappedBindings.remove(key); } public void clear() { wrappedBindings.clear(); } public boolean containsValue(Object value) { return calculateBindingMap().containsValue(value); } public boolean isEmpty() { return calculateBindingMap().isEmpty(); } protected Map<String, Object> calculateBindingMap() { Map<String, Object> bindingMap = new HashMap<String, Object>(); Set<String> keySet = variableContext.keySet(); for (String variableName : keySet) { bindingMap.put(variableName, unpack(variableContext.resolve(variableName))); } Set<Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet(); for (Entry<String, Object> entry : wrappedBindingsEntries) { bindingMap.put(entry.getKey(), entry.getValue()); } return bindingMap; } protected Object unpack(TypedValue resolvedValue) { if(resolvedValue != null) { return resolvedValue.getValue(); } return null; } public static VariableContextScriptBindings wrap(Bindings wrappedBindings, VariableContext variableContext) { return new VariableContextScriptBindings(wrappedBindings, variableContext); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\el\VariableContextScriptBindings.java
1
请完成以下Java代码
public synchronized void addDevice(final DeviceConfig device) { final String deviceName = device.getDeviceName(); final DeviceConfig existingDevice = removeDeviceByName(deviceName); devicesByName.put(deviceName, device); device.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.put(attributeCode, device)); logger.info("addDevice: {} -> {}", existingDevice, device); } public synchronized @Nullable DeviceConfig removeDeviceByName(@NonNull final String deviceName) { final DeviceConfig existingDevice = devicesByName.remove(deviceName); if (existingDevice != null) { existingDevice.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.remove(attributeCode, existingDevice)); } return existingDevice; } public synchronized ImmutableList<DeviceConfig> getAllDevices()
{ return ImmutableList.copyOf(devicesByName.values()); } public synchronized ImmutableList<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode) { return ImmutableList.copyOf(devicesByAttributeCode.get(attributeCode)); } public ImmutableSet<AttributeCode> getAllAttributeCodes() { return ImmutableSet.copyOf(devicesByAttributeCode.keySet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDeviceConfigPool.java
1
请完成以下Java代码
public static void sendMessageTo(String[] userIds, String message) { for (String userId : userIds) { VxeSocket.sendMessageTo(userId, message); } } /** * 向所有用户的所有页面发送消息 * * @param message 消息内容 */ public static void sendMessageToAll(String message) { for (VxeSocket socketItem : socketPool.values()) { socketItem.sendMessage(message); } } /** * websocket 开启连接 */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("pageId") String pageId) { try { this.userId = userId; this.pageId = pageId; this.socketId = userId + pageId; this.session = session; socketPool.put(this.socketId, this); getUserPool(userId).put(this.pageId, this); log.info("【vxeSocket】有新的连接,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 断开连接 */ @OnClose public void onClose() { try { socketPool.remove(this.socketId); getUserPool(this.userId).remove(this.pageId); log.info("【vxeSocket】连接断开,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 收到消息
*/ @OnMessage public void onMessage(String message) { // log.info("【vxeSocket】onMessage:" + message); JSONObject json; try { json = JSON.parseObject(message); } catch (Exception e) { log.warn("【vxeSocket】收到不合法的消息:" + message); return; } String type = json.getString(VxeSocketConst.TYPE); switch (type) { // 心跳检测 case VxeSocketConst.TYPE_HB: this.sendMessage(VxeSocket.packageMessage(type, true)); break; // 更新form数据 case VxeSocketConst.TYPE_UVT: this.handleUpdateForm(json); break; default: log.warn("【vxeSocket】收到不识别的消息类型:" + type); break; } } /** * 处理 UpdateForm 事件 */ private void handleUpdateForm(JSONObject json) { // 将事件转发给所有人 JSONObject data = json.getJSONObject(VxeSocketConst.DATA); VxeSocket.sendMessageToAll(VxeSocket.packageMessage(VxeSocketConst.TYPE_UVT, data)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\vxe\websocket\VxeSocket.java
1
请完成以下Java代码
private static OIRow applyChanges(@NonNull final OIRow row, @NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests) { final OIRow.OIRowBuilder changedRowBuilder = row.toBuilder(); for (final JSONDocumentChangedEvent event : fieldChangeRequests) { event.assertReplaceOperation(); if (OIRow.FIELD_Selected.equals(event.getPath())) { changedRowBuilder.selected(event.getValueAsBoolean(false)); } } return changedRowBuilder.build(); } public void markRowsAsSelected(final DocumentIdsSelection rowIds)
{ rowsHolder.changeRowsByIds(rowIds, row -> row.withSelected(true)); headerPropertiesHolder.setValue(null); } public boolean hasSelectedRows() { return rowsHolder.anyMatch(OIRow::isSelected); } public void clearUserInput() { rowsHolder.changeRowsByIds(DocumentIdsSelection.ALL, OIRow::withUserInputCleared); headerPropertiesHolder.setValue(null); } public OIRowUserInputParts getUserInput() {return OIRowUserInputParts.ofStream(rowsHolder.stream());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIViewData.java
1
请完成以下Java代码
public Builder setDocActionElement(@Nullable final DocumentLayoutElementDescriptor docActionElement) { this.docActionElement = docActionElement; return this; } public Builder setGridView(final ViewLayout.Builder gridView) { this._gridView = gridView; return this; } public Builder setSingleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout) { this.singleRowLayout = singleRowLayout; return this; } private DocumentLayoutSingleRow.Builder getSingleRowLayout() { return singleRowLayout; } private ViewLayout.Builder getGridView() { return _gridView; } public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail) { if (detail == null) { return this; } if (detail.isEmpty()) { logger.trace("Skip adding detail to layout because it is empty; detail={}", detail); return this; }
details.add(detail); return this; } public Builder setSideListView(final ViewLayout sideListViewLayout) { this._sideListView = sideListViewLayout; return this; } private ViewLayout getSideList() { Preconditions.checkNotNull(_sideListView, "sideList"); return _sideListView; } public Builder putDebugProperty(final String name, final String value) { debugProperties.put(name, value); return this; } public Builder setStopwatch(final Stopwatch stopwatch) { this.stopwatch = stopwatch; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_M_Promotion[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Campaign getC_Campaign() throws RuntimeException { return (I_C_Campaign)MTable.get(getCtx(), I_C_Campaign.Table_Name) .getPO(getC_Campaign_ID(), get_TrxName()); } /** Set Campaign. @param C_Campaign_ID Marketing Campaign */ public void setC_Campaign_ID (int C_Campaign_ID) { if (C_Campaign_ID < 1) set_Value (COLUMNNAME_C_Campaign_ID, null); else set_Value (COLUMNNAME_C_Campaign_ID, Integer.valueOf(C_Campaign_ID)); } /** Get Campaign. @return Marketing Campaign */ public int getC_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Campaign_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 Promotion. @param M_Promotion_ID Promotion */ public void setM_Promotion_ID (int M_Promotion_ID) { if (M_Promotion_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Promotion_ID, Integer.valueOf(M_Promotion_ID)); } /** Get Promotion. @return Promotion */ public int getM_Promotion_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Promotion_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Relative Priority. @param PromotionPriority Which promotion should be apply to a product */ public void setPromotionPriority (int PromotionPriority) { set_Value (COLUMNNAME_PromotionPriority, Integer.valueOf(PromotionPriority)); } /** Get Relative Priority. @return Which promotion should be apply to a product */ public int getPromotionPriority () { Integer ii = (Integer)get_Value(COLUMNNAME_PromotionPriority); 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_M_Promotion.java
1
请完成以下Java代码
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Override public int hashCode() { return Objects.hash(firstName, lastName, position); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Player other = (Player) obj;
if (firstName == null) { if (other.firstName != null) { return false; } } else if (!firstName.equals(other.firstName)) { return false; } if (lastName == null) { if (other.lastName != null) { return false; } } else if (!lastName.equals(other.lastName)) { return false; } if (position == null) { if (other.position != null) { return false; } } else if (!position.equals(other.position)) { return false; } return true; } }
repos\tutorials-master\core-java-modules\core-java-lang-3\src\main\java\com\baeldung\hash\Player.java
1
请在Spring Boot框架中完成以下Java代码
public void onFailure(Throwable t) { log.warn("Failed to update alarm", t); } } private AlarmApiCallResult withWsCallback(AlarmApiCallResult result) { return withWsCallback(null, result); } private AlarmApiCallResult withWsCallback(AlarmModificationRequest request, AlarmApiCallResult result) { if (result.isSuccessful() && result.isModified()) { Futures.addCallback(Futures.immediateFuture(result), new AlarmUpdateCallback(), wsCallBackExecutor); if (result.isSeverityChanged()) { AlarmInfo alarm = result.getAlarm(); AlarmComment.AlarmCommentBuilder alarmComment = AlarmComment.builder() .alarmId(alarm.getId()) .type(AlarmCommentType.SYSTEM) .comment(JacksonUtil.newObjectNode() .put("text", String.format(SEVERITY_CHANGED.getText(), result.getOldSeverity(), alarm.getSeverity()))
.put("subtype", SEVERITY_CHANGED.name()) .put("oldSeverity", result.getOldSeverity().name()) .put("newSeverity", alarm.getSeverity().name())); if (request != null && request.getUserId() != null) { alarmComment.userId(request.getUserId()); } try { alarmCommentService.saveAlarmComment(alarm, alarmComment.build(), null); } catch (ThingsboardException e) { log.error("Failed to save alarm comment", e); } } } return result; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultAlarmSubscriptionService.java
2
请完成以下Java代码
public @Nullable Authentication buildRunAs(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { List<GrantedAuthority> newAuthorities = new ArrayList<>(); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { GrantedAuthority extraAuthority = new SimpleGrantedAuthority( getRolePrefix() + attribute.getAttribute()); newAuthorities.add(extraAuthority); } } if (newAuthorities.isEmpty()) { return null; } // Add existing authorities newAuthorities.addAll(authentication.getAuthorities()); return new RunAsUserToken(this.key, authentication.getPrincipal(), authentication.getCredentials(), newAuthorities, authentication.getClass()); } public String getKey() { return this.key; } public String getRolePrefix() { return this.rolePrefix; } public void setKey(String key) { this.key = key; } /** * Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set * to an empty value, although this is usually not desirable. * @param rolePrefix the new prefix
*/ public void setRolePrefix(String rolePrefix) { this.rolePrefix = rolePrefix; } @Override public boolean supports(ConfigAttribute attribute) { return attribute.getAttribute() != null && attribute.getAttribute().startsWith("RUN_AS_"); } /** * This implementation supports any type of class, because it does not query the * presented secure object. * @param clazz the secure object * @return always <code>true</code> */ @Override public boolean supports(Class<?> clazz) { return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\RunAsManagerImpl.java
1
请完成以下Java代码
public static Type ofStringValueOrNull(@Nullable final String value) { if (value == null) { return null; } final Type result = MAP.get(value); return result; } public static String getValueOrNull(@Nullable final Type type) { if (type == null) { return null; } return type.value; } } @JsonProperty("id") @NonNull OrderResponsePackageItemPartId id; @JsonProperty("qty") @NonNull Quantity qty; @JsonProperty("type") Type type; @JsonProperty("deliveryDate") ZonedDateTime deliveryDate; @JsonProperty("defectReason") OrderDefectReason defectReason; @JsonProperty("tour") String tour; @JsonProperty("tourId") String tourId; @JsonProperty("tourDeviation") boolean tourDeviation;
@Builder @JsonCreator private OrderResponsePackageItemPart( @JsonProperty("id") final OrderResponsePackageItemPartId id, @JsonProperty("qty") @NonNull final Quantity qty, @JsonProperty("type") final Type type, @JsonProperty("deliveryDate") final ZonedDateTime deliveryDate, @JsonProperty("defectReason") final OrderDefectReason defectReason, @JsonProperty("tour") final String tour, @JsonProperty("tourId") final String tourId, @JsonProperty("tourDeviation") final boolean tourDeviation) { this.id = id != null ? id : OrderResponsePackageItemPartId.random(); this.qty = qty; this.type = type; this.deliveryDate = deliveryDate; this.defectReason = defectReason; this.tour = tour; this.tourId = tourId; this.tourDeviation = tourDeviation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderResponsePackageItemPart.java
1
请完成以下Java代码
private void initProviderBean(String beanName, Object bean) throws Exception { Service service = this.applicationContext.findAnnotationOnBean(beanName, Service.class); ServiceBean<Object> serviceConfig = new ServiceBean<Object>(service); if ((service.interfaceClass() == null || service.interfaceClass() == void.class) && (service.interfaceName() == null || "".equals(service.interfaceName()))) { Class<?>[] interfaces = bean.getClass().getInterfaces(); if (interfaces.length > 0) { serviceConfig.setInterface(interfaces[0]); } } Environment environment = this.applicationContext.getEnvironment(); String application = service.application(); serviceConfig.setApplication(this.parseApplication(application, this.properties, environment, beanName, "application", application)); String module = service.module(); serviceConfig.setModule( this.parseModule(module, this.properties, environment, beanName, "module", module)); String[] registries = service.registry(); serviceConfig.setRegistries( this.parseRegistries(registries, this.properties, environment, beanName, "registry")); String[] protocols = service.protocol(); serviceConfig.setProtocols(
this.parseProtocols(protocols, this.properties, environment, beanName, "registry")); String monitor = service.monitor(); serviceConfig.setMonitor( this.parseMonitor(monitor, this.properties, environment, beanName, "monitor", monitor)); String provider = service.provider(); serviceConfig.setProvider( this.parseProvider(provider, this.properties, environment, beanName, "provider", provider)); serviceConfig.setApplicationContext(this.applicationContext); serviceConfig.afterPropertiesSet(); serviceConfig.setRef(bean); serviceConfig.export(); } @Override protected String buildErrorMsg(String... errors) { if (errors == null || errors.length != 3) { return super.buildErrorMsg(errors); } return new StringBuilder().append("beanName=").append(errors[0]).append(", ").append(errors[1]) .append("=").append(errors[2]).append(" not found in multi configs").toString(); } }
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboProviderAutoConfiguration.java
1
请完成以下Java代码
void uselessNullCheck() { String head = "1234"; String tail = "5678"; String concatenation = concatenateOnlyIfSecondArgumentIsNotNull(head, tail); if (concatenation != null) { System.out.println(concatenation); } } void uselessNullCheckOnInferredAnnotation() { if (StringUtils.isEmpty(null)) { System.out.println("baeldung"); } } @Contract(pure = true) String replace(String string, char oldChar, char newChar) { return string.replace(oldChar, newChar); } @Contract(value = "true -> false; false -> true", pure = true) boolean not(boolean input) { return !input; } @Contract("true -> new") void contractExpectsWrongParameterType(List<Integer> integers) { } @Contract("_, _ -> new") void contractExpectsMoreParametersThanMethodHas(String s) { } @Contract("_ -> _; null -> !null") String secondContractClauseNotReachable(String s) { return ""; } @Contract("_ -> true") void contractExpectsWrongReturnType(String s) { } // NB: the following examples demonstrate how to use the mutates attribute of the annotation // This attribute is currently experimental and could be changed or removed in the future @Contract(mutates = "param") void incrementArrayFirstElement(Integer[] integers) { if (integers.length > 0) { integers[0] = integers[0] + 1; }
} @Contract(pure = true, mutates = "param") void impossibleToMutateParamInPureFunction(List<String> strings) { if (strings != null) { strings.forEach(System.out::println); } } @Contract(mutates = "param3") void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) { } @Contract(mutates = "param") void impossibleToMutableImmutableType(String s) { } @Contract(mutates = "this") static void impossibleToMutateThisInStaticMethod() { } }
repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java
1
请在Spring Boot框架中完成以下Java代码
public KerberosAuthenticationProvider kerberosAuthenticationProvider() { KerberosAuthenticationProvider provider = new KerberosAuthenticationProvider(); SunJaasKerberosClient client = new SunJaasKerberosClient(); client.setDebug(true); provider.setKerberosClient(client); provider.setUserDetailsService(dummyUserDetailsService()); return provider; } @Bean public SpnegoEntryPoint spnegoEntryPoint() { return new SpnegoEntryPoint("/login"); } @Bean public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(AuthenticationManager authenticationManager) { SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter(); filter.setAuthenticationManager(authenticationManager); return filter; } @Bean public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() { KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider(); provider.setTicketValidator(sunJaasKerberosTicketValidator()); provider.setUserDetailsService(dummyUserDetailsService()); return provider; }
@Bean public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() { SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator(); ticketValidator.setServicePrincipal("HTTP/demo.kerberos.bealdung.com@baeldung.com"); ticketValidator.setKeyTabLocation(new FileSystemResource("baeldung.keytab")); ticketValidator.setDebug(true); return ticketValidator; } @Bean public DummyUserDetailsService dummyUserDetailsService() { return new DummyUserDetailsService(); } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2-sso\spring-security-sso-kerberos\src\main\java\com\baeldung\intro\config\WebSecurityConfig.java
2
请完成以下Java代码
public Set<CostElement> getCostElements() { return amountsPerElement.keySet(); } public CostAmountDetailed getCostAmountForCostElement(final CostElement costElement) { final CostAmountDetailed amt = amountsPerElement.get(costElement); if (amt == null) { throw new AdempiereException("No cost amount for " + costElement + " in " + this); } return amt; } public AggregatedCostAmount merge(@NonNull final AggregatedCostAmount other) { if (!Objects.equals(costSegment, other.costSegment)) { throw new AdempiereException("Cannot merge cost results when the cost segment is not matching: " + this + ", " + other); } // merge amounts maps; will fail in case of duplicate cost elements final ImmutableMap<CostElement, CostAmountDetailed> amountsNew = ImmutableMap.<CostElement, CostAmountDetailed>builder() .putAll(amountsPerElement) .putAll(other.amountsPerElement) .build(); return new AggregatedCostAmount(costSegment, amountsNew); } public AggregatedCostAmount add(@NonNull final AggregatedCostAmount other) { if (!Objects.equals(costSegment, other.costSegment)) { throw new AdempiereException("Cannot add cost results when the cost segment is not matching: " + this + ", " + other); } final Map<CostElement, CostAmountDetailed> amountsNew = new HashMap<>(amountsPerElement); other.amountsPerElement.forEach((costElement, amtToAdd) -> { amountsNew.compute(costElement, (ce, amtOld) -> amtOld != null ? amtOld.add(amtToAdd) : amtToAdd); }); return new AggregatedCostAmount(costSegment, amountsNew); } @VisibleForTesting public AggregatedCostAmount retainOnlyAccountable(@NonNull final AcctSchema as) { final AcctSchemaCosting costing = as.getCosting(); final LinkedHashMap<CostElement, CostAmountDetailed> amountsPerElementNew = new LinkedHashMap<>(); amountsPerElement.forEach((costElement, costAmount) -> { if (costElement.isAccountable(costing))
{ amountsPerElementNew.put(costElement, costAmount); } }); if (amountsPerElementNew.size() == amountsPerElement.size()) { return this; } return new AggregatedCostAmount(costSegment, amountsPerElementNew); } public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as) { return getTotalAmount(as.getCosting()).orElseGet(() -> CostAmountDetailed.zero(as.getCurrencyId())); } @VisibleForTesting Optional<CostAmountDetailed> getTotalAmount(@NonNull final AcctSchemaCosting asCosting) { return getCostElements() .stream() .filter(costElement -> costElement.isAccountable(asCosting)) .map(this::getCostAmountForCostElement) .reduce(CostAmountDetailed::add); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\AggregatedCostAmount.java
1
请完成以下Java代码
public class C_Invoice_CancelAndRecreate extends JavaProcess implements IProcessPrecondition { private final RecreateInvoiceEnqueuer enqueuer = SpringContextHolder.instance.getBean(RecreateInvoiceEnqueuer.class); private final IQueryBL queryBL = Services.get(IQueryBL.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected void prepare() { final IQueryFilter<I_C_Invoice> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { return; } final int selectionCount = queryBL .createQueryBuilder(I_C_Invoice.class) .filter(userSelectionFilter)
.addEqualsFilter(I_C_Invoice.COLUMNNAME_DocStatus, X_C_Invoice.DOCSTATUS_Completed) .addOnlyActiveRecordsFilter() .create() .createSelection(getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException("@NoSelection@"); } } @Override protected String doIt() throws Exception { enqueuer.enqueueSelection(getProcessInfo().getPinstanceId()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_CancelAndRecreate.java
1
请完成以下Java代码
public void setM_PharmaProductCategory_ID (int M_PharmaProductCategory_ID) { if (M_PharmaProductCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, Integer.valueOf(M_PharmaProductCategory_ID)); } /** Get Pharma Product Category. @return Pharma Product Category */ @Override public int getM_PharmaProductCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PharmaProductCategory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name.
@param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_PharmaProductCategory.java
1
请在Spring Boot框架中完成以下Java代码
public class ServerDeploy extends BaseEntity implements Serializable { @Id @Column(name = "server_id") @ApiModelProperty(value = "ID", hidden = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ApiModelProperty(value = "服务器名称") private String name; @ApiModelProperty(value = "IP") private String ip; @ApiModelProperty(value = "端口") private Integer port; @ApiModelProperty(value = "账号") private String account; @ApiModelProperty(value = "密码") private String password; public void copy(ServerDeploy source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServerDeploy that = (ServerDeploy) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(id, name); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\domain\ServerDeploy.java
2
请完成以下Java代码
public void invokeListener(DelegateListener listener) throws Exception { listener.notify(this); } public boolean hasFailedOnEndListeners() { return false; } // getters / setters ///////////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBusinessKeyWithoutCascade() { return businessKeyWithoutCascade; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; this.businessKeyWithoutCascade = businessKey; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isSkipCustomListeners() { return skipCustomListeners; }
public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMapping; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMapping = skipIoMappings; } public boolean isSkipSubprocesses() { return skipSubprocesses; } public void setSkipSubprocesseses(boolean skipSubprocesses) { this.skipSubprocesses = skipSubprocesses; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(values); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } final EffectiveValuesEvaluatee other = (EffectiveValuesEvaluatee)obj; return values.equals(other.values);
} @Override public String get_ValueAsString(final String variableName) { return values.get(variableName); } @Override public boolean has_Variable(final String variableName) { return values.containsKey(variableName); } @Override public String get_ValueOldAsString(final String variableName) { // TODO Auto-generated method stub return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CachedStringExpression.java
1
请完成以下Java代码
public String getExcelProcessingPage() { return "excel"; } @RequestMapping(method = RequestMethod.POST, value = "/uploadExcelFile") public String uploadFile(Model model, MultipartFile file) throws IOException { InputStream in = file.getInputStream(); File currDir = new File("."); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename(); FileOutputStream f = new FileOutputStream(fileLocation); int ch = 0; while ((ch = in.read()) != -1) { f.write(ch); } f.flush(); f.close(); model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!"); return "excel"; } @RequestMapping(method = RequestMethod.GET, value = "/readPOI") public String readPOI(Model model) throws IOException {
if (fileLocation != null) { if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) { Map<Integer, List<MyCell>> data = excelPOIHelper.readExcel(fileLocation); model.addAttribute("data", data); } else { model.addAttribute("message", "Not a valid excel file!"); } } else { model.addAttribute("message", "File missing! Please upload an excel file."); } return "excel"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java-2\src\main\java\com\baeldung\excel\ExcelController.java
1
请完成以下Java代码
public Criteria andRandomNumNotIn(List<String> values) { addCriterion("random_num not in", values, "randomNum"); return (Criteria) this; } public Criteria andRandomNumBetween(String value1, String value2) { addCriterion("random_num between", value1, value2, "randomNum"); return (Criteria) this; } public Criteria andRandomNumNotBetween(String value1, String value2) { addCriterion("random_num not between", value1, value2, "randomNum"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() {
return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\entity\secondary\ReaderExample.java
1
请完成以下Java代码
public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorVariableName() { return errorVariableName; } public void setErrorVariableName(String errorVariableName) { this.errorVariableName = errorVariableName; } public Boolean getErrorVariableTransient() { return errorVariableTransient; } public void setErrorVariableTransient(Boolean errorVariableTransient) { this.errorVariableTransient = errorVariableTransient; }
public Boolean getErrorVariableLocalScope() { return errorVariableLocalScope; } public void setErrorVariableLocalScope(Boolean errorVariableLocalScope) { this.errorVariableLocalScope = errorVariableLocalScope; } @Override public ErrorEventDefinition clone() { ErrorEventDefinition clone = new ErrorEventDefinition(); clone.setValues(this); return clone; } public void setValues(ErrorEventDefinition otherDefinition) { super.setValues(otherDefinition); setErrorCode(otherDefinition.getErrorCode()); setErrorVariableName(otherDefinition.getErrorVariableName()); setErrorVariableLocalScope(otherDefinition.getErrorVariableLocalScope()); setErrorVariableTransient(otherDefinition.getErrorVariableTransient()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ErrorEventDefinition.java
1
请完成以下Java代码
public Result<?> handlePoolException(PoolException e) { log.error(e.getMessage(), e); addSysLog(e); return Result.error("Redis 连接异常!"); } /** * SQL注入风险,全局异常处理 * * @param exception * @return */ @ExceptionHandler(JeecgSqlInjectionException.class) public Result<?> handleSQLException(Exception exception) { String msg = exception.getMessage().toLowerCase(); final String extractvalue = "extractvalue"; final String updatexml = "updatexml"; boolean hasSensitiveInformation = msg.indexOf(extractvalue) >= 0 || msg.indexOf(updatexml) >= 0; if (msg != null && hasSensitiveInformation) { log.error("校验失败,存在SQL注入风险!{}", msg); return Result.error("校验失败,存在SQL注入风险!"); } addSysLog(exception); return Result.error("校验失败,存在SQL注入风险!" + msg); } /** * 添加异常新系统日志 * @param e 异常 * @author chenrui * @date 2024/4/22 17:16 */ private void addSysLog(Throwable e) { LogDTO log = new LogDTO(); log.setLogType(CommonConstant.LOG_TYPE_4); log.setLogContent(e.getClass().getName()+":"+e.getMessage()); log.setRequestParam(ExceptionUtils.getStackTrace(e)); //获取request HttpServletRequest request = null; try { request = SpringContextUtils.getHttpServletRequest(); } catch (NullPointerException | BeansException ignored) { } if (null != request) { //请求的参数 if (!isTooBigException(e)) { // 文件上传过大异常时不能获取参数,否则会报错 Map<String, String[]> parameterMap = request.getParameterMap(); if(!CollectionUtils.isEmpty(parameterMap)) { log.setMethod(oConvertUtils.mapToString(request.getParameterMap())); } } // 请求地址
log.setRequestUrl(request.getRequestURI()); //设置IP地址 log.setIp(IpUtils.getIpAddr(request)); //设置客户端 if(BrowserUtils.isDesktop(request)){ log.setClientType(ClientTerminalTypeEnum.PC.getKey()); }else{ log.setClientType(ClientTerminalTypeEnum.APP.getKey()); } } //获取登录用户信息 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); if(sysUser!=null){ log.setUserid(sysUser.getUsername()); log.setUsername(sysUser.getRealname()); } baseCommonService.addLog(log); } /** * 是否文件过大异常 * for [QQYUN-11716]上传大图片失败没有精确提示 * @param e * @return * @author chenrui * @date 2025/4/8 20:21 */ private static boolean isTooBigException(Throwable e) { boolean isTooBigException = false; if(e instanceof MultipartException){ Throwable cause = e.getCause(); if (cause instanceof IllegalStateException){ isTooBigException = true; } } if(e instanceof MaxUploadSizeExceededException){ isTooBigException = true; } return isTooBigException; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\exception\JeecgBootExceptionHandler.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DiscretionaryItem.class, CMMN_ELEMENT_DISCRETIONARY_ITEM) .namespaceUri(CMMN11_NS) .extendsType(TableItem.class) .instanceProvider(new ModelTypeInstanceProvider<DiscretionaryItem>() { public DiscretionaryItem newInstance(ModelTypeInstanceContext instanceContext) { return new DiscretionaryItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .idAttributeReference(PlanItemDefinition.class) .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); itemControlChild = sequenceBuilder.element(ItemControl.class) .build(); entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class) .build(); exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DiscretionaryItemImpl.java
1
请完成以下Java代码
public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3 Base URL. @param MSV3_BaseUrl Beispiel: https://msv3-server:443/msv3/v2.0 */ @Override public void setMSV3_BaseUrl (java.lang.String MSV3_BaseUrl) { set_Value (COLUMNNAME_MSV3_BaseUrl, MSV3_BaseUrl); } /** Get MSV3 Base URL. @return Beispiel: https://msv3-server:443/msv3/v2.0 */ @Override public java.lang.String getMSV3_BaseUrl () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_BaseUrl); } /** Set MSV3_Vendor_Config. @param MSV3_Vendor_Config_ID MSV3_Vendor_Config */ @Override public void setMSV3_Vendor_Config_ID (int MSV3_Vendor_Config_ID) { if (MSV3_Vendor_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Vendor_Config_ID, Integer.valueOf(MSV3_Vendor_Config_ID)); } /** Get MSV3_Vendor_Config. @return MSV3_Vendor_Config */ @Override public int getMSV3_Vendor_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Vendor_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); }
/** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Nutzerkennung. @param UserID Nutzerkennung */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } /** * Version AD_Reference_ID=540904 * Reference name: MSV3_Version */ public static final int VERSION_AD_Reference_ID=540904; /** 1 = 1 */ public static final String VERSION_1 = "1"; /** 2 = 2 */ public static final String VERSION_2 = "2"; /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Vendor_Config.java
1
请完成以下Java代码
public void setSpringSecurityContextAttrName(String springSecurityContextAttrName) { Assert.hasText(springSecurityContextAttrName, "springSecurityContextAttrName cannot be null or empty"); this.springSecurityContextAttrName = springSecurityContextAttrName; } /** * If set to true the result of {@link #load(ServerWebExchange)} will use * {@link Mono#cache()} to prevent multiple lookups. * @param cacheSecurityContext true if {@link Mono#cache()} should be used, else * false. */ public void setCacheSecurityContext(boolean cacheSecurityContext) { this.cacheSecurityContext = cacheSecurityContext; } @Override public Mono<Void> save(ServerWebExchange exchange, @Nullable SecurityContext context) { return exchange.getSession().doOnNext((session) -> { if (context == null) { session.getAttributes().remove(this.springSecurityContextAttrName); logger.debug(LogMessage.format("Removed SecurityContext stored in WebSession: '%s'", session));
} else { session.getAttributes().put(this.springSecurityContextAttrName, context); logger.debug(LogMessage.format("Saved SecurityContext '%s' in WebSession: '%s'", context, session)); } }).flatMap(WebSession::changeSessionId); } @Override public Mono<SecurityContext> load(ServerWebExchange exchange) { Mono<SecurityContext> result = exchange.getSession().flatMap((session) -> { SecurityContext context = (SecurityContext) session.getAttribute(this.springSecurityContextAttrName); logger.debug((context != null) ? LogMessage.format("Found SecurityContext '%s' in WebSession: '%s'", context, session) : LogMessage.format("No SecurityContext found in WebSession: '%s'", session)); return Mono.justOrEmpty(context); }); return (this.cacheSecurityContext) ? result.cache() : result; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\context\WebSessionServerSecurityContextRepository.java
1
请完成以下Java代码
public String getDocumentInfo(final DocumentTableFields docFields) { return getSummary(docFields); } @Override public int getDoc_User_ID(final DocumentTableFields docFields) { return extractForecast(docFields).getCreatedBy(); } @Override public int getC_Currency_ID(final DocumentTableFields docFields) { return -1; } @Override public BigDecimal getApprovalAmt(final DocumentTableFields docFields) { return BigDecimal.ZERO; } @Override public File createPDF(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public String completeIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); forecast.setDocAction(IDocument.ACTION_None); return IDocument.STATUS_Completed; } @Override public void approveIt(final DocumentTableFields docFields) { } @Override public void rejectIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void voidIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(forecast.getDocStatus()); if (docStatus.isClosedReversedOrVoided()) { throw new AdempiereException("Document Closed: " + docStatus); } getLines(forecast).forEach(this::voidLine); forecast.setProcessed(true); forecast.setDocAction(IDocument.ACTION_None);
} @Override public void unCloseIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void reverseCorrectIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void reverseAccrualIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void reactivateIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); forecast.setProcessed(false); forecast.setDocAction(IDocument.ACTION_Complete); } @Override public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); return TimeUtil.asLocalDate(forecast.getDatePromised()); } private void voidLine(@NonNull final I_M_ForecastLine line) { line.setQty(BigDecimal.ZERO); line.setQtyCalculated(BigDecimal.ZERO); InterfaceWrapperHelper.save(line); } private List<I_M_ForecastLine> getLines(@NonNull final I_M_Forecast forecast) { return forecastDAO.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\ForecastDocumentHandler.java
1
请完成以下Java代码
private boolean isRelatedToCreatedReturnHUs(@NonNull final I_M_HU_Trx_Line trxLine) { final IHUTrxBL trxBL = Services.get(IHUTrxBL.class); final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class); final I_M_InOutLine inOutLine = trxBL.getReferencedObjectOrNull(trxLine, I_M_InOutLine.class); return inOutLine != null && huInOutBL.isCustomerReturn(inOutLine.getM_InOut()) && trxLine.getM_HU() != null && inOutLine.getReturn_Origin_InOutLine_ID() > 0 && Services.get(IHandlingUnitsBL.class).isVirtual(trxLine.getM_HU()); } private Optional<HUTraceForReturnedQtyRequest> buildRequest(@NonNull final I_M_HU_Trx_Line trxLine) { final I_M_HU returnedVHU = trxLine.getM_HU(); final I_M_InOutLine returnLine = trxBL.getReferencedObjectOrNull(trxLine, I_M_InOutLine.class); final I_M_InOut returnHeader = returnLine.getM_InOut(); final InOutLineId shipmentLineId = InOutLineId.ofRepoId(returnLine.getReturn_Origin_InOutLine_ID()); final Map<InOutLineId, List<I_M_HU>> shippedHUs = huInOutDAO.retrieveShippedHUsByShipmentLineId(ImmutableSet.of(shipmentLineId)); if (Check.isEmpty(shippedHUs.get(shipmentLineId))) { return Optional.empty(); } final Set<HuId> shippedTopLevelHuIds = shippedHUs.get(shipmentLineId) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); final Set<HuId> shippedVHUIds = handlingUnitsBL.getVHUIds(shippedTopLevelHuIds); final ProductId productId = ProductId.ofRepoId(trxLine.getM_Product_ID());
final HuId topLevelReturnedHUId = HuId.ofRepoId(handlingUnitsBL.getTopLevelParent(returnedVHU).getM_HU_ID()); final UomId uomIdToUse = UomId.ofRepoId(CoalesceUtil.firstGreaterThanZero(trxLine.getC_UOM_ID(), returnLine.getC_UOM_ID())); final HUTraceForReturnedQtyRequest addTraceRequest = HUTraceForReturnedQtyRequest.builder() .returnedVirtualHU(returnedVHU) .topLevelReturnedHUId(topLevelReturnedHUId) .sourceShippedVHUIds(shippedVHUIds) .customerReturnId(InOutId.ofRepoId(returnHeader.getM_InOut_ID())) .docStatus(returnHeader.getDocStatus()) .eventTime(Instant.now()) .orgId(OrgId.ofRepoId(returnLine.getAD_Org_ID())) .productId(productId) .qty(Quantitys.of(trxLine.getQty(), uomIdToUse)) .build(); return Optional.of(addTraceRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CreateReturnedHUsTrxListener.java
1
请完成以下Java代码
public final class DocumentFieldAsProcessInstanceParameter implements IProcessInstanceParameter { public static DocumentFieldAsProcessInstanceParameter of(final IDocumentFieldView documentField) { return new DocumentFieldAsProcessInstanceParameter(documentField); } private final IDocumentFieldView documentField; private DocumentFieldAsProcessInstanceParameter(@NonNull final IDocumentFieldView documentField) { this.documentField = documentField; } @Override public String getParameterName() { return documentField.getFieldName(); } @Override public DocumentFieldWidgetType getWidgetType() { return documentField.getWidgetType(); } @Override public OptionalInt getMinPrecision() { return documentField.getMinPrecision(); } @Override public Object getValueAsJsonObject(final JSONOptions jsonOpts) { return documentField.getValueAsJsonObject(jsonOpts); } @Override public LogicExpressionResult getReadonly() { return documentField.getReadonly(); } @Override public LogicExpressionResult getMandatory() { return documentField.getMandatory(); }
@Override public LogicExpressionResult getDisplayed() { return documentField.getDisplayed(); } @Override public DocumentValidStatus getValidStatus() { return documentField.getValidStatus(); } @Override public DeviceDescriptorsList getDevices() { return documentField.getDescriptor() .getDeviceDescriptorsProvider() .getDeviceDescriptors(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\DocumentFieldAsProcessInstanceParameter.java
1