instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public UserQuery userLastName(String lastName) { this.lastName = lastName; return this; } public UserQuery userLastNameLike(String lastNameLike) { ensureNotNull("Provided lastNameLike", lastNameLike); this.lastNameLike = lastNameLike; return this; } public UserQuery userEmail(String email) { this.email = email; return this; } public UserQuery userEmailLike(String emailLike) { ensureNotNull("Provided emailLike", emailLike); this.emailLike = emailLike; return this; } public UserQuery memberOfGroup(String groupId) { ensureNotNull("Provided groupId", groupId); this.groupId = groupId; return this; } public UserQuery potentialStarter(String procDefId) { ensureNotNull("Provided processDefinitionId", procDefId); this.procDefId = procDefId; return this; } public UserQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId; return this; } //sorting ////////////////////////////////////////////////////////// public UserQuery orderByUserId() { return orderBy(UserQueryProperty.USER_ID); } public UserQuery orderByUserEmail() { return orderBy(UserQueryProperty.EMAIL); } public UserQuery orderByUserFirstName() { return orderBy(UserQueryProperty.FIRST_NAME); } public UserQuery orderByUserLastName() { return orderBy(UserQueryProperty.LAST_NAME); } //getters ////////////////////////////////////////////////////////// public String getId() {
return id; } public String[] getIds() { return ids; } public String getFirstName() { return firstName; } public String getFirstNameLike() { return firstNameLike; } public String getLastName() { return lastName; } public String getLastNameLike() { return lastNameLike; } public String getEmail() { return email; } public String getEmailLike() { return emailLike; } public String getGroupId() { return groupId; } public String getTenantId() { return tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override public void onParameterChanged(final String parameterName) { if (PARAM_AD_ORG_TARGET_ID.equals(parameterName) || PARAM_DATE_ORG_CHANGE.equals(parameterName)) { if (p_orgTargetId == null) { return; }
final BPartnerId partnerId = BPartnerId.ofRepoId(getRecord_ID()); final Instant orgChangeDate = CoalesceUtil.coalesce(p_startDate, SystemTime.asInstant()); final OrgChangeBPartnerComposite orgChangePartnerComposite = service.getByIdAndOrgChangeDate(partnerId, orgChangeDate); isShowMembershipParameter = orgChangePartnerComposite.hasMembershipSubscriptions() && service.hasAnyMembershipProduct(p_orgTargetId); final GroupCategoryId groupCategoryId = orgChangePartnerComposite.getGroupCategoryId(); if (groupCategoryId != null && service.isGroupCategoryContainsProductsInTargetOrg(groupCategoryId, p_orgTargetId)) { p_groupCategoryId = groupCategoryId; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_MoveToAnotherOrg_ProcessHelper.java
1
请完成以下Java代码
protected void clearContext(HttpServletRequest request) { SecurityContextHolder.clearContext(); try { request.getSession().invalidate(); } catch (Exception ignored) { } } protected void authorizeToken(OAuth2AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) { // @formatter:off var authRequest = OAuth2AuthorizeRequest .withClientRegistrationId(token.getAuthorizedClientRegistrationId()) .principal(token) .attributes(attrs -> { attrs.put(HttpServletRequest.class.getName(), request); attrs.put(HttpServletResponse.class.getName(), response); }).build(); // @formatter:on
var name = token.getName(); try { var res = clientManager.authorize(authRequest); if (res == null || hasTokenExpired(res.getAccessToken())) { logger.warn("Authorize failed for '{}': could not re-authorize expired access token", name); clearContext(request); } else { logger.debug("Authorize successful for '{}', access token expiry: {}", name, res.getAccessToken().getExpiresAt()); } } catch (OAuth2AuthorizationException e) { logger.warn("Authorize failed for '{}': {}", name, e.getMessage()); clearContext(request); } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\AuthorizeTokenFilter.java
1
请完成以下Java代码
public class ElementReferenceCollectionBuilderImpl<Target extends ModelElementInstance, Source extends ModelElementInstance> implements ElementReferenceCollectionBuilder<Target, Source> { private final Class<Source> childElementType; private final Class<Target> referenceTargetClass; protected ElementReferenceCollectionImpl<Target, Source> elementReferenceCollectionImpl; public ElementReferenceCollectionBuilderImpl(Class<Source> childElementType, Class<Target> referenceTargetClass, ChildElementCollectionImpl<Source> collection) { this.childElementType = childElementType; this.referenceTargetClass = referenceTargetClass; this.elementReferenceCollectionImpl = new ElementReferenceCollectionImpl<Target, Source>(collection); } public ElementReferenceCollection<Target, Source> build() { return elementReferenceCollectionImpl; } @SuppressWarnings("unchecked") public void performModelBuild(Model model) {
ModelElementTypeImpl referenceTargetType = (ModelElementTypeImpl) model.getType(referenceTargetClass); ModelElementTypeImpl referenceSourceType = (ModelElementTypeImpl) model.getType(childElementType); elementReferenceCollectionImpl.setReferenceTargetElementType(referenceTargetType); elementReferenceCollectionImpl.setReferenceSourceElementType(referenceSourceType); // the referenced attribute may be declared on a base type of the referenced type. AttributeImpl<String> idAttribute = (AttributeImpl<String>) referenceTargetType.getAttribute("id"); if (idAttribute != null) { idAttribute.registerIncoming(elementReferenceCollectionImpl); elementReferenceCollectionImpl.setReferenceTargetAttribute(idAttribute); } else { throw new ModelException("Unable to find id attribute of " + referenceTargetClass); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceCollectionBuilderImpl.java
1
请完成以下Java代码
public class C_Invoice_Candidate_Update_HeaderAggKeys extends JavaProcess { final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); @Override protected void prepare() { // nothing to do } @Override protected String doIt() throws Exception { int counter = 0; final Iterator<I_C_Invoice_Candidate> unprocessedCands = invoiceCandDAO.retrieveNonProcessed(new PlainContextAware(getCtx(), ITrx.TRXNAME_None)); try (final IAutoCloseable updateInProgressCloseable = invoiceCandBL.setUpdateProcessInProgress())
{ for (final I_C_Invoice_Candidate ic : IteratorUtils.asIterable(unprocessedCands)) { Services.get(IAggregationBL.class) .getUpdateProcessor() .process(ic); // disable the model validation engine for this PO to gain performance InterfaceWrapperHelper.setDynAttribute(ic, ModelValidationEngine.DYNATTR_DO_NOT_INVOKE_ON_MODEL_CHANGE, true); InterfaceWrapperHelper.save(ic); counter++; } } return "@Updated@ " + counter + " @C_Invoice_Candidate@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_Update_HeaderAggKeys.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException { return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name) .getPO(getM_PromotionGroup_ID(), get_TrxName()); } /** Set Promotion Group. @param M_PromotionGroup_ID Promotion Group */ public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID)); } /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Group Line. @param M_PromotionGroupLine_ID Promotion Group Line */ public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID)
{ if (M_PromotionGroupLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID)); } /** Get Promotion Group Line. @return Promotion Group Line */ public int getM_PromotionGroupLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroupLine.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getPollingFrequency() { return this.pollingFrequency; } public void setPollingFrequency(Duration pollingFrequency) { this.pollingFrequency = pollingFrequency; } public Duration getStep() { return this.step; } public void setStep(Duration step) { this.step = step; } public boolean isPublishUnchangedMeters() {
return this.publishUnchangedMeters; } public void setPublishUnchangedMeters(boolean publishUnchangedMeters) { this.publishUnchangedMeters = publishUnchangedMeters; } public boolean isBuffered() { return this.buffered; } public void setBuffered(boolean buffered) { this.buffered = buffered; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdProperties.java
2
请完成以下Spring Boot application配置
# configurations for AWS SDK consumer and producer aws.access.key=my-aws-access-key-goes-here aws.secret.key=my-aws-secret-key-goes-here ips.partition.key=ips-partition-key ips.stream=ips-stream ips.shard.id=1 # configurations for Spring Cloud Stream Kineses Binder consumer and producer cloud.aws.credentials.access-key=my-aws-access-key cloud.aws.credentials.secret-key=my-aws-secret-key cloud.aws.region.static=eu-central-1 cloud.aws.stack.auto=false spring.cloud.stream.bindings.input-in-0.destination=live-ips spring.cloud.stream.bindings.input-in-0.group=live-ips-group spring.cloud.stream.binding
s.input-in-0.content-type=text/plain spring.cloud.stream.function.definition = input spring.cloud.stream.bindings.output-out-0.destination=myStream spring.cloud.stream.bindings.output-out-0.content-type=text/plain spring.cloud.stream.poller.fixed-delay = 3000
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kinesis\src\main\resources\application.properties
2
请完成以下Java代码
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getExecutionId() { return executionId; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean iswithException() { return withJobException; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } public boolean isOnlyChildExecutions() { return onlyChildExecutions;
} public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @ApiModelProperty(example = "myCfg") public String getJobHandlerConfiguration() { return jobHandlerConfiguration; } public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } @ApiModelProperty(example = "myAdvancedCfg") public String getAdvancedJobHandlerConfiguration() { return advancedJobHandlerConfiguration; } public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) { this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration; } @ApiModelProperty(example = "custom value") public String getCustomValues() { return customValues; } public void setCustomValues(String customValues) {
this.customValues = customValues; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java
2
请完成以下Java代码
private Quantity getStorageQty(final I_M_HU actualPickedHU) { return handlingUnitsBL.getStorageFactory() .getStorage(actualPickedHU) .getQuantity(schedule.getProductId()) .orElseThrow(() -> new AdempiereException("No storage found for " + actualPickedHU)); } private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) { return hus.stream().map(hu -> HuId.ofRepoId(hu.getM_HU_ID())).collect(ImmutableSet.toImmutableSet()); } private List<I_M_HU> splitOutOfPickFromHU(final DDOrderMoveSchedule schedule) { // Atm we always take top level HUs // TODO: implement TU level support if (!HuId.equals(huIdToPick, schedule.getPickFromHUId())) { throw new AdempiereException("HU not matching the scheduled one"); } final I_M_HU pickFromHU = handlingUnitsBL.getById(huIdToPick); return ImmutableList.of(pickFromHU); } private MovementId createPickFromMovement(@NonNull final Set<HuId> huIdsToMove) { final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate)
.fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(getInTransitLocatorId()) .huIdsToMove(huIdsToMove) .build(); return new HUMovementGenerator(request) .createMovement() .getSingleMovementLineId() .getMovementId(); } private LocatorId getInTransitLocatorId() { if (inTransitLocatorIdEffective == null) { inTransitLocatorIdEffective = computeInTransitLocatorId(); } return inTransitLocatorIdEffective; } private LocatorId computeInTransitLocatorId() { if (inTransitLocatorId != null) { return inTransitLocatorId; } final WarehouseId warehouseInTransitId = WarehouseId.ofRepoId(ddOrder.getM_Warehouse_ID()); return warehouseBL.getOrCreateDefaultLocatorId(warehouseInTransitId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\pick_from\DDOrderPickFromCommand.java
1
请完成以下Java代码
public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; }
public void setRole(String role) { this.role = role; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\User.java
1
请完成以下Java代码
public AppDefinitionEntity findAppDefinitionByKeyAndVersionAndTenantId(String appDefinitionKey, Integer appDefinitionVersion, String tenantId) { Map<String, Object> params = new HashMap<>(); params.put("appDefinitionKey", appDefinitionKey); params.put("appDefinitionVersion", appDefinitionVersion); params.put("tenantId", tenantId); List<AppDefinitionEntity> results = getDbSqlSession().selectList("selectAppDefinitionsByKeyAndVersionAndTenantId", params); if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { throw new FlowableException("There are " + results.size() + " app definitions with key = '" + appDefinitionKey + "' and version = '" + appDefinitionVersion + "'."); } return null; } @Override public void updateAppDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateAppDefinitionTenantIdForDeploymentId", params); } @Override @SuppressWarnings("unchecked") public List<AppDefinition> findAppDefinitionsByQueryCriteria(AppDefinitionQueryImpl appDefinitionQuery) { return getDbSqlSession().selectList("selectAppDefinitionsByQueryCriteria", appDefinitionQuery); } @Override public long findAppDefinitionCountByQueryCriteria(AppDefinitionQueryImpl appDefinitionQuery) { return (Long) getDbSqlSession().selectOne("selectAppDefinitionCountByQueryCriteria", appDefinitionQuery); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\data\impl\MybatisAppDefinitionDataManager.java
1
请完成以下Java代码
public Integer getRetries() { return retries; } public String getErrorMessage() { return errorMessage; } public String getActivityId() { return activityId; } public String getActivityInstanceId() { return activityInstanceId; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getTenantId() { return tenantId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; }
public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId(); result.timestamp = historicExternalTaskLog.getTimestamp(); result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries(); result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请完成以下Java代码
public final class ObjectUtils { /** * 判读是否是复杂对象 * 如果是:(Boolean, Character, Byte, Short, Integer, Long, Float, Double, String)返回true * * @param target * @return */ public static boolean isComplexObject(Object target) { if (Objects.isNull(target)) { return false; } if (target instanceof String) { return true; } if (target instanceof Integer) { return true; } if (target instanceof Long) { return true; } if (target instanceof Boolean) { return true; } if (target instanceof Float) { return true; } if (target instanceof Double) { return true;
} if (target instanceof Byte) { return true; } if (target instanceof Short) { return true; } if (target instanceof Character) { return true; } return false; } public static boolean isArray(Object obj) { return (obj != null && obj.getClass().isArray()); } }
repos\spring-boot-student-master\spring-boot-student-okhttp\src\main\java\com\xiaolyuh\util\ObjectUtils.java
1
请完成以下Java代码
public void setISO_Code (final java.lang.String ISO_Code) { set_Value (COLUMNNAME_ISO_Code, ISO_Code); } @Override public java.lang.String getISO_Code() { return get_ValueAsString(COLUMNNAME_ISO_Code); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPriceStd (final BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } @Override public BigDecimal getPriceStd() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPricingSystem_Value (final @Nullable java.lang.String PricingSystem_Value) { set_Value (COLUMNNAME_PricingSystem_Value, PricingSystem_Value); } @Override public java.lang.String getPricingSystem_Value() { return get_ValueAsString(COLUMNNAME_PricingSystem_Value); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() {
return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java
1
请在Spring Boot框架中完成以下Java代码
public void setOrder(int order) { this.order = order; } @Override public int getOrder() { return this.order; } @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } @Autowired(required = false) public void setJobRegistry(JobRegistry jobRegistry) { this.jobRegistry = jobRegistry; } public void setJobName(String jobName) { this.jobName = jobName; } @Autowired(required = false) public void setJobParametersConverter(JobParametersConverter converter) { this.converter = converter; } @Autowired(required = false) public void setJobs(Collection<Job> jobs) { this.jobs = jobs; } @Override public void run(ApplicationArguments args) throws Exception { String[] jobArguments = args.getNonOptionArgs().toArray(new String[0]); run(jobArguments); } public void run(String... args) throws JobExecutionException { logger.info("Running default command line with: " + Arrays.asList(args)); Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "="); launchJobFromProperties((properties != null) ? properties : new Properties()); } protected void launchJobFromProperties(Properties properties) throws JobExecutionException { JobParameters jobParameters = this.converter.getJobParameters(properties);
executeLocalJobs(jobParameters); executeRegisteredJobs(jobParameters); } private boolean isLocalJob(String jobName) { return this.jobs.stream().anyMatch((job) -> job.getName().equals(jobName)); } private boolean isRegisteredJob(String jobName) { return this.jobRegistry != null && this.jobRegistry.getJobNames().contains(jobName); } private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException { for (Job job : this.jobs) { if (StringUtils.hasText(this.jobName)) { if (!this.jobName.equals(job.getName())) { logger.debug(LogMessage.format("Skipped job: %s", job.getName())); continue; } } execute(job, jobParameters); } } private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException { if (this.jobRegistry != null && StringUtils.hasText(this.jobName)) { if (!isLocalJob(this.jobName)) { Job job = this.jobRegistry.getJob(this.jobName); Assert.notNull(job, () -> "No job found with name '" + this.jobName + "'"); execute(job, jobParameters); } } } protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, InvalidJobParametersException { JobExecution execution = this.jobOperator.start(job, jobParameters); if (this.publisher != null) { this.publisher.publishEvent(new JobExecutionEvent(execution)); } } }
repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\JobLauncherApplicationRunner.java
2
请完成以下Java代码
public boolean isAvailableToWork() { return this.executor.hasAvailablePermits(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("executor", executor) .toString(); } @Override public void shutdownExecutor() { shutdownLock.lock(); try { shutdown0(); } finally { shutdownLock.unlock(); } } @Override protected void executeTask(@NonNull final WorkpackageProcessorTask task) { logger.debug("Going to submit task={} to executor={}", task, executor); executor.execute(task); logger.debug("Done submitting task"); } private void shutdown0() { logger.info("shutdown - Shutdown started for executor={}", executor); executor.shutdown(); int retryCount = 5;
boolean terminated = false; while (!terminated && retryCount > 0) { logger.info("shutdown - waiting for executor to be terminated; retries left={}; executor={}", retryCount, executor); try { terminated = executor.awaitTermination(5 * 1000, TimeUnit.MICROSECONDS); } catch (final InterruptedException e) { logger.warn("Failed shutting down executor for " + name + ". Retry " + retryCount + " more times."); terminated = false; } retryCount--; } executor.shutdownNow(); logger.info("Shutdown finished"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\ThreadPoolQueueProcessor.java
1
请完成以下Java代码
public class RegexUtils { public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); private static final ConcurrentMap<String, Pattern> patternsCache = new ConcurrentReferenceHashMap<>(16, SOFT); public static String replace(String s, Pattern pattern, UnaryOperator<String> replacer) { return pattern.matcher(s).replaceAll(matchResult -> { return replacer.apply(matchResult.group()); }); } public static String replace(String input, @Language("regexp") String pattern, Function<MatchResult, String> replacer) { return patternsCache.computeIfAbsent(pattern, Pattern::compile).matcher(input).replaceAll(replacer); }
public static boolean matches(String input, Pattern pattern) { return pattern.matcher(input).matches(); } public static String getMatch(String input, Pattern pattern, int group) { Matcher matcher = pattern.matcher(input); if (matcher.find()) { try { return matcher.group(group); } catch (Exception ignored) {} } return null; } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\RegexUtils.java
1
请完成以下Java代码
public Integer getSubjectCount() { return subjectCount; } public void setSubjectCount(Integer subjectCount) { this.subjectCount = subjectCount; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", icon=").append(icon); sb.append(", subjectCount=").append(subjectCount); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectCategory.java
1
请完成以下Java代码
protected Object evaluateScriptRequest(ScriptEngineRequest.Builder requestBuilder) { ScriptEngineRequest request = requestBuilder.build(); Object result = evaluateScript(getScriptingEngines(), request); if (resultVariable != null) { VariableContainer variableContainer = request.getScopeContainer(); String resultVariable = Objects.toString(this.resultVariable.getValue(variableContainer), null); if (variableContainer != null && resultVariable != null) { variableContainer.setVariable(resultVariable, result); } } return result; } protected Object evaluateScript(ScriptingEngines scriptingEngines, ScriptEngineRequest request) { return scriptingEngines.evaluate(request).getResult(); } protected void validateParameters() { if (script == null) { throw new FlowableIllegalStateException("The field 'script' should be set on " + getClass().getSimpleName()); } if (language == null) { throw new FlowableIllegalStateException("The field 'language' should be set on " + getClass().getSimpleName()); } } protected abstract ScriptingEngines getScriptingEngines(); public void setScript(String script) { this.script = script; }
/** * Sets the script as Expression for backwards compatibility. * Requires to for 'field' injection of scripts. * Expression is not evaluated */ public void setScript(Expression script) { this.script = script.getExpressionText(); } public String getScript() { return script; } public void setLanguage(Expression language) { this.language = language; } public void setResultVariable(Expression resultVariable) { this.resultVariable = resultVariable; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\AbstractScriptEvaluator.java
1
请完成以下Java代码
public static String getPackPath(Object object) { // 检查用户传入的参数是否为空 if (object == null) { throw new java.lang.IllegalArgumentException("参数不能为空!"); } // 获得类的全名,包括包名 String clsName = object.getClass().getName(); return clsName; } public static String getAppPath(Class cls) { // 检查用户传入的参数是否为空 if (cls == null) { throw new java.lang.IllegalArgumentException("参数不能为空!"); } ClassLoader loader = cls.getClassLoader(); // 获得类的全名,包括包名 String clsName = cls.getName() + ".class"; // 获得传入参数所在的包 Package pack = cls.getPackage(); String path = ""; // 如果不是匿名包,将包名转化为路径 if (pack != null) { String packName = pack.getName(); String javaSpot="java."; String javaxSpot="javax."; // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库 if (packName.startsWith(javaSpot) || packName.startsWith(javaxSpot)) { throw new java.lang.IllegalArgumentException("不要传送系统类!"); } // 在类的名称中,去掉包名的部分,获得类的文件名 clsName = clsName.substring(packName.length() + 1); // 判定包名是否是简单包名,如果是,则直接将包名转换为路径, if (packName.indexOf(SymbolConstant.SPOT) < 0) { path = packName + "/"; } else { // 否则按照包名的组成部分,将包名转换为路径 int start = 0, end = 0; end = packName.indexOf("."); StringBuilder pathBuilder = new StringBuilder(); while (end != -1) { pathBuilder.append(packName, start, end).append("/"); start = end + 1; end = packName.indexOf(".", start); } if(oConvertUtils.isNotEmpty(pathBuilder.toString())){ path = pathBuilder.toString(); } path = path + packName.substring(start) + "/"; } } // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名 java.net.URL url = loader.getResource(path + clsName); // 从URL对象中获取路径信息 String realPath = url.getPath();
// 去掉路径信息中的协议名"file:" int pos = realPath.indexOf("file:"); if (pos > -1) { realPath = realPath.substring(pos + 5); } // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径 pos = realPath.indexOf(path + clsName); realPath = realPath.substring(0, pos - 1); // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名 if (realPath.endsWith(SymbolConstant.EXCLAMATORY_MARK)) { realPath = realPath.substring(0, realPath.lastIndexOf("/")); } /*------------------------------------------------------------ ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要 的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的 中文及空格路径 -------------------------------------------------------------*/ try { realPath = java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } return realPath; }// getAppPath定义结束 }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\MyClassLoader.java
1
请完成以下Java代码
public EntityImpl update(EntityImpl entity) { return update(entity, true); } @Override public EntityImpl update(EntityImpl entity, boolean fireUpdateEvent) { EntityImpl updatedEntity = getDataManager().update(entity); if (fireUpdateEvent && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, entity) ); } return updatedEntity; } @Override public void delete(String id) { EntityImpl entity = findById(id); delete(entity); } @Override public void delete(EntityImpl entity) { delete(entity, true); } @Override public void delete(EntityImpl entity, boolean fireDeleteEvent) { getDataManager().delete(entity); if (fireDeleteEvent && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, entity) ); } } protected abstract DataManager<EntityImpl> getDataManager(); /* Execution related entity count methods */ protected boolean isExecutionRelatedEntityCountEnabledGlobally() { return processEngineConfiguration.getPerformanceSettings().isEnableExecutionRelationshipCounts(); }
protected boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) { if (executionEntity instanceof CountingExecutionEntity) { return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity); } return false; } protected boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) { /* * There are two flags here: a global flag and a flag on the execution entity. * The global flag can be switched on and off between different reboots, * however the flag on the executionEntity refers to the state at that particular moment. * * Global flag / ExecutionEntity flag : result * * T / T : T (all true, regular mode with flags enabled) * T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled) * F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will be done) * F / F : F (all disabled) * * From this table it is clear that only when both are true, the result should be true, * which is the regular AND rule for booleans. */ return isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntityManager.java
1
请完成以下Java代码
public boolean isWithoutTenantId() { return withoutTenantId; } public String getEngineVersion() { return engineVersion; } public String getDerivedFrom() { return derivedFrom; } public String getParentDeploymentId() { return parentDeploymentId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public String getCategoryLike() { return categoryLike; } public String getKey() { return key;
} public String getKeyLike() { return keyLike; } public String getParentDeploymentIdLike() { return parentDeploymentIdLike; } public List<String> getParentDeploymentIds() { return parentDeploymentIds; } public boolean isLatest() { return latest; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
public static @Nullable String getVersion() { Package pkg = SpringSecurityCoreVersion.class.getPackage(); return (pkg != null) ? pkg.getImplementationVersion() : null; } /** * Disable if springVersion and springSecurityVersion are the same to allow working * with Uber Jars. * @param springVersion * @param springSecurityVersion * @return */ private static boolean disableChecks(@Nullable String springVersion, @Nullable String springSecurityVersion) { if (springVersion == null || springVersion.equals(springSecurityVersion)) { return true; } return Boolean.getBoolean(DISABLE_CHECKS); }
/** * Loads the spring version or null if it cannot be found. * @return */ private static @Nullable String getSpringVersion() { Properties properties = new Properties(); try (InputStream is = SpringSecurityCoreVersion.class.getClassLoader() .getResourceAsStream("META-INF/spring-security.versions")) { properties.load(is); } catch (IOException | NullPointerException ex) { return null; } return properties.getProperty("org.springframework:spring-core"); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\SpringSecurityCoreVersion.java
1
请完成以下Java代码
public int getDoc_User_ID() { return getAD_User_ID(); } @Override public int getC_Currency_ID() { final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID()); return pl.getC_Currency_ID(); } /** * Get Document Approval Amount * * @return amount */ @Override public BigDecimal getApprovalAmt() { return getTotalLines(); } private String getUserName() {
return Services.get(IUserDAO.class).retrieveUserOrNull(getCtx(), getAD_User_ID()).getName(); } /** * @return true if CO, CL or RE */ public boolean isComplete() { final String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisition.java
1
请完成以下Java代码
protected boolean isPersistenceConnectionError(Throwable throwable) { boolean isPersistenceException = (throwable instanceof ProcessEnginePersistenceException); if (!isPersistenceException) { return false; } SQLException sqlException = getSqlException((ProcessEnginePersistenceException) throwable); if (sqlException == null) { return false; } String sqlState = sqlException.getSQLState(); return sqlState != null && sqlState.startsWith(PERSISTENCE_CONNECTION_ERROR_CLASS);
} protected SQLException getSqlException(ProcessEnginePersistenceException e) { boolean hasTwoCauses = e.getCause() != null && e.getCause().getCause() != null; if (!hasTwoCauses) { return null; } Throwable cause = e.getCause().getCause(); return cause instanceof SQLException ? (SQLException) cause : null; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\exception\ExceptionLogger.java
1
请完成以下Java代码
public final ET compile(final ExpressionContext context, @Nullable final String expressionStr) { // Check if it's an empty expression // NOTE: we are preserving all whitespaces from expressions, so that's why we are not trimming the string if (expressionStr == null || expressionStr.isEmpty()) { return getNullExpression(); } String inStr = expressionStr; int i = inStr.indexOf(PARAMETER_TAG); if (i < 0) { return createConstantExpression(context, expressionStr); } final List<Object> chunks = new ArrayList<>(); while (i != -1) { // up to first parameter marker if (i > 0) { final String chunk = inStr.substring(0, i); chunks.add(chunk); } else { // expression is starting with a parameter // nothing to do here } inStr = inStr.substring(i + PARAMETER_TAG_LENGTH); // from first marker final int j = inStr.indexOf(PARAMETER_TAG); // next parameter marker if (j < 0) { // no second tag throw new ExpressionCompileException("Missing closing tag " + PARAMETER_TAG + " in currentSubstring") .appendParametersToMessage() .setParameter("currentSubstring", inStr) .setParameter("expressionString", expressionStr); } else if (j == 0) { // Double marker (e.g. @@) // => consider it's an escaped marker, so append "@" only chunks.add(PARAMETER_TAG); } else {
// Parameter final String token = inStr.substring(0, j); final CtxName parameter = CtxNames.parse(token); chunks.add(parameter); } inStr = inStr.substring(j + PARAMETER_TAG_LENGTH); // from second @ to end i = inStr.indexOf(PARAMETER_TAG); } // Add the remaining chunk, if any if (!inStr.isEmpty()) { chunks.add(inStr); } // // Case: if we are dealing with a string expression which actually it's one parameter binding, no strings before, no strings after // then we have a specialized implementation for that if (chunks.size() == 1 && chunks.get(0) instanceof CtxName) { final CtxName parameter = (CtxName)chunks.get(0); return createSingleParamaterExpression(context, expressionStr, parameter); } return createGeneralExpression(context, expressionStr, chunks); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\AbstractChunkBasedExpressionCompiler.java
1
请完成以下Java代码
public void afterPropertiesSet() throws Exception { Map<String, JobAlarm> serviceBeanMap = applicationContext.getBeansOfType(JobAlarm.class); if (serviceBeanMap != null && serviceBeanMap.size() > 0) { jobAlarmList = new ArrayList<JobAlarm>(serviceBeanMap.values()); } } /** * job alarm * * @param info * @param jobLog * @return */ public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) { boolean result = false; if (jobAlarmList!=null && jobAlarmList.size()>0) { result = true; // success means all-success
for (JobAlarm alarm: jobAlarmList) { boolean resultItem = false; try { resultItem = alarm.doAlarm(info, jobLog); } catch (Exception e) { logger.error(e.getMessage(), e); } if (!resultItem) { result = false; } } } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\alarm\JobAlarmer.java
1
请完成以下Java代码
public String getHandledTableName() { return I_M_ForecastLine.Table_Name; } @Override @NonNull public Dimension getFromRecord(@NonNull final I_M_ForecastLine record) { return Dimension.builder() .projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID())) .campaignId(record.getC_Campaign_ID()) .activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID())) .userElementString1(record.getUserElementString1()) .userElementString2(record.getUserElementString2()) .userElementString3(record.getUserElementString3()) .userElementString4(record.getUserElementString4()) .userElementString5(record.getUserElementString5()) .userElementString6(record.getUserElementString6()) .userElementString7(record.getUserElementString7()) .build(); }
@Override public void updateRecord(final I_M_ForecastLine record, final Dimension from) { record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId())); record.setC_Campaign_ID(from.getCampaignId()); record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId())); record.setUserElementString1(from.getUserElementString1()); record.setUserElementString2(from.getUserElementString2()); record.setUserElementString3(from.getUserElementString3()); record.setUserElementString4(from.getUserElementString4()); record.setUserElementString5(from.getUserElementString5()); record.setUserElementString6(from.getUserElementString6()); record.setUserElementString7(from.getUserElementString7()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\ForecastLineDimensionFactory.java
1
请在Spring Boot框架中完成以下Java代码
public static MultiQueryRequest buildUpdatedAfterQueryRequest(@NonNull final String updatedAfter, @NonNull final PageAndLimit pageAndLimitValues) { return MultiQueryRequest.builder() .filter(buildUpdatedAfterJsonQueries(updatedAfter)) .limit(pageAndLimitValues.getLimit()) .page(pageAndLimitValues.getPageIndex()) .build(); } @NonNull public MultiQueryRequest buildShopware6QueryRequest(@NonNull final JsonExternalSystemRequest request, @NonNull final PageAndLimit pageAndLimitValues) { final List<JsonQuery> queries = buildLookUpSpecificOrderQuery(request); if (!Check.isEmpty(queries)) { return MultiQueryRequest.builder() .filter(JsonQuery.builder() .queryType(QueryType.MULTI) .operatorType(OperatorType.AND) .jsonQueries(queries) .build()) .limit(pageAndLimitValues.getLimit()) .page(pageAndLimitValues.getPageIndex()) .build(); } else { final String updatedAfterOverride = request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE); final String updatedAfter = CoalesceUtil.coalesceNotNull( updatedAfterOverride, request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER), Instant.ofEpochSecond(0).toString()); return buildUpdatedAfterQueryRequest(updatedAfter, pageAndLimitValues); } } public boolean shouldIgnoreNextImportTimestamp(@NonNull final JsonExternalSystemRequest externalSystemRequest) { final String orderId = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_ORDER_ID); final String orderNo = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_ORDER_NO); final String updatedAfterOverride = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE); return Stream.of(orderId, orderNo, updatedAfterOverride)
.anyMatch(Check::isNotBlank); } @NonNull private ImmutableList<JsonQuery> buildLookUpSpecificOrderQuery(@NonNull final JsonExternalSystemRequest request) { final ImmutableList.Builder<JsonQuery> getSpecificOrderQuery = ImmutableList.builder(); final String orderId = request.getParameters().get(ExternalSystemConstants.PARAM_ORDER_ID); if (Check.isNotBlank(orderId)) { getSpecificOrderQuery.add(buildEqualsJsonQuery(FIELD_ORDER_ID, orderId)); } final String orderNo = request.getParameters().get(ExternalSystemConstants.PARAM_ORDER_NO); if (Check.isNotBlank(orderNo)) { getSpecificOrderQuery.add(buildEqualsJsonQuery(FIELD_ORDER_NUMBER, orderNo)); } return getSpecificOrderQuery.build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\OrderQueryHelper.java
2
请完成以下Java代码
public List<HttpStatus> getStatuses() { return statuses; } public RetryConfig setStatuses(HttpStatus... statuses) { this.statuses = Arrays.asList(statuses); return this; } public List<HttpMethod> getMethods() { return methods; } public RetryConfig setMethods(HttpMethod... methods) { this.methods = Arrays.asList(methods); return this; } public List<Class<? extends Throwable>> getExceptions() { return exceptions; } public RetryConfig setExceptions(Class<? extends Throwable>... exceptions) { this.exceptions = Arrays.asList(exceptions); return this; } } public static class BackoffConfig { private Duration firstBackoff = Duration.ofMillis(5); private @Nullable Duration maxBackoff; private int factor = 2; private boolean basedOnPreviousValue = true; public BackoffConfig() { } public BackoffConfig(Duration firstBackoff, Duration maxBackoff, int factor, boolean basedOnPreviousValue) { this.firstBackoff = firstBackoff; this.maxBackoff = maxBackoff; this.factor = factor; this.basedOnPreviousValue = basedOnPreviousValue; } public void validate() { Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present"); } public Duration getFirstBackoff() { return firstBackoff; } public void setFirstBackoff(Duration firstBackoff) { this.firstBackoff = firstBackoff; } public @Nullable Duration getMaxBackoff() { return maxBackoff; } public void setMaxBackoff(Duration maxBackoff) { this.maxBackoff = maxBackoff; }
public int getFactor() { return factor; } public void setFactor(int factor) { this.factor = factor; } public boolean isBasedOnPreviousValue() { return basedOnPreviousValue; } public void setBasedOnPreviousValue(boolean basedOnPreviousValue) { this.basedOnPreviousValue = basedOnPreviousValue; } @Override public String toString() { return new ToStringCreator(this).append("firstBackoff", firstBackoff) .append("maxBackoff", maxBackoff) .append("factor", factor) .append("basedOnPreviousValue", basedOnPreviousValue) .toString(); } } public static class JitterConfig { private double randomFactor = 0.5; public void validate() { Assert.isTrue(randomFactor >= 0 && randomFactor <= 1, "random factor must be between 0 and 1 (default 0.5)"); } public JitterConfig() { } public JitterConfig(double randomFactor) { this.randomFactor = randomFactor; } public double getRandomFactor() { return randomFactor; } public void setRandomFactor(double randomFactor) { this.randomFactor = randomFactor; } @Override public String toString() { return new ToStringCreator(this).append("randomFactor", randomFactor).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java
1
请完成以下Java代码
private static ProductId extractProductId(final @NonNull I_M_Cost record) { return ProductId.ofRepoId(record.getM_Product_ID()); } @NonNull private CostElement extractCostElement(final @NonNull I_M_Cost record) { return costElementCache.computeIfAbsent(extractCostElementId(record), costElementRepo::getById); } @NonNull private static CostElementId extractCostElementId(final @NonNull I_M_Cost record) { return CostElementId.ofRepoId(record.getM_CostElement_ID()); } private AcctSchema getAcctSchema(final AcctSchemaId acctSchemaId) { return acctSchemaCache.computeIfAbsent(acctSchemaId, acctSchemasRepo::getById); } @NonNull private static AcctSchemaId extractAcctSchemaId(final @NonNull I_M_Cost record) { return AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()); } private I_C_UOM extractUOM(final @NonNull I_M_Cost record) { return uomCache.computeIfAbsent(extractUomId(record), uomsRepo::getById); }
private static UomId extractUomId(final @NonNull I_M_Cost record) { return UomId.ofRepoId(record.getC_UOM_ID()); } // // // @Value(staticConstructor = "of") private static class ProductAndAcctSchemaId { @NonNull ProductId productId; @NonNull AcctSchemaId acctSchemaId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CurrentCostsLoader.java
1
请完成以下Java代码
public HistoricIdentityLinkLogQuery orderByOperationType() { orderBy(HistoricIdentityLinkLogQueryProperty.OPERATION_TYPE); return this; } @Override public HistoricIdentityLinkLogQuery orderByAssignerId() { orderBy(HistoricIdentityLinkLogQueryProperty.ASSIGNER_ID); return this; } @Override public HistoricIdentityLinkLogQuery orderByTenantId() { orderBy(HistoricIdentityLinkLogQueryProperty.TENANT_ID); return this; } @Override
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogCountByQueryCriteria(this); } @Override public List<HistoricIdentityLinkLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricIdentityLinkManager() .findHistoricIdentityLinkLogByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIdentityLinkLogQueryImpl.java
1
请完成以下Java代码
public class ExecutionVariablesResource extends AbstractVariablesResource { private String resourceTypeName; public ExecutionVariablesResource(ProcessEngine engine, String resourceId, boolean isProcessInstance, ObjectMapper objectMapper) { super(engine, resourceId, objectMapper); if (isProcessInstance) { resourceTypeName = "process instance"; } else { resourceTypeName = "execution"; } } protected String getResourceTypeName() { return resourceTypeName; } protected void updateVariableEntities(VariableMap modifications, List<String> deletions) { RuntimeServiceImpl runtimeService = (RuntimeServiceImpl) engine.getRuntimeService(); runtimeService.updateVariables(resourceId, modifications, deletions); }
protected void removeVariableEntity(String variableKey) { engine.getRuntimeService().removeVariable(resourceId, variableKey); } protected VariableMap getVariableEntities(boolean deserializeValues) { return engine.getRuntimeService().getVariablesTyped(resourceId, deserializeValues); } protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { return engine.getRuntimeService().getVariableTyped(resourceId, variableKey, deserializeValue); } protected void setVariableEntity(String variableKey, TypedValue variableValue) { engine.getRuntimeService().setVariable(resourceId, variableKey, variableValue); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ExecutionVariablesResource.java
1
请完成以下Java代码
public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderCreateRequestPackage { @JsonProperty("id") Id id; @JsonProperty("orderType") OrderType orderType; @JsonProperty("orderIdentification") /** One of 4 predefined or one free identifier. May deviate from the request identifier and be replaced by one of the 4 predefined identifiers (see specifications). */ String orderIdentification; @JsonProperty("supportId") SupportIDType supportId; @JsonProperty("packingMaterialId") String packingMaterialId; @JsonProperty("items") List<OrderCreateRequestPackageItem> items; @Builder private OrderCreateRequestPackage( @JsonProperty("id") @NonNull final Id id, @JsonProperty("orderType") @NonNull final OrderType orderType, @JsonProperty("orderIdentification") @NonNull final String orderIdentification, @JsonProperty("supportId") @NonNull final SupportIDType supportId, @JsonProperty("packingMaterialId") final String packingMaterialId,
@JsonProperty("items") @Singular @NonNull final List<OrderCreateRequestPackageItem> items) { if (items.isEmpty()) { throw new IllegalArgumentException("Order package shall have at least one item"); } this.id = id; this.orderType = orderType; this.orderIdentification = orderIdentification; this.supportId = supportId; this.packingMaterialId = packingMaterialId; this.items = ImmutableList.copyOf(items); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderCreateRequestPackage.java
2
请完成以下Java代码
public PlanItem getCurrentPlanItem() { return currentPlanItem; } public void setCurrentPlanItem(PlanItem currentPlanItem) { this.currentPlanItem = currentPlanItem; } public CmmnDiShape getCurrentDiShape() { return currentDiShape; } public void setCurrentDiShape(CmmnDiShape currentDiShape) { this.currentDiShape = currentDiShape; } public CmmnDiEdge getCurrentDiEdge() { return currentDiEdge; } public void setCurrentDiEdge(CmmnDiEdge currentDiEdge) { this.currentDiEdge = currentDiEdge; } public List<Stage> getStages() { return stages; } public List<PlanFragment> getPlanFragments() { return planFragments; } public List<Criterion> getEntryCriteria() { return entryCriteria; } public List<Criterion> getExitCriteria() { return exitCriteria; } public List<Sentry> getSentries() { return sentries; } public List<SentryOnPart> getSentryOnParts() { return sentryOnParts; } public List<SentryIfPart> getSentryIfParts() { return sentryIfParts; }
public List<PlanItem> getPlanItems() { return planItems; } public List<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitions; } public List<CmmnDiShape> getDiShapes() { return diShapes; } public List<CmmnDiEdge> getDiEdges() { return diEdges; } public GraphicInfo getCurrentLabelGraphicInfo() { return currentLabelGraphicInfo; } public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) { this.currentLabelGraphicInfo = labelGraphicInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
1
请完成以下Java代码
public void setQtyToDeliver (final @Nullable BigDecimal QtyToDeliver) { set_ValueNoCheck (COLUMNNAME_QtyToDeliver, QtyToDeliver); } @Override public BigDecimal getQtyToDeliver() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDeliver); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSetup_Place_No (final int Setup_Place_No) { set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public int getSetup_Place_No() { return get_ValueAsInt(COLUMNNAME_Setup_Place_No); } /** * ShipmentAllocation_BestBefore_Policy AD_Reference_ID=541043 * Reference name: ShipmentAllocation_BestBefore_Policy */ public static final int SHIPMENTALLOCATION_BESTBEFORE_POLICY_AD_Reference_ID=541043; /** Newest_First = N */ public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Newest_First = "N"; /** Expiring_First = E */ public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Expiring_First = "E"; @Override public void setShipmentAllocation_BestBefore_Policy (final @Nullable java.lang.String ShipmentAllocation_BestBefore_Policy) { set_ValueNoCheck (COLUMNNAME_ShipmentAllocation_BestBefore_Policy, ShipmentAllocation_BestBefore_Policy); } @Override public java.lang.String getShipmentAllocation_BestBefore_Policy() { return get_ValueAsString(COLUMNNAME_ShipmentAllocation_BestBefore_Policy); }
@Override public void setShipperName (final @Nullable java.lang.String ShipperName) { set_ValueNoCheck (COLUMNNAME_ShipperName, ShipperName); } @Override public java.lang.String getShipperName() { return get_ValueAsString(COLUMNNAME_ShipperName); } @Override public void setWarehouseName (final @Nullable java.lang.String WarehouseName) { set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName); } @Override public java.lang.String getWarehouseName() { return get_ValueAsString(COLUMNNAME_WarehouseName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Packageable_V.java
1
请在Spring Boot框架中完成以下Java代码
public GlobalResponseBodyHandler responseWrapper(ServerCodecConfigurer serverCodecConfigurer, RequestedContentTypeResolver requestedContentTypeResolver) { return new GlobalResponseBodyHandler(serverCodecConfigurer.getWriters(), requestedContentTypeResolver); } // @Override // public void addCorsMappings(CorsRegistry registry) { // // 添加全局的 CORS 配置 // registry.addMapping("/**") // 匹配所有 URL ,相当于全局配置 // .allowedOrigins("*") // 允许所有请求来源 // .allowCredentials(true) // 允许发送 Cookie // .allowedMethods("*") // 允许所有请求 Method // .allowedHeaders("*") // 允许所有请求 Header //// .exposedHeaders("*") // 允许所有响应 Header // .maxAge(1800L); // 有效期 1800 秒,2 小时 // } @Bean @Order(0) // 设置 order 排序。这个顺序很重要哦,为避免麻烦请设置在最前 public CorsWebFilter corsFilter() { // 创建 UrlBasedCorsConfigurationSource 配置源,类似 CorsRegistry 注册表 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 创建 CorsConfiguration 配置,相当于 CorsRegistration 注册信息 CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("*")); // 允许所有请求来源 config.setAllowCredentials(true); // 允许发送 Cookie config.addAllowedMethod("*"); // 允许所有请求 Method config.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求 Header // config.setExposedHeaders(Collections.singletonList("*")); // 允许所有响应 Header
config.setMaxAge(1800L); // 有效期 1800 秒,2 小时 source.registerCorsConfiguration("/**", config); // 创建 CorsWebFilter 对象 return new CorsWebFilter(source); // 创建 CorsFilter 过滤器 } // @Override // public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { // configurer.registerDefaults(false); // configurer.customCodecs().decoder(new Jaxb2XmlDecoder()); // <- here // configurer.customCodecs().encoder(new Jaxb2XmlEncoder()); // <- here // } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-02\src\main\java\cn\iocoder\springboot\lab27\springwebflux\config\WebFluxConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
protected Properties extractCtxFromItem(final InOutLineWithQualityIssues item) { return Env.getCtx(); } @Override protected String extractTrxNameFromItem(final InOutLineWithQualityIssues item) { return ITrx.TRXNAME_ThreadInherited; } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final InOutLineWithQualityIssues item) { return TableRecordReference.of(I_M_InOutLine.Table_Name, item.getM_InOutLine_ID()); } }; @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName) { // Services final IQueueDAO queueDAO = Services.get(IQueueDAO.class);
final IRequestBL requestBL = Services.get(IRequestBL.class); // retrieve the items (inout lines) that were enqueued and put them in a list final List<I_M_InOutLine> lines = queueDAO.retrieveAllItems(workPackage, I_M_InOutLine.class); // for each line that was enqueued, create a R_Request containing the information from the inout line and inout for (final I_M_InOutLine line : lines) { requestBL.createRequestFromInOutLineWithQualityIssues(line); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\C_Request_CreateFromInout_Async.java
2
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set 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 Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclaration.java
1
请完成以下Java代码
public class DateComparisonUtils { public static boolean isSameDayUsingLocalDate(Date date1, Date date2) { LocalDate localDate1 = date1.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); LocalDate localDate2 = date2.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); return localDate1.isEqual(localDate2); } public static boolean isSameDayUsingInstant(Date date1, Date date2) { Instant instant1 = date1.toInstant() .truncatedTo(ChronoUnit.DAYS); Instant instant2 = date2.toInstant() .truncatedTo(ChronoUnit.DAYS); return instant1.equals(instant2); } public static boolean isSameDayUsingSimpleDateFormat(Date date1, Date date2) { SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); return fmt.format(date1) .equals(fmt.format(date2)); } public static boolean isSameDayUsingCalendar(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); } public static boolean isSameDayUsingApacheCommons(Date date1, Date date2) { return DateUtils.isSameDay(date1, date2); } public static boolean isSameDayUsingJoda(Date date1, Date date2) { org.joda.time.LocalDate localDate1 = new org.joda.time.LocalDate(date1); org.joda.time.LocalDate localDate2 = new org.joda.time.LocalDate(date2); return localDate1.equals(localDate2); } public static boolean isSameDayUsingDate4j(Date date1, Date date2) { DateTime dateObject1 = DateTime.forInstant(date1.getTime(), TimeZone.getDefault()); DateTime dateObject2 = DateTime.forInstant(date2.getTime(), TimeZone.getDefault()); return dateObject1.isSameDayAs(dateObject2); } }
repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\date\comparison\DateComparisonUtils.java
1
请完成以下Java代码
private boolean isEnabled() { return sysConfigBL.getBooleanValue(SYSCONFIG_Enabled, false); } @Override public boolean canConvert(final String filterId) { return FILTER_ID.equals(filterId); } @Nullable @Override public FilterSql getSql( final DocumentFilter filter, final SqlOptions sqlOpts, final SqlDocumentFilterConverterContext context) { final DocumentFilterParam filterParameter = filter.getParameterOrNull(PARAMETERNAME_SearchText); if (filterParameter == null) { return null; } final String searchText = filterParameter.getValueAsString(); return FilterSql.ofWhereClause(SqlAndParams.builder() .append(sqlOpts.getTableNameOrAlias()) .append(getSqlCriteria(searchText))
.build()); } private SqlAndParams getSqlCriteria(final String searchText) { final String searchLikeValue = convertSearchTextToSqlLikeString(searchText); return SqlAndParams.of(BPARTNER_SEARCH_SQL_TEMPLATE, searchLikeValue, searchLikeValue, searchLikeValue); } // converts user entered strings like ' john doe ' to '%john%doe%' private static String convertSearchTextToSqlLikeString(@NonNull final String searchText) { String sql = searchText.trim() .replaceAll("\\s+", "%") .replaceAll("%+", "%"); if (!sql.startsWith("%")) { sql = "%" + sql; } if (!sql.endsWith("%")) { sql = sql + "%"; } return sql; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bpartner\filter\BPartnerSimpleFuzzySearchFilterProvider.java
1
请完成以下Java代码
public void setProductName(String productName) { this.productName = productName; } public Integer getRecommendStatus() { return recommendStatus; } public void setRecommendStatus(Integer recommendStatus) { this.recommendStatus = recommendStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", productName=").append(productName); sb.append(", recommendStatus=").append(recommendStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeNewProduct.java
1
请在Spring Boot框架中完成以下Java代码
public class FTSSearchResultRepository { private static final String SQL_INSERT = buildSqlInsert(); private static String buildSqlInsert() { final StringBuilder sqlColumns = new StringBuilder( I_T_ES_FTS_Search_Result.COLUMNNAME_Search_UUID // 1 + "," + I_T_ES_FTS_Search_Result.COLUMNNAME_Line // 2 + "," + I_T_ES_FTS_Search_Result.COLUMNNAME_JSON // 3 ); final StringBuilder sqlValues = new StringBuilder("?, ?, ?"); for (final String keyColumnName : I_T_ES_FTS_Search_Result.COLUMNNAME_ALL_Keys) { sqlColumns.append(", ").append(keyColumnName); sqlValues.append(", ?"); } return "INSERT INTO " + I_T_ES_FTS_Search_Result.Table_Name + " (" + sqlColumns + ")" + " VALUES (" + sqlValues + ")"; } public void saveNew(@NonNull final FTSSearchResult result) { final ImmutableList<FTSSearchResultItem> items = result.getItems(); if (items.isEmpty()) { return; } PreparedStatement pstmt = null; try { int nextLineNo = 1; pstmt = DB.prepareStatement(SQL_INSERT, ITrx.TRXNAME_None); final ArrayList<Object> sqlParams = new ArrayList<>(); for (final FTSSearchResultItem item : items) { final int lineNo = nextLineNo++; sqlParams.clear(); sqlParams.add(result.getSearchId()); sqlParams.add(lineNo); sqlParams.add(item.getJson());
for (final String keyColumnName : I_T_ES_FTS_Search_Result.COLUMNNAME_ALL_Keys) { final Object value = item.getKey().getValueBySelectionTableColumnName(keyColumnName); sqlParams.add(value); } DB.setParameters(pstmt, sqlParams); pstmt.addBatch(); } pstmt.executeBatch(); } catch (final SQLException ex) { throw new DBException(ex, SQL_INSERT); } finally { DB.close(pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchResultRepository.java
2
请在Spring Boot框架中完成以下Java代码
public String prefix() { return "management.otlp.metrics.export"; } @Override public String url() { return obtain((properties) -> this.connectionDetails.getUrl(), OtlpConfig.super::url); } @Override public AggregationTemporality aggregationTemporality() { return obtain(OtlpMetricsProperties::getAggregationTemporality, OtlpConfig.super::aggregationTemporality); } @Override public Map<String, String> resourceAttributes() { Map<String, String> resourceAttributes = new LinkedHashMap<>(); new OpenTelemetryResourceAttributes(this.environment, this.openTelemetryProperties.getResourceAttributes()) .applyTo(resourceAttributes::put); return Collections.unmodifiableMap(resourceAttributes); } @Override public Map<String, String> headers() { return obtain(OtlpMetricsProperties::getHeaders, OtlpConfig.super::headers); } @Override public HistogramFlavor histogramFlavor() { return obtain(OtlpMetricsProperties::getHistogramFlavor, OtlpConfig.super::histogramFlavor); } @Override public Map<String, HistogramFlavor> histogramFlavorPerMeter() { return obtain(perMeter(Meter::getHistogramFlavor), OtlpConfig.super::histogramFlavorPerMeter); } @Override public Map<String, Integer> maxBucketsPerMeter() { return obtain(perMeter(Meter::getMaxBucketCount), OtlpConfig.super::maxBucketsPerMeter); } @Override public int maxScale() { return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale);
} @Override public int maxBucketCount() { return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount); } @Override public TimeUnit baseTimeUnit() { return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit); } private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) { return (properties) -> { if (CollectionUtils.isEmpty(properties.getMeter())) { return null; } Map<String, V> perMeter = new LinkedHashMap<>(); properties.getMeter().forEach((key, meterProperties) -> { V value = getter.get(meterProperties); if (value != null) { perMeter.put(key, value); } }); return (!perMeter.isEmpty()) ? perMeter : null; }; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public class McpSyncClientExchangeFilterFunction implements ExchangeFilterFunction { private final ClientCredentialsOAuth2AuthorizedClientProvider clientCredentialTokenProvider = new ClientCredentialsOAuth2AuthorizedClientProvider(); private final ServletOAuth2AuthorizedClientExchangeFilterFunction delegate; private final ClientRegistrationRepository clientRegistrationRepository; private static final String AUTHORIZATION_CODE_CLIENT_REGISTRATION_ID = "authserver"; private static final String CLIENT_CREDENTIALS_CLIENT_REGISTRATION_ID = "authserver-client-credentials"; public McpSyncClientExchangeFilterFunction(OAuth2AuthorizedClientManager clientManager, ClientRegistrationRepository clientRegistrationRepository) { this.delegate = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientManager); this.delegate.setDefaultClientRegistrationId(AUTHORIZATION_CODE_CLIENT_REGISTRATION_ID); this.clientRegistrationRepository = clientRegistrationRepository; } @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) { return this.delegate.filter(request, next); } else { var accessToken = getClientCredentialsAccessToken(); var requestWithToken = ClientRequest.from(request) .headers(headers -> headers.setBearerAuth(accessToken)) .build(); return next.exchange(requestWithToken); } } private String getClientCredentialsAccessToken() { var clientRegistration = this.clientRegistrationRepository.findByRegistrationId(CLIENT_CREDENTIALS_CLIENT_REGISTRATION_ID);
var authRequest = OAuth2AuthorizationContext.withClientRegistration(clientRegistration) .principal(new AnonymousAuthenticationToken("client-credentials-client", "client-credentials-client", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))) .build(); return this.clientCredentialTokenProvider.authorize(authRequest) .getAccessToken() .getTokenValue(); } public Consumer<WebClient.Builder> configuration() { return builder -> builder.defaultRequest(this.delegate.defaultRequest()) .filter(this); } }
repos\tutorials-master\spring-ai-modules\spring-ai-mcp-oauth\mcp-client-oauth2\src\main\java\com\baeldung\mcp\mcpclientoauth2\McpSyncClientExchangeFilterFunction.java
2
请完成以下Java代码
public Double getDoubleValue() { return null; } @Override public void setDoubleValue(Double doubleValue) { } @Override public byte[] getBytes() { return null; } @Override public void setBytes(byte[] bytes) { } @Override public Object getCachedValue() { return null; } @Override public void setCachedValue(Object cachedValue) { } @Override public String getId() { return null; } @Override public void setId(String id) { } @Override public void setName(String name) { } @Override public void setProcessInstanceId(String processInstanceId) { } @Override public void setProcessDefinitionId(String processDefinitionId) { } @Override public void setExecutionId(String executionId) { } @Override public Object getValue() { return variableValue; } @Override public void setValue(Object value) { variableValue = value; } @Override public String getTypeName() { return TYPE_TRANSIENT; } @Override public void setTypeName(String typeName) { } @Override public String getProcessInstanceId() { return null; } @Override public String getProcessDefinitionId() { return null; }
@Override public String getTaskId() { return null; } @Override public void setTaskId(String taskId) { } @Override public String getExecutionId() { return null; } // non-supported (v6) @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } @Override public void setScopeId(String scopeId) { } @Override public void setSubScopeId(String subScopeId) { } @Override public void setScopeType(String scopeType) { } @Override public String getScopeDefinitionId() { return null; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { } @Override public String getMetaInfo() { return null; } @Override public void setMetaInfo(String metaInfo) { } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
1
请在Spring Boot框架中完成以下Java代码
public String getMobileNo() { return mobileNo; } /** * 手机号 * * @return */ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } /** * 操作员类型 * * @return */ public String getType() { return type; } /** * 操作员类型 * * @return */ public void setType(String type) { this.type = type; } /** * 盐 * * @return */ public String getsalt() { return salt;
} /** * 盐 * * @param salt */ public void setsalt(String salt) { this.salt = salt; } /** * 认证加密的盐 * * @return */ public String getCredentialsSalt() { return loginName + salt; } public PmsOperator() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperator.java
2
请完成以下Java代码
private Optional<ListInfo> loadListInfo(final int adReferenceId) { ListInfo.Builder listInfoBuilder = null; final String sql = "SELECT " + " r.Name as ReferenceName" + ", rl.Value" + ", rl.Name" + ", rl.ValueName" // metas: 02827: added ValueName + ", rl.AD_Ref_List_ID" + " FROM AD_Reference r " + " LEFT OUTER JOIN AD_Ref_List rl ON (rl.AD_Reference_ID=r.AD_Reference_ID) " + " WHERE r.AD_Reference_ID=?" + " ORDER BY rl.AD_Ref_List_ID"; final Object[] sqlParams = new Object[] { adReferenceId }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); while (rs.next()) { if (listInfoBuilder == null) { final String referenceName = rs.getString("ReferenceName"); listInfoBuilder = ListInfo.builder() .setAD_Reference_ID(adReferenceId) .setName(referenceName); } final int AD_Ref_List_ID = rs.getInt("AD_Ref_List_ID"); if (AD_Ref_List_ID > 0) { final String value = rs.getString("Value"); final String name = rs.getString("Name"); final String valueName = rs.getString("ValueName"); listInfoBuilder.addItem(value, name, valueName); } } } catch (final SQLException e) { throw new DBException(e, sql, sqlParams); } finally { DB.close(rs, pstmt); } if (listInfoBuilder == null) { return Optional.empty();
} return Optional.of(listInfoBuilder.build()); } public Optional<TableReferenceInfo> loadTableReferenceInfo(final int adReferenceId) { final String sql = "SELECT" + " t.TableName, t.EntityType" // 1,2 + ", ck.AD_Reference_ID" // 3 + ", ck.IsKey" // 4 + ", ck.AD_Reference_Value_ID as Key_Reference_Value_ID" // 5 + " FROM AD_Ref_Table rt" + " INNER JOIN AD_Table t ON (t.AD_Table_ID=rt.AD_Table_ID)" + " INNER JOIN AD_Column ck ON (ck.AD_Table_ID=rt.AD_Table_ID AND ck.AD_Column_ID=rt.AD_Key)" + " WHERE rt.AD_Reference_ID=?"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None); pstmt.setInt(1, adReferenceId); rs = pstmt.executeQuery(); if (rs.next()) { final String refTableName = rs.getString(1); final String entityType = rs.getString(2); final int refDisplayType = rs.getInt(3); final boolean refIsKey = "Y".equals(rs.getString("IsKey")); final int keyReferenceValueId = rs.getInt("Key_Reference_Value_ID"); final TableReferenceInfo tableReferenceInfo = new TableReferenceInfo(refTableName, refDisplayType, entityType, refIsKey, keyReferenceValueId); return Optional.of(tableReferenceInfo); } } catch (final SQLException e) { throw new DBException(e, sql); } finally { DB.close(rs, pstmt); } return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\TableAndColumnInfoRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteViaIdentifiersX() { Author author = authorRepository.findByNameWithBooks("Joana Nimar"); bookRepository.deleteByAuthorIdentifier(author.getId()); authorRepository.deleteByIdentifier(author.getId()); } // More Author are loaded in the Persistent Context @Transactional public void deleteViaBulkIn() { List<Author> authors = authorRepository.findByAge(34); bookRepository.deleteBulkByAuthors(authors); authorRepository.deleteInBatch(authors); } // More Author and the associated Book are in Persistent Context @Transactional public void deleteViaBulkInX() { List<Author> authors = authorRepository.findByGenreWithBooks("Anthology"); bookRepository.deleteBulkByAuthors(authors); authorRepository.deleteInBatch(authors); }
// No Author or Book that should be deleted are loaded in the Persistent Context @Transactional public void deleteViaHardCodedIdentifiers() { bookRepository.deleteByAuthorIdentifier(4L); authorRepository.deleteByIdentifier(4L); } // No Author or Book that should be deleted are loaded in the Persistent Context @Transactional public void deleteViaBulkHardCodedIdentifiers() { List<Long> authorsIds = Arrays.asList(1L, 4L); bookRepository.deleteBulkByAuthorIdentifier(authorsIds); authorRepository.deleteBulkByIdentifier(authorsIds); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCascadeChildRemoval\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public boolean isSystemOnly() { return this == SystemOnly; } /** * @return true if it has Client flag set */ public boolean isClient() { return (accesses & ClientOnly.accesses) > 0; } /** * @return true if it has only the Client flag set (i.e. it's {@value #ClientOnly}) */ public boolean isClientOnly() { return this == ClientOnly; } /** * @return true if it has Organization flag set */ public boolean isOrganization() { return (accesses & Organization.accesses) > 0; } /** * @return true if it has only the Organization flag set (i.e. it's {@value #Organization}) */ public boolean isOrganizationOnly() { return this == Organization; } /** * @return user friendly AD_Message of this access level. */ public String getAD_Message() { return adMessage; } /** * Gets user friendly description of enabled flags.
* * e.g. "3 - Client - Org" * * @return user friendly description of enabled flags */ public String getDescription() { final StringBuilder accessLevelInfo = new StringBuilder(); accessLevelInfo.append(getAccessLevelString()); if (isSystem()) { accessLevelInfo.append(" - System"); } if (isClient()) { accessLevelInfo.append(" - Client"); } if (isOrganization()) { accessLevelInfo.append(" - Org"); } return accessLevelInfo.toString(); } // -------------------------------------- // Pre-indexed values for optimization private static ImmutableMap<Integer, TableAccessLevel> accessLevelInt2accessLevel; static { final ImmutableMap.Builder<Integer, TableAccessLevel> builder = new ImmutableMap.Builder<Integer, TableAccessLevel>(); for (final TableAccessLevel l : values()) { builder.put(l.getAccessLevelInt(), l); } accessLevelInt2accessLevel = builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\TableAccessLevel.java
1
请完成以下Java代码
public static GlobalQRCode toGlobalQRCode(final HUQRCode qrCode) { return JsonConverterV1.toGlobalQRCode(HUQRCodeJsonConverter.GLOBAL_QRCODE_TYPE, qrCode); } public static HUQRCode fromGlobalQRCodeJsonString(@NonNull final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static HUQRCode fromGlobalQRCode(final GlobalQRCode globalQRCode) { if (!isHandled(globalQRCode)) { throw new AdempiereException(INVALID_QR_CODE_ERROR_MSG) .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long } // // IMPORTANT: keep in sync with huQRCodes.js // final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION)) { return JsonConverterV1.fromGlobalQRCode(globalQRCode);
} else { throw new AdempiereException(INVALID_QR_VERSION_ERROR_MSG) .setParameter("version", version); } } public static JsonDisplayableQRCode toRenderedJson(@NonNull final HUQRCode huQRCode) { return JsonDisplayableQRCode.builder() .code(toGlobalQRCodeJsonString(huQRCode)) .displayable(huQRCode.toDisplayableQRCode()) .build(); } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\json\HUQRCodeJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class DDOrderCandidateUpdatedHandler extends DDOrderCandidateAdvisedOrCreatedHandler<DDOrderCandidateUpdatedEvent> { public DDOrderCandidateUpdatedHandler( @NonNull final CandidateRepositoryRetrieval candidateRepository, @NonNull final CandidateRepositoryWriteService candidateRepositoryCommands, @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final DDOrderDetailRequestHandler ddOrderDetailRequestHandler, @NonNull final MainDataRequestHandler mainDataRequestHandler) { super( candidateRepository, candidateRepositoryCommands, candidateChangeHandler, ddOrderDetailRequestHandler, mainDataRequestHandler); } @Override public Collection<Class<? extends DDOrderCandidateUpdatedEvent>> getHandledEventType() { return ImmutableList.of(DDOrderCandidateUpdatedEvent.class); } @Override public void handleEvent(@NonNull final DDOrderCandidateUpdatedEvent event) { createAndProcessCandidates(event); } @Override protected CandidatesQuery createPreExistingCandidatesQuery(@NonNull final AbstractDDOrderCandidateEvent event, @NonNull final CandidateType candidateType) { final int ddOrderCandidateId = event.getExistingDDOrderCandidateId(); if (ddOrderCandidateId <= 0) { throw new AdempiereException("existing DD_Order_Candidate_ID should be provided")
.setParameter("event", event) .appendParametersToMessage(); } return CandidatesQuery.builder() .type(candidateType) .materialDescriptorQuery(MaterialDescriptorQuery.builder() .productId(event.getProductId()) .storageAttributesKey(event.getStorageAttributesKey()) .build()) .groupId(event.getMaterialDispoGroupId()) .businessCase(CandidateBusinessCase.DISTRIBUTION) .distributionDetailsQuery(DistributionDetailsQuery.builder().ddOrderCandidateId(ddOrderCandidateId).build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddordercandidate\DDOrderCandidateUpdatedHandler.java
2
请完成以下Java代码
public int getM_HU_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item_Storage getM_HU_Item_Storage() { return get_ValueAsPO(COLUMNNAME_M_HU_Item_Storage_ID, de.metas.handlingunits.model.I_M_HU_Item_Storage.class); } @Override public void setM_HU_Item_Storage(final de.metas.handlingunits.model.I_M_HU_Item_Storage M_HU_Item_Storage) { set_ValueFromPO(COLUMNNAME_M_HU_Item_Storage_ID, de.metas.handlingunits.model.I_M_HU_Item_Storage.class, M_HU_Item_Storage); } @Override public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_Value (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_Value (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); } @Override public int getM_HU_Item_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_HU_Item_Storage_Snapshot_ID (final int M_HU_Item_Storage_Snapshot_ID) { if (M_HU_Item_Storage_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, M_HU_Item_Storage_Snapshot_ID); } @Override public int getM_HU_Item_Storage_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} @Override public void setQty (final 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 setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
1
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } @Override public List<IFacetCategory> getFacetCategories() { return facetCategories; } @Override public Set<IFacet<ModelType>> getFacets() { return facets; } @Override public Set<IFacet<ModelType>> getFacetsByCategory(IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null"); // TODO optimize final ImmutableSet.Builder<IFacet<ModelType>> facetsForCategory = ImmutableSet.builder(); for (final IFacet<ModelType> facet : facets) { if (!facetCategory.equals(facet.getFacetCategory())) { continue; } facetsForCategory.add(facet); } return facetsForCategory.build(); } public static class Builder<ModelType> { private final Set<IFacetCategory> facetCategories = new LinkedHashSet<>(); private final LinkedHashSet<IFacet<ModelType>> facets = new LinkedHashSet<>(); private Builder() { super(); } public IFacetCollectorResult<ModelType> build() { // If there was nothing added to this builder, return the empty instance (optimization) if (isEmpty()) { return EmptyFacetCollectorResult.getInstance(); } return new FacetCollectorResult<>(this); } /** @return true if this builder is empty */ private final boolean isEmpty() { return facets.isEmpty() && facetCategories.isEmpty(); } public Builder<ModelType> addFacetCategory(final IFacetCategory facetCategory) { Check.assumeNotNull(facetCategory, "facetCategory not null");
facetCategories.add(facetCategory); return this; } public Builder<ModelType> addFacet(final IFacet<ModelType> facet) { Check.assumeNotNull(facet, "facet not null"); facets.add(facet); facetCategories.add(facet.getFacetCategory()); return this; } public Builder<ModelType> addFacets(final Iterable<IFacet<ModelType>> facets) { Check.assumeNotNull(facets, "facet not null"); for (final IFacet<ModelType> facet : facets) { addFacet(facet); } return this; } /** @return true if there was added at least one facet */ public boolean hasFacets() { return !facets.isEmpty(); } public Builder<ModelType> addFacetCollectorResult(final IFacetCollectorResult<ModelType> facetCollectorResult) { // NOTE: we need to add the categories first, to make sure we preserve the order of categories this.facetCategories.addAll(facetCollectorResult.getFacetCategories()); this.facets.addAll(facetCollectorResult.getFacets()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCollectorResult.java
1
请完成以下Spring Boot application配置
spring.servlet.multipart.max-file-size=150MB spring.servlet.multipart.max-request-size=200MB spring.servlet.multipart.file-size-threshold=100MB upload.path
=D:/tmp/ download.path=D:/tmp/download/ file.client.type=local-file
repos\springboot-demo-master\file\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public Pool getPool() { return this.pool; } public Simple getSimple() { return this.simple; } public Shutdown getShutdown() { return this.shutdown; } public String getThreadNamePrefix() { return this.threadNamePrefix; } public void setThreadNamePrefix(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; } public static class Pool { /** * Maximum allowed number of threads. Doesn't have an effect if virtual threads * are enabled. */ private int size = 1; public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class Simple { /** * Set the maximum number of parallel accesses allowed. -1 indicates no * concurrency limit at all. */ private @Nullable Integer concurrencyLimit; public @Nullable Integer getConcurrencyLimit() { return this.concurrencyLimit; }
public void setConcurrencyLimit(@Nullable Integer concurrencyLimit) { this.concurrencyLimit = concurrencyLimit; } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination; /** * Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingProperties.java
2
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public LocalDateTime getCreatedTs() { return createdTs; } public void setCreatedTs(LocalDateTime createdTs) { this.createdTs = createdTs; } public BigDecimal getPrice() { return price;
} public void setPrice(BigDecimal price) { this.price = price; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Product{"); sb.append("id=").append(id); sb.append(", title='").append(title).append('\''); sb.append(", createdTs=").append(createdTs); sb.append(", price=").append(price); sb.append('}'); return sb.toString(); } }
repos\tutorials-master\persistence-modules\spring-jdbc\src\main\java\com\baeldung\spring\jdbc\batch\model\Product.java
1
请完成以下Java代码
public BigDecimal getQty() { return inoutLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class); final org.compiere.model.I_M_InOut inOut = inoutLine.getM_InOut(); // Applied only to customer return inout lines. final boolean isCustomerReturnInOutLine = huInOutBL.isCustomerReturn(inOut); if (inoutLine.isManualPackingMaterial() || isCustomerReturnInOutLine) { return inoutLine.getM_HU_PI_Item_Product_ID(); } final I_C_OrderLine orderline = InterfaceWrapperHelper.create(inoutLine.getC_OrderLine(), I_C_OrderLine.class); return orderline == null ? -1 : orderline.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return inoutLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { inoutLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return inoutLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { inoutLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return inoutLine.getQtyEnteredTU(); } @Override
public void setQtyTU(final BigDecimal qtyPacks) { inoutLine.setQtyEnteredTU(qtyPacks); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public boolean isInDispute() { return inoutLine.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { inoutLine.setIsInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InOutLineHUPackingAware.java
1
请完成以下Java代码
public I_M_HU_PI_Item_Product getM_HU_PI_ItemProductFor(final Object document, final ProductId productId) { if (productId == null) { // No product selected. Nothing to do. return null; } final de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine ddOrderLine = getDDOrderLine(document); final I_M_HU_PI_Item_Product piip; // the record is new // search for the right combination if (InterfaceWrapperHelper.isNew(ddOrderLine) && ddOrderLine.getM_HU_PI_Item_Product_ID() > 0) { piip = ddOrderLine.getM_HU_PI_Item_Product(); } else { final I_DD_Order ddOrder = ddOrderLine.getDD_Order(); final String huUnitType = X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit; piip = Services.get(IHUPIItemProductDAO.class).retrieveMaterialItemProduct( productId, BPartnerId.ofRepoIdOrNull(ddOrder.getC_BPartner_ID()), TimeUtil.asZonedDateTime(ddOrder.getDateOrdered()), huUnitType, false); // allowInfiniteCapacity = false } return piip; } /** * Calls {@link #getM_HU_PI_ItemProductFor(Object, ProductId)} with the given <code>document</code> which is a <code>DD_OrderLine</code> and sets the PIIP to it. Does <b>not</b> save the dd order line. */ @Override public void applyChangesFor(final Object document) {
final de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine ddOrderLine = getDDOrderLine(document); final boolean enforcePIIP = Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DD_OrderLine_Enforce_M_HU_PI_Item_Product, false); if(!enforcePIIP) { return; } final ProductId productId = ProductId.ofRepoIdOrNull(ddOrderLine.getM_Product_ID()); final I_M_HU_PI_Item_Product piip = getM_HU_PI_ItemProductFor(ddOrderLine, productId); ddOrderLine.setM_HU_PI_Item_Product(piip); } private de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine getDDOrderLine(final Object document) { Check.assumeInstanceOf(document, I_DD_OrderLine.class, "document"); return InterfaceWrapperHelper.create(document, de.metas.distribution.ddorder.lowlevel.model.I_DD_OrderLine.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\hu_spis\DDOrderLineHUDocumentHandler.java
1
请完成以下Java代码
public IPricingResult calculatePrice() { final IEditablePricingContext pricingCtx = createPricingContext() .setFailIfNotCalculated(); try { return pricingBL.calculatePrice(pricingCtx); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("pricingContext", pricingCtx); } } private IEditablePricingContext createPricingContext() { final IEditablePricingContext context = pricingBL.createPricingContext() .setFailIfNotCalculated() .setOrgId(pricingInfo.getOrgId()) .setProductId(pricingInfo.getProductId()) .setBPartnerId(pricingInfo.getBpartnerId()) .setQty(pricingInfo.getQuantity()) .setConvertPriceToContextUOM(pricingInfo.isConvertPriceToContextUOM())
.setSOTrx(SOTrx.PURCHASE) .setCountryId(pricingInfo.getCountryId()) .setManualPriceEnabled(pricingInfo.getIsManualPrice()); if (pricingInfo.getIsManualPrice()) { context.setUomId(pricingInfo.getPriceEnteredUomId()) .setCurrencyId(pricingInfo.getCurrencyId()) .setManualPrice(pricingInfo.getPriceEntered()); } return context; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\PurchaseOrderPriceCalculator.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (obj == null || !(obj instanceof ObjectIdentityImpl)) { return false; } ObjectIdentityImpl other = (ObjectIdentityImpl) obj; if (this.identifier instanceof Number && other.identifier instanceof Number) { // Integers and Longs with same value should be considered equal if (((Number) this.identifier).longValue() != ((Number) other.identifier).longValue()) { return false; } } else { // Use plain equality for other serializable types if (!this.identifier.equals(other.identifier)) { return false; } } return this.type.equals(other.type); } @Override public Serializable getIdentifier() { return this.identifier; } @Override public String getType() { return this.type; } /** * Important so caching operates properly. * @return the hash */
@Override public int hashCode() { int result = this.type.hashCode(); result = 31 * result + this.identifier.hashCode(); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()).append("["); sb.append("Type: ").append(this.type); sb.append("; Identifier: ").append(this.identifier).append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\ObjectIdentityImpl.java
1
请完成以下Java代码
public int getAD_EventLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_EventLog_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Issue getAD_Issue() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class); } @Override public void setAD_Issue(org.compiere.model.I_AD_Issue AD_Issue) { set_ValueFromPO(COLUMNNAME_AD_Issue_ID, org.compiere.model.I_AD_Issue.class, AD_Issue); } /** Set System-Problem. @param AD_Issue_ID Automatically created or manually entered System Issue */ @Override public void setAD_Issue_ID (int AD_Issue_ID) { if (AD_Issue_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Issue_ID, Integer.valueOf(AD_Issue_ID)); } /** Get System-Problem. @return Automatically created or manually entered System Issue */ @Override public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java-Klasse. @param Classname Java-Klasse */ @Override public void setClassname (java.lang.String Classname) { set_ValueNoCheck (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Fehler. @param IsError Ein Fehler ist bei der Durchführung aufgetreten */ @Override public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return Ein Fehler ist bei der Durchführung aufgetreten */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null)
{ if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
1
请在Spring Boot框架中完成以下Java代码
public int getRepair_VHU_ID() { return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID); } /** * Status AD_Reference_ID=541245 * Reference name: C_Project_Repair_Task_Status */ public static final int STATUS_AD_Reference_ID=541245; /** Not Started = NS */ public static final String STATUS_NotStarted = "NS"; /** In Progress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status);
} /** * Type AD_Reference_ID=541243 * Reference name: C_Project_Repair_Task_Type */ public static final int TYPE_AD_Reference_ID=541243; /** ServiceRepairOrder = W */ public static final String TYPE_ServiceRepairOrder = "W"; /** SpareParts = P */ public static final String TYPE_SpareParts = "P"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java
2
请在Spring Boot框架中完成以下Java代码
public class PmsRole extends PermissionBaseEntity { private static final long serialVersionUID = -1850274607153125161L; private String roleCode; // 角色编码:例如:admin private String roleName; // 角色名称 public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } /** * 角色名称 * * @return
*/ public String getRoleName() { return roleName; } /** * 角色名称 * * @return */ public void setRoleName(String roleName) { this.roleName = roleName; } public PmsRole() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsRole.java
2
请完成以下Java代码
private static void validateAdditionalProperties(@Nullable Map<String, String> additionalProperties) { if (additionalProperties != null) { additionalProperties.forEach((name, value) -> { if (value == null) { throw new NullAdditionalPropertyValueException(name); } }); } } public @Nullable String getGroup() { return this.group; } public @Nullable String getArtifact() { return this.artifact; } public @Nullable String getName() { return this.name; } public @Nullable String getVersion() { return this.version; } public @Nullable Instant getTime() { return this.time; } public @Nullable Map<String, String> getAdditionalProperties() { return this.additionalProperties; }
} /** * Exception thrown when an additional property with a null value is encountered. */ public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\BuildPropertiesWriter.java
1
请完成以下Java代码
public class PaymentView_Launcher_From_C_Invoice_SingleDocument extends JavaProcess { private final IViewsRepository viewsFactory; final IInvoiceDAO invoiceDAO; final PaymentAllocationRepository allocationRepository; public PaymentView_Launcher_From_C_Invoice_SingleDocument() { viewsFactory = SpringContextHolder.instance.getBean(IViewsRepository.class); allocationRepository = SpringContextHolder.instance.getBean(PaymentAllocationRepository.class); invoiceDAO = Services.get(IInvoiceDAO.class); } @Override protected String doIt() { final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(InvoiceId.ofRepoId(getRecord_ID()));
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(PaymentsViewFactory.WINDOW_ID) .setParameter(PaymentsViewFactory.PARAMETER_TYPE_BPARTNER_ID, bPartnerId) .build()) .getViewId(); getResult().setWebuiViewToOpen(WebuiViewToOpen.builder() .viewId(viewId.getViewId()) .target(ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentView_Launcher_From_C_Invoice_SingleDocument.java
1
请完成以下Java代码
public static void setDefaultEncoding(String encoding) { Assert.notNull(encoding, "'encoding' cannot be null"); bodyEncoding = encoding; } /** * Set the maximum length of a test message body to render as a String in * {@link #toString()}. Default 50. * @param length the length to render. * @since 2.2.20 */ public static void setMaxBodyLength(int length) { maxBodyLength = length; } public byte[] getBody() { return this.body; //NOSONAR } public MessageProperties getMessageProperties() { return this.messageProperties; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("("); buffer.append("Body:'").append(this.getBodyContentAsString()).append("'"); buffer.append(" ").append(this.messageProperties.toString()); buffer.append(")"); return buffer.toString(); } private String getBodyContentAsString() { try { String contentType = this.messageProperties.getContentType(); if (MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT.equals(contentType)) { return "[serialized object]"; } String encoding = encoding(); if (this.body.length <= maxBodyLength // NOSONAR && (MessageProperties.CONTENT_TYPE_TEXT_PLAIN.equals(contentType) || MessageProperties.CONTENT_TYPE_JSON.equals(contentType) || MessageProperties.CONTENT_TYPE_JSON_ALT.equals(contentType) || MessageProperties.CONTENT_TYPE_XML.equals(contentType))) { return new String(this.body, encoding); } } catch (Exception e) { // ignore } // Comes out as '[B@....b' (so harmless) return this.body.toString() + "(byte[" + this.body.length + "])"; //NOSONAR } private String encoding() { String encoding = this.messageProperties.getContentEncoding(); if (encoding == null) { encoding = bodyEncoding; } return encoding; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(this.body); result = prime * result + ((this.messageProperties == null) ? 0 : this.messageProperties.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Message other = (Message) obj; if (!Arrays.equals(this.body, other.body)) { return false; } if (this.messageProperties == null) { return other.messageProperties == null; } return this.messageProperties.equals(other.messageProperties); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\Message.java
1
请完成以下Java代码
public class JavaClassDAO implements IJavaClassDAO { @Override public List<I_AD_JavaClass> retrieveAllJavaClasses(final I_AD_JavaClass_Type type) { final int javaClassTypeID = type.getAD_JavaClass_Type_ID(); final Properties ctx = InterfaceWrapperHelper.getCtx(type); return retrieveAllJavaClasses(ctx, javaClassTypeID); } @Cached(cacheName = I_AD_JavaClass.Table_Name + "#by#" + I_AD_JavaClass.COLUMNNAME_AD_JavaClass_Type_ID) /* package */ List<I_AD_JavaClass> retrieveAllJavaClasses(final @CacheCtx Properties ctx, final int javaClassTypeID) { return Services.get(IQueryBL.class) .createQueryBuilder(I_AD_JavaClass.class, new PlainContextAware(ctx)) .addEqualsFilter(I_AD_JavaClass.COLUMNNAME_AD_JavaClass_Type_ID, javaClassTypeID) .create() .list(I_AD_JavaClass.class); } @Override @Cached(cacheName = I_AD_JavaClass.Table_Name + "#by#" + I_AD_JavaClass.COLUMNNAME_AD_JavaClass_ID) public I_AD_JavaClass retriveJavaClassOrNull( @CacheCtx final Properties ctx, final int adJavaClassId) { if (adJavaClassId <= 0) { return null; } return Services.get(IQueryBL.class).createQueryBuilder(I_AD_JavaClass.class, ctx, ITrx.TRXNAME_None) .filter(new EqualsQueryFilter<I_AD_JavaClass>(I_AD_JavaClass.COLUMNNAME_AD_JavaClass_ID, adJavaClassId)) .create() .firstOnly(I_AD_JavaClass.class); } @Override public List<I_AD_JavaClass> retrieveJavaClasses( @CacheCtx final Properties ctx, final String javaClassTypeInternalName) { if (javaClassTypeInternalName == null) { return Collections.emptyList(); } final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_AD_JavaClass_Type.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_JavaClass_Type.COLUMNNAME_InternalName, javaClassTypeInternalName) .andCollectChildren(I_AD_JavaClass.COLUMN_AD_JavaClass_Type_ID, I_AD_JavaClass.class) .addOnlyActiveRecordsFilter() .create() .list(); } @Override @Cached(cacheName = I_AD_JavaClass_Type.Table_Name + "#by#" + I_AD_JavaClass_Type.COLUMNNAME_InternalName) public I_AD_JavaClass_Type retrieveJavaClassTypeOrNull( @CacheCtx final Properties ctx, final String internalName) { final IQueryBL queryBL = Services.get(IQueryBL.class); return queryBL.createQueryBuilder(I_AD_JavaClass_Type.class, ctx, ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_JavaClass_Type.COLUMNNAME_InternalName, internalName) .create() .firstOnly(I_AD_JavaClass_Type.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\impl\JavaClassDAO.java
1
请完成以下Java代码
public static void main(String[] args) throws IOException, TimeoutException { // 创建连接 Connection connection = getConnection(); // 创建信道 Channel channel = connection.createChannel(); // 初始化测试用的 Exchange 和 Queue initExchangeAndQueue(channel); // 发送 3 条消息 for (int i = 0; i < 3; i++) { String message = "Hello World" + i; channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes()); } // 关闭 channel.close(); connection.close(); } public static Connection getConnection() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory(); factory.setHost(IP_ADDRESS); factory.setPort(PORT); factory.setUsername(USERNAME); factory.setPassword(PASSWORD); return factory.newConnection(); } // 创建 RabbitMQ Exchange 和 Queue ,然后使用 ROUTING_KEY 路由键将两者绑定。 // 该步骤,其实可以在 RabbitMQ Management 上操作,并不一定需要在代码中 private static void initExchangeAndQueue(Channel channel) throws IOException { // 创建交换器:direct、持久化、不自动删除 channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null); // 创建队列:持久化、非排他、非自动删除的队列 channel.queueDeclare(QUEUE_NAME, true, false, false, null); // 将交换器与队列通过路由键绑定 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY); } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-native\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\RabbitMQProducer.java
1
请完成以下Java代码
public boolean reverseAccrualIt() { throw new UnsupportedOperationException(); } @Override public boolean reActivateIt() { throw new UnsupportedOperationException(); } /************************************************************************* * Get Summary * * @return Summary of Document */ @Override public String getSummary() { final StringBuilder sb = new StringBuilder(); sb.append(getDocumentNo()); // : Grand Total = 123.00 (#1) sb.append(": ").append(Msg.translate(getCtx(), "GrandTotal")).append("=").append(getGrandTotal()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) { sb.append(" - ").append(getDescription()); } return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateInvoiced()); } @Override public String getProcessMsg() { return null; } @Override public int getDoc_User_ID() { return getSalesRep_ID(); } @Override public BigDecimal getApprovalAmt() { return getGrandTotal(); } public void setRMA(final MRMA rma) {
final MInvoice originalInvoice = rma.getOriginalInvoice(); if (originalInvoice == null) { throw new AdempiereException("Not invoiced - RMA: " + rma.getDocumentNo()); } setM_RMA_ID(rma.getM_RMA_ID()); setAD_Org_ID(rma.getAD_Org_ID()); setDescription(rma.getDescription()); InvoiceDocumentLocationAdapterFactory .locationAdapter(this) .setFrom(originalInvoice); setSalesRep_ID(rma.getSalesRep_ID()); setGrandTotal(rma.getAmt()); setOpenAmt(rma.getAmt()); setIsSOTrx(rma.isSOTrx()); setTotalLines(rma.getAmt()); setC_Currency_ID(originalInvoice.getC_Currency_ID()); setIsTaxIncluded(originalInvoice.isTaxIncluded()); setM_PriceList_ID(originalInvoice.getM_PriceList_ID()); setC_Project_ID(originalInvoice.getC_Project_ID()); setC_Activity_ID(originalInvoice.getC_Activity_ID()); setC_Campaign_ID(originalInvoice.getC_Campaign_ID()); setUser1_ID(originalInvoice.getUser1_ID()); setUser2_ID(originalInvoice.getUser2_ID()); } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE * @deprecated Please use {@link IInvoiceBL#isComplete(I_C_Invoice)} */ @Deprecated public boolean isComplete() { return Services.get(IInvoiceBL.class).isComplete(this); } // isComplete } // MInvoice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInvoice.java
1
请完成以下Java代码
public List<String> getAllKeysInJsonUsingJsonNodeFieldNames(String json, ObjectMapper mapper) throws JsonMappingException, JsonProcessingException { List<String> keys = new ArrayList<>(); JsonNode jsonNode = mapper.readTree(json); getAllKeysUsingJsonNodeFieldNames(jsonNode, keys); return keys; } public List<String> getAllKeysInJsonUsingJsonNodeFields(String json, ObjectMapper mapper) throws JsonMappingException, JsonProcessingException { List<String> keys = new ArrayList<>(); JsonNode jsonNode = mapper.readTree(json); getAllKeysUsingJsonNodeFields(jsonNode, keys); return keys; } private void getAllKeysUsingJsonNodeFields(JsonNode jsonNode, List<String> keys) { if (jsonNode.isObject()) { Iterator<Entry<String, JsonNode>> fields = jsonNode.fields(); fields.forEachRemaining(field -> { keys.add(field.getKey()); getAllKeysUsingJsonNodeFieldNames((JsonNode) field.getValue(), keys); }); } else if (jsonNode.isArray()) { ArrayNode arrayField = (ArrayNode) jsonNode; arrayField.forEach(node -> { getAllKeysUsingJsonNodeFieldNames(node, keys); }); } } private void getAllKeysUsingJsonNodeFieldNames(JsonNode jsonNode, List<String> keys) { if (jsonNode.isObject()) { Iterator<String> fieldNames = jsonNode.fieldNames(); fieldNames.forEachRemaining(fieldName -> { keys.add(fieldName); getAllKeysUsingJsonNodeFieldNames(jsonNode.get(fieldName), keys); }); } else if (jsonNode.isArray()) { ArrayNode arrayField = (ArrayNode) jsonNode; arrayField.forEach(node -> { getAllKeysUsingJsonNodeFieldNames(node, keys); }); } } public List<String> getKeysInJsonUsingJsonParser(String json, ObjectMapper mapper) throws IOException {
List<String> keys = new ArrayList<>(); JsonNode jsonNode = mapper.readTree(json); JsonParser jsonParser = jsonNode.traverse(); while (!jsonParser.isClosed()) { if (jsonParser.nextToken() == JsonToken.FIELD_NAME) { keys.add((jsonParser.getCurrentName())); } } return keys; } public List<String> getKeysInJsonUsingJsonParser(String json) throws JsonParseException, IOException { List<String> keys = new ArrayList<>(); JsonFactory factory = new JsonFactory(); JsonParser jsonParser = factory.createParser(json); while (!jsonParser.isClosed()) { if (jsonParser.nextToken() == JsonToken.FIELD_NAME) { keys.add((jsonParser.getCurrentName())); } } return keys; } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\jsonnode\GetAllKeysFromJSON.java
1
请完成以下Java代码
public int getB_TopicType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicType_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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicCategory.java
1
请在Spring Boot框架中完成以下Java代码
public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Bean(name = "jobRepository") public JobRepository getJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "jobLauncher") public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // TaskExecutorJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } @Bean public Step firstStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("firstStep", jobRepository) .<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 1").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item; }) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean public Step secondStep(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("secondStep", jobRepository)
.<String, String>chunk(1, transactionManager) .reader(new IteratorItemReader<>(Stream.of("Data from Step 2").iterator())) .processor(item -> { System.out.println("Processing: " + item); return item; }) .writer(items -> items.forEach(System.out::println)) .build(); } @Bean(name = "parentJob") public Job parentJob(JobRepository jobRepository, @Qualifier("firstStep") Step firstStep, @Qualifier("secondStep") Step secondStep) { return new JobBuilder("parentJob", jobRepository) .start(firstStep) .next(secondStep) .build(); } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\SpringBatchConfig.java
2
请完成以下Java代码
public BigDecimal getQty() { return olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand); } @Override public int getM_HU_PI_Item_Product_ID() { final Integer valueOverrideOrValue = getValueOverrideOrValue(olCand, I_C_OLCand.COLUMNNAME_M_HU_PI_Item_Product_ID); return valueOverrideOrValue == null ? 0 : valueOverrideOrValue; } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { olCand.setM_HU_PI_Item_Product_Override_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return olCand.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId(); } @Override public void setC_UOM_ID(final int uomId) { values.setUomId(UomId.ofRepoIdOrNull(uomId)); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { olCand.setPrice_UOM_Internal_ID(uomId); } } @Override public BigDecimal getQtyTU()
{ return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand)); } @Override public void setQtyTU(final BigDecimal qtyPacks) { values.setQtyTU(qtyPacks); } @Override public int getC_BPartner_ID() { final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand); return BPartnerId.toRepoId(bpartnerId); } @Override public void setC_BPartner_ID(final int partnerId) { olCand.setC_BPartner_Override_ID(partnerId); values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId)); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java
1
请完成以下Java代码
public POSPayment changingStatusToPending() { if (paymentProcessingStatus.isPending()) { return this; } if (!paymentProcessingStatus.isNew()) { throw new AdempiereException("Cannot change status from " + paymentProcessingStatus + " to Pending"); } return toBuilder().paymentProcessingStatus(POSPaymentProcessingStatus.PENDING).build(); } public POSPayment changingStatusToSuccessful() { if (paymentProcessingStatus == POSPaymentProcessingStatus.SUCCESSFUL) { return this; } return toBuilder().paymentProcessingStatus(POSPaymentProcessingStatus.SUCCESSFUL).build(); } public POSPayment changingStatusToDeleted() { if (isDeleted()) { return this; } assertAllowDelete(); return toBuilder().paymentProcessingStatus(POSPaymentProcessingStatus.DELETED).build(); } public POSPayment changingStatusFromRemote(@NonNull final POSPaymentProcessResponse response) { paymentMethod.assertCard(); // NOTE: when changing status from remote we cannot validate if the status transition is OK // we have to accept what we have on remote. return toBuilder() .paymentProcessingStatus(response.getStatus()) .cardProcessingDetails(POSPaymentCardProcessingDetails.builder() .config(response.getConfig()) .transactionId(response.getTransactionId()) .summary(response.getSummary()) .cardReader(response.getCardReader()) .build()) .build(); } public POSPayment withPaymentReceipt(@Nullable final PaymentId paymentReceiptId) { if (PaymentId.equals(this.paymentReceiptId, paymentReceiptId))
{ return this; } if (paymentReceiptId != null && !paymentProcessingStatus.isSuccessful()) { throw new AdempiereException("Cannot set a payment receipt if status is not successful"); } if (this.paymentReceiptId != null && paymentReceiptId != null) { throw new AdempiereException("Changing the payment receipt is not allowed"); } return toBuilder().paymentReceiptId(paymentReceiptId).build(); } public POSPayment withCashTenderedAmount(@NonNull final BigDecimal cashTenderedAmountBD) { paymentMethod.assertCash(); Check.assume(cashTenderedAmountBD.signum() > 0, "Cash Tendered Amount must be positive"); final Money cashTenderedAmountNew = Money.of(cashTenderedAmountBD, this.cashTenderedAmount.getCurrencyId()); if (Money.equals(this.cashTenderedAmount, cashTenderedAmountNew)) { return this; } return toBuilder().cashTenderedAmount(cashTenderedAmountNew).build(); } public POSPayment withCardPayAmount(@NonNull final BigDecimal cardPayAmountBD) { paymentMethod.assertCard(); Check.assume(cardPayAmountBD.signum() > 0, "Card Pay Amount must be positive"); final Money amountNew = Money.of(cardPayAmountBD, this.amount.getCurrencyId()); if (Money.equals(this.amount, amountNew)) { return this; } return toBuilder().amount(amountNew).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPayment.java
1
请完成以下Java代码
private void mapVirtualColumnsInSourceTable(final Set<String> toColumnsWithoutAPhysicalFromColumn) { if (Adempiere.isUnitTestMode()) { return; } final POInfo fromTablePOInfo = POInfo.getPOInfo(fromTableName); Check.assumeNotNull(fromTablePOInfo, "cannot find POInfo for table name: {}", fromTableName); toColumnsWithoutAPhysicalFromColumn.stream() .filter(fromTablePOInfo::isVirtualColumn) .forEach(fromColumnName -> { final String toColumnName = fromColumnName; final String columnSql = ColumnSql.ofSql(fromTablePOInfo.getColumnSql(fromColumnName), fromTableName).toSqlString(); Check.assumeNotEmpty(columnSql, "columnSQL unexpectedly null for {}.{}", fromTableName, fromColumnName); mapColumnToSql(toColumnName, columnSql); }); } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapColumn(final String toColumnName, final String fromColumnName) { final IQueryInsertFromColumn from = new QueryInsertFromColumn(fromColumnName); mapColumn(toColumnName, from); return this; } private final QueryInsertExecutor<ToModelType, FromModelType> mapColumn(final String toColumnName, final IQueryInsertFromColumn from) { this.toColumn2fromColumn.put(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToConstant(final String toColumnName, final Object constantValue) { final IQueryInsertFromColumn from = new ConstantQueryInsertFromColumn(constantValue); mapColumn(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToSql(final String toColumnName, final String fromSql) { final IQueryInsertFromColumn from = new SqlQueryInsertFromColumn(fromSql); mapColumn(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapPrimaryKey() { final String toColumnName = getToKeyColumnName(); final IQueryInsertFromColumn from = new PrimaryKeyQueryInsertFromColumn(getToTableName()); mapColumn(toColumnName, from); return this; }
@Override public QueryInsertExecutor<ToModelType, FromModelType> creatingSelectionOfInsertedRows() { this.createSelectionOfInsertedRows = true; return this; } /* package */ boolean isCreateSelectionOfInsertedRows() { return createSelectionOfInsertedRows; } /* package */String getToKeyColumnName() { return InterfaceWrapperHelper.getKeyColumnName(toModelClass); } /** * @return "To ColumnName" to "From Column" map */ /* package */ Map<String, IQueryInsertFromColumn> getColumnMapping() { return toColumn2fromColumnRO; } /* package */ boolean isEmpty() { return toColumn2fromColumn.isEmpty(); } /* package */ String getToTableName() { return toTableName; } /* package */ Class<ToModelType> getToModelClass() { return toModelClass; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryInsertExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public class TodoControllerJpa { public TodoControllerJpa(TodoRepository todoRepository) { super(); this.todoRepository = todoRepository; } private final TodoRepository todoRepository; @RequestMapping("list-todos") public String listAllTodos(ModelMap model) { String username = getLoggedInUsername(model); List<Todo> todos = todoRepository.findByUsername(username); model.addAttribute("todos", todos); return "listTodos"; } //GET, POST @RequestMapping(value="add-todo", method = RequestMethod.GET) public String showNewTodoPage(ModelMap model) { String username = getLoggedInUsername(model); Todo todo = new Todo(0, username, "", LocalDate.now().plusYears(1), false); model.put("todo", todo); return "todo"; } @RequestMapping(value="add-todo", method = RequestMethod.POST) public String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todo.setUsername(username); todoRepository.save(todo); // todoService.addTodo(username, todo.getDescription(), // todo.getTargetDate(), todo.isDone()); return "redirect:list-todos"; } @RequestMapping("delete-todo") public String deleteTodo(@RequestParam int id) { //Delete todo todoRepository.deleteById(id);
return "redirect:list-todos"; } @RequestMapping(value="update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { Todo todo = todoRepository.findById(id).get(); model.addAttribute("todo", todo); return "todo"; } @RequestMapping(value="update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todo.setUsername(username); todoRepository.save(todo); return "redirect:list-todos"; } private String getLoggedInUsername(ModelMap model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication.getName(); } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoControllerJpa.java
2
请完成以下Java代码
public SetRemovalTimeToHistoricBatchesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricBatchesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); mode = Mode.CLEARED_REMOVAL_TIME; return this; } public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricBatchesCmd(this)); } public HistoricBatchQuery getQuery() { return query; } public List<String> getIds() { return ids;
} public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricBatchesBuilderImpl.java
1
请完成以下Java代码
public class GrpcExceptionListener<ReqT, RespT> extends SimpleForwardingServerCallListener<ReqT> { private final GrpcExceptionResponseHandler exceptionHandler; private final ServerCall<ReqT, RespT> serverCall; /** * Creates a new exception handling grpc server call listener. * * @param delegate The listener to delegate to (Required). * @param serverCall The server call to used to send the error responses (Required). * @param exceptionHandler The exception handler to use (Required). */ protected GrpcExceptionListener( final Listener<ReqT> delegate, final ServerCall<ReqT, RespT> serverCall, final GrpcExceptionResponseHandler exceptionHandler) { super(delegate); this.serverCall = serverCall; this.exceptionHandler = exceptionHandler; }
@Override public void onMessage(final ReqT message) { try { super.onMessage(message); } catch (final Throwable error) { // For errors thrown in the request's StreamObserver#onNext this.exceptionHandler.handleError(this.serverCall, error); } } @Override public void onHalfClose() { try { super.onHalfClose(); } catch (final Throwable error) { // For errors from unary grpc method implementation methods directly (Not via StreamObserver) // For errors thrown in the request's StreamObserver#onCompleted this.exceptionHandler.handleError(this.serverCall, error); } } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\error\GrpcExceptionListener.java
1
请完成以下Java代码
public void setLocalRootLocation (final String LocalRootLocation) { set_Value (COLUMNNAME_LocalRootLocation, LocalRootLocation); } @Override public String getLocalRootLocation() { return get_ValueAsString(COLUMNNAME_LocalRootLocation); } @Override public void setProcessedDirectory (final String ProcessedDirectory) { set_Value (COLUMNNAME_ProcessedDirectory, ProcessedDirectory); } @Override public String getProcessedDirectory() { return get_ValueAsString(COLUMNNAME_ProcessedDirectory); } @Override public void setProductFileNamePattern (final @Nullable String ProductFileNamePattern) { set_Value (COLUMNNAME_ProductFileNamePattern, ProductFileNamePattern); } @Override
public String getProductFileNamePattern() { return get_ValueAsString(COLUMNNAME_ProductFileNamePattern); } @Override public void setPurchaseOrderFileNamePattern (final @Nullable String PurchaseOrderFileNamePattern) { set_Value (COLUMNNAME_PurchaseOrderFileNamePattern, PurchaseOrderFileNamePattern); } @Override public String getPurchaseOrderFileNamePattern() { return get_ValueAsString(COLUMNNAME_PurchaseOrderFileNamePattern); } @Override public void setWarehouseFileNamePattern (final @Nullable String WarehouseFileNamePattern) { set_Value (COLUMNNAME_WarehouseFileNamePattern, WarehouseFileNamePattern); } @Override public String getWarehouseFileNamePattern() { return get_ValueAsString(COLUMNNAME_WarehouseFileNamePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_LocalFile.java
1
请完成以下Java代码
public void addEmit(String keyword) { if (this.emits == null) { this.emits = new TreeSet<String>(); } this.emits.add(keyword); } /** * 添加一些匹配到的模式串 * @param emits */ public void addEmit(Collection<String> emits) { for (String emit : emits) { addEmit(emit); } } /** * 获取这个节点代表的模式串(们) * @return */ public Collection<String> emit() { return this.emits == null ? Collections.<String>emptyList() : this.emits; } /** * 获取failure状态 * @return */ public State failure() { return this.failure; } /** * 设置failure状态 * @param failState */ public void setFailure(State failState) { this.failure = failState; } /** * 转移到下一个状态 * @param character 希望按此字符转移 * @param ignoreRootState 是否忽略根节点,如果是根节点自己调用则应该是true,否则为false * @return 转移结果 */ private State nextState(Character character, boolean ignoreRootState) { State nextState = this.success.get(character); if (!ignoreRootState && nextState == null && this.depth == 0) { nextState = this; } return nextState; } /** * 按照character转移,根节点转移失败会返回自己(永远不会返回null) * @param character * @return */ public State nextState(Character character)
{ return nextState(character, false); } /** * 按照character转移,任何节点转移失败会返回null * @param character * @return */ public State nextStateIgnoreRootState(Character character) { return nextState(character, true); } public State addState(Character character) { State nextState = nextStateIgnoreRootState(character); if (nextState == null) { nextState = new State(this.depth + 1); this.success.put(character, nextState); } return nextState; } public Collection<State> getStates() { return this.success.values(); } public Collection<Character> getTransitions() { return this.success.keySet(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("State{"); sb.append("depth=").append(depth); sb.append(", emits=").append(emits); sb.append(", success=").append(success.keySet()); sb.append(", failure=").append(failure); sb.append('}'); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\State.java
1
请完成以下Java代码
public int getLineNo() { return lineNo; } @Override public void setLineNo(final int lineNo) { this.lineNo = lineNo; } @Override public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes) { this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes); } @Override public List<IInvoiceLineAttribute> getInvoiceLineAttributes() { return invoiceLineAttributes; } @Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate() { return iciolsToUpdate; } @Override public int getC_PaymentTerm_ID() { return C_PaymentTerm_ID; } @Override public void setC_PaymentTerm_ID(final int paymentTermId) { C_PaymentTerm_ID = paymentTermId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class); } @Override public void setC_DocType(org.compiere.model.I_C_DocType C_DocType) { set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType); } /** Set Belegart. @param C_DocType_ID Document type or rules */ @Override public void setC_DocType_ID (int C_DocType_ID)
{ if (C_DocType_ID < 0) set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Document type or rules */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Document_Action_Access.java
1
请完成以下Java代码
public void ignoredUnsupportedAttribute(String attribute, String element, String id) { logInfo( "005", "The attribute '{}' based on the element '{}' of the sentry with id '{}' is not supported and will be ignored.", attribute, element, id ); } public void multipleIgnoredConditions(String id) { logInfo( "006", "The ifPart of the sentry with id '{}' has more than one condition. " + "Only the first one will be used and the other conditions will be ignored.", id );
} public CmmnTransformException nonMatchingVariableEvents(String id) { return new CmmnTransformException(exceptionMessage( "007", "The variableOnPart of the sentry with id '{}' must have one valid variable event. ", id )); } public CmmnTransformException emptyVariableName(String id) { return new CmmnTransformException(exceptionMessage( "008", "The variableOnPart of the sentry with id '{}' must have variable name. ", id )); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransformerLogger.java
1
请在Spring Boot框架中完成以下Java代码
public DeviceConfig.Builder setDeviceClassname(final String deviceClassname) { this.deviceClassname = deviceClassname; return this; } private String getDeviceClassname() { Check.assumeNotEmpty(deviceClassname, "deviceClassname is not empty"); return deviceClassname; } public DeviceConfig.Builder setParameterValueSupplier(final IDeviceParameterValueSupplier parameterValueSupplier) { this.parameterValueSupplier = parameterValueSupplier; return this; } private IDeviceParameterValueSupplier getParameterValueSupplier() { Check.assumeNotNull(parameterValueSupplier, "Parameter parameterValueSupplier is not null"); return parameterValueSupplier; } public DeviceConfig.Builder setRequestClassnamesSupplier(final IDeviceRequestClassnamesSupplier requestClassnamesSupplier) { this.requestClassnamesSupplier = requestClassnamesSupplier; return this; } private IDeviceRequestClassnamesSupplier getRequestClassnamesSupplier() { Check.assumeNotNull(requestClassnamesSupplier, "Parameter requestClassnamesSupplier is not null"); return requestClassnamesSupplier; } public DeviceConfig.Builder setAssignedWarehouseIds(final Set<WarehouseId> assignedWareouseIds) { this.assignedWareouseIds = assignedWareouseIds; return this; } private ImmutableSet<WarehouseId> getAssignedWarehouseIds() { return assignedWareouseIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedWareouseIds); } @NonNull
private ImmutableSet<LocatorId> getAssignedLocatorIds() { return assignedLocatorIds == null ? ImmutableSet.of() : ImmutableSet.copyOf(assignedLocatorIds); } @NonNull public DeviceConfig.Builder setAssignedLocatorIds(final Set<LocatorId> assignedLocatorIds) { this.assignedLocatorIds = assignedLocatorIds; return this; } @NonNull public DeviceConfig.Builder setBeforeHooksClassname(@NonNull final ImmutableList<String> beforeHooksClassname) { this.beforeHooksClassname = beforeHooksClassname; return this; } @NonNull private ImmutableList<String> getBeforeHooksClassname() { return Optional.ofNullable(beforeHooksClassname).orElseGet(ImmutableList::of); } @NonNull public DeviceConfig.Builder setDeviceConfigParams(@NonNull final ImmutableMap<String, String> deviceConfigParams) { this.deviceConfigParams = deviceConfigParams; return this; } @NonNull private ImmutableMap<String, String> getDeviceConfigParams() { return deviceConfigParams == null ? ImmutableMap.of() : deviceConfigParams; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\DeviceConfig.java
2
请在Spring Boot框架中完成以下Java代码
public int create(MemberReadHistory memberReadHistory) { if (memberReadHistory.getProductId() == null) { return 0; } UmsMember member = memberService.getCurrentMember(); memberReadHistory.setMemberId(member.getId()); memberReadHistory.setMemberNickname(member.getNickname()); memberReadHistory.setMemberIcon(member.getIcon()); memberReadHistory.setId(null); memberReadHistory.setCreateTime(new Date()); if (sqlEnable) { PmsProduct product = productMapper.selectByPrimaryKey(memberReadHistory.getProductId()); if (product == null || product.getDeleteStatus() == 1) { return 0; } memberReadHistory.setProductName(product.getName()); memberReadHistory.setProductSubTitle(product.getSubTitle()); memberReadHistory.setProductPrice(product.getPrice() + ""); memberReadHistory.setProductPic(product.getPic()); } memberReadHistoryRepository.save(memberReadHistory); return 1; } @Override public int delete(List<String> ids) { List<MemberReadHistory> deleteList = new ArrayList<>(); for(String id:ids){ MemberReadHistory memberReadHistory = new MemberReadHistory(); memberReadHistory.setId(id); deleteList.add(memberReadHistory); } memberReadHistoryRepository.deleteAll(deleteList); return ids.size();
} @Override public Page<MemberReadHistory> list(Integer pageNum, Integer pageSize) { UmsMember member = memberService.getCurrentMember(); Pageable pageable = PageRequest.of(pageNum-1, pageSize); return memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(member.getId(),pageable); } @Override public void clear() { UmsMember member = memberService.getCurrentMember(); memberReadHistoryRepository.deleteAllByMemberId(member.getId()); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\MemberReadHistoryServiceImpl.java
2
请完成以下Java代码
public IMutableHUContext setHUPackingMaterialsCollector(@NonNull final IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> huPackingMaterialsCollector) { this._huPackingMaterialsCollector = huPackingMaterialsCollector; return this; } @Override public CompositeHUTrxListener getTrxListeners() { if (_trxListeners == null) { final CompositeHUTrxListener trxListeners = new CompositeHUTrxListener(); // Add system registered listeners final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); trxListeners.addListeners(huTrxBL.getHUTrxListenersList()); _trxListeners = trxListeners; } return _trxListeners; } @Override public void addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener) { emptyHUListeners.add(emptyHUListener); } @Override public List<EmptyHUListener> getEmptyHUListeners() { return ImmutableList.copyOf(emptyHUListeners); } @Override public void flush() { final IAttributeStorageFactory attributesStorageFactory = _attributesStorageFactory;
if(attributesStorageFactory != null) { attributesStorageFactory.flush(); } } @Override public IAutoCloseable temporarilyDontDestroyHU(@NonNull final HuId huId) { huIdsToNotDestroy.add(huId); return () -> huIdsToNotDestroy.remove(huId); } @Override public boolean isDontDestroyHu(@NonNull final HuId huId) { return huIdsToNotDestroy.contains(huId); } @Override public boolean isPropertyTrue(@NonNull final String propertyName) { final Boolean isPropertyTrue = getProperty(propertyName); return isPropertyTrue != null && isPropertyTrue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\MutableHUContext.java
1
请在Spring Boot框架中完成以下Java代码
public void fetchActiveAlarms() { log.trace("[{}, subId: {}] Fetching active alarms from DB", subscription.getSessionId(), subscription.getSubscriptionId()); OriginatorAlarmFilter originatorAlarmFilter = new OriginatorAlarmFilter(subscription.getEntityId(), subscription.getTypeList(), subscription.getSeverityList()); List<UUID> alarmIds = alarmService.findActiveOriginatorAlarms(subscription.getTenantId(), originatorAlarmFilter, alarmsPerAlarmStatusSubscriptionCacheSize); subscription.getAlarmIds().addAll(alarmIds); subscription.setHasMoreAlarmsInDB(alarmIds.size() == alarmsPerAlarmStatusSubscriptionCacheSize); } private void handleAlarmStatusSubscriptionUpdate(TbSubscription<AlarmSubscriptionUpdate> sub, AlarmSubscriptionUpdate subscriptionUpdate) { try { AlarmInfo alarm = subscriptionUpdate.getAlarm(); if (!alarm.getOriginator().equals(subscription.getEntityId())) { return; } Set<UUID> alarmsIds = subscription.getAlarmIds(); if (alarmsIds.contains(alarm.getId().getId())) { if (!subscription.matches(alarm) || subscriptionUpdate.isAlarmDeleted()) { alarmsIds.remove(alarm.getId().getId()); if (alarmsIds.isEmpty()) { if (subscription.isHasMoreAlarmsInDB()) { fetchActiveAlarms(); if (alarmsIds.isEmpty()) { sendUpdate(); }
} else { sendUpdate(); } } } } else if (subscription.matches(alarm)) { if (alarmsIds.size() < alarmsPerAlarmStatusSubscriptionCacheSize) { alarmsIds.add(alarm.getId().getId()); if (alarmsIds.size() == 1) { sendUpdate(); } } else { subscription.setHasMoreAlarmsInDB(true); } } } catch (Exception e) { log.error("[{}, subId: {}] Failed to handle update for alarm status subscription: {}", subscription.getSessionId(), subscription.getSubscriptionId(), subscriptionUpdate, e); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmStatusSubCtx.java
2
请在Spring Boot框架中完成以下Java代码
public void onFailure(RuleEngineException e) { if (ExceptionUtil.lookupExceptionInCause(e, AbstractRateLimitException.class) != null) { onRateLimit(e); return; } log.trace("[{}] ON FAILURE", id, e); if (failedMsgTimer != null) { failedMsgTimer.record(System.currentTimeMillis() - startMsgProcessing, TimeUnit.MILLISECONDS); } ctx.onFailure(tenantId, id, e); } @Override public boolean isMsgValid() {
return !ctx.isCanceled(); } @Override public void onProcessingStart(RuleNodeInfo ruleNodeInfo) { log.trace("[{}] ON PROCESSING START: {}", id, ruleNodeInfo); ctx.onProcessingStart(id, ruleNodeInfo); } @Override public void onProcessingEnd(RuleNodeId ruleNodeId) { log.trace("[{}] ON PROCESSING END: {}", id, ruleNodeId); ctx.onProcessingEnd(id, ruleNodeId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbMsgPackCallback.java
2
请在Spring Boot框架中完成以下Java代码
public class XmlBody { @Nullable String roleTitle; @NonNull String role; @NonNull String place; @NonNull XmlProlog prolog; @Nullable String remark; @Nullable XmlBalance balance; @NonNull XmlEsr esr; @NonNull XmlTiers tiers; @NonNull XmlLaw law; @NonNull XmlTreatment treatment; @Singular List<XmlService> services; @Singular List<XmlDocument> documents; public XmlBody withMod(@Nullable final BodyMod bodyMod) { if (bodyMod == null) { return this; } final XmlBodyBuilder builder = toBuilder(); if (bodyMod.getEsr() != null) { builder.esr(bodyMod.getEsr()); } builder.prolog(prolog.withMod(bodyMod.getPrologMod())); if (balance != null) { builder.balance(balance.withMod(bodyMod.getBalanceMod())); } else if (tiers.getBalance() != null) { tiers.getBalance().withMod(bodyMod.getBalanceMod()); } if (bodyMod.getServiceModsWithSelectors() != null) { final ImmutableMap<Integer, XmlService> recordId2xService = Maps.uniqueIndex(services, XmlService::getRecordId); builder.clearServices(); for (final ServiceModWithSelector serviceModWithSelector : bodyMod.getServiceModsWithSelectors()) {
// we assume that this method would never have been invoked if this was null final XmlService xServiceToModify = recordId2xService.get(serviceModWithSelector.getRecordId()); builder.service(xServiceToModify.withMod(serviceModWithSelector.getServiceMod())); } } if (bodyMod.getDocuments() != null) { builder .clearDocuments() .documents(bodyMod.getDocuments()); } return builder.build(); } @Value @Builder public static class BodyMod { @Nullable PrologMod prologMod; @Nullable BalanceMod balanceMod; @Nullable XmlEsr esr; @Nullable List<ServiceModWithSelector> serviceModsWithSelectors; /** * if not null, it will completely replace the body's former documents. */ List<XmlDocument> documents; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\payload\XmlBody.java
2
请在Spring Boot框架中完成以下Java代码
public class RequestId implements RepoIdAware { @JsonCreator public static RequestId ofRepoId(final int repoId) { return new RequestId(repoId); } public static RequestId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(final RequestId requestId) { return requestId != null ? requestId.getRepoId() : -1; }
int repoId; private RequestId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "R_Request_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\RequestId.java
2
请完成以下Java代码
public class NameGenderEntity { private Long count; private String gender; private String name; private Float probability; public NameGenderEntity() { super(); } public Long getCount() { return count; } public void setCount(Long count) { this.count = count; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Float getProbability() { return probability; } public void setProbability(Float probability) { this.probability = probability; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((count == null) ? 0 : count.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((probability == null) ? 0 : probability.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NameGenderEntity other = (NameGenderEntity) obj; if (count == null) { if (other.count != null) return false; } else if (!count.equals(other.count)) return false; if (gender == null) { if (other.gender != null) return false; } else if (!gender.equals(other.gender)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (probability == null) { if (other.probability != null) return false; } else if (!probability.equals(other.probability)) return false; return true; } @Override public String toString() { return "NameGenderModel [count=" + count + ", gender=" + gender + ", name=" + name + ", probability=" + probability + "]"; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameGenderEntity.java
1
请完成以下Java代码
public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public Integer getStatus() { return status; }
public void setStatus(Integer status) { this.status = status; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", icon=").append(icon); sb.append(", email=").append(email); sb.append(", nickName=").append(nickName); sb.append(", note=").append(note); sb.append(", createTime=").append(createTime); sb.append(", loginTime=").append(loginTime); sb.append(", status=").append(status); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java
1
请完成以下Java代码
public void setCell(final int rowIndex, @NonNull final String columnName, @NonNull final Cell value) { while (rowIndex >= rowsList.size()) { addRow(new Row()); } rowsList.get(rowIndex).put(columnName, value); } public boolean isEmpty() {return header.isEmpty() || rowsList.isEmpty();} public void addRow(@NonNull final Row row) { rowsList.add(row); } public void addRows(@NonNull final Collection<Row> rows) { rowsList.addAll(rows); } public void addRows(@NonNull final Table other) { rowsList.addAll(other.rowsList); } public void removeColumnsWithBlankValues() { header.removeIf(this::isBlankColumn); } private boolean isBlankColumn(final String columnName) { return rowsList.stream().allMatch(row -> row.isBlankColumn(columnName)); } public void moveColumnsToStart(final String... columnNamesToMove) { if (columnNamesToMove == null || columnNamesToMove.length == 0) { return; } for (int i = columnNamesToMove.length - 1; i >= 0; i--) { if (columnNamesToMove[i] == null) { continue; } final String columnNameToMove = columnNamesToMove[i]; if (header.remove(columnNameToMove)) { header.add(0, columnNameToMove); } } } public void moveColumnsToEnd(final String... columnNamesToMove) { if (columnNamesToMove == null) { return; } for (final String columnNameToMove : columnNamesToMove) { if (columnNameToMove == null) { continue; } if (header.remove(columnNameToMove)) { header.add(columnNameToMove); } } } public Optional<Table> removeColumnsWithSameValue() { if (rowsList.isEmpty()) { return Optional.empty(); } final Table removedTable = new Table(); for (final String columnName : new ArrayList<>(header)) {
final Cell commonValue = getCommonValue(columnName).orElse(null); if (commonValue != null) { header.remove(columnName); removedTable.addHeader(columnName); removedTable.setCell(0, columnName, commonValue); } } if (removedTable.isEmpty()) { return Optional.empty(); } return Optional.of(removedTable); } private Optional<Cell> getCommonValue(@NonNull final String columnName) { if (rowsList.isEmpty()) { return Optional.empty(); } final Cell firstValue = rowsList.get(0).getCell(columnName); for (int i = 1; i < rowsList.size(); i++) { final Cell value = rowsList.get(i).getCell(columnName); if (!Objects.equals(value, firstValue)) { return Optional.empty(); } } return Optional.of(firstValue); } public TablePrinter toPrint() { return new TablePrinter(this); } public String toTabularString() { return toPrint().toString(); } @Override @Deprecated public String toString() {return toTabularString();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Table.java
1
请完成以下Java代码
public final boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException { return trace(sql, () -> delegate.execute(sql, autoGeneratedKeys)); } @Override public final boolean execute(final String sql, final int[] columnIndexes) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnIndexes)); } @Override public final boolean execute(final String sql, final String[] columnNames) throws SQLException { return trace(sql, () -> delegate.execute(sql, columnNames)); } @Override public final int getResultSetHoldability() throws SQLException { return delegate.getResultSetHoldability(); } @Override public final boolean isClosed() throws SQLException { return delegate.isClosed(); } @Override
public final void setPoolable(final boolean poolable) throws SQLException { delegate.setPoolable(poolable); } @Override public final boolean isPoolable() throws SQLException { return delegate.isPoolable(); } @Override public final void closeOnCompletion() throws SQLException { delegate.closeOnCompletion(); } @Override public final boolean isCloseOnCompletion() throws SQLException { return delegate.isCloseOnCompletion(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java
1
请完成以下Java代码
public class KeyStoreKeyFactory { private final Resource resource; private final char[] password; private @Nullable KeyStore store; private final Object lock = new Object(); private final String type; public KeyStoreKeyFactory(Resource resource, char[] password) { this(resource, password, type(resource)); } private static String type(Resource resource) { String ext = StringUtils.getFilenameExtension(resource.getFilename()); return (ext != null) ? ext : "jks"; } public KeyStoreKeyFactory(Resource resource, char[] password, String type) { this.resource = resource; this.password = password; this.type = type; } public KeyPair getKeyPair(String alias) { return getKeyPair(alias, this.password); } public KeyPair getKeyPair(String alias, char[] password) { try { synchronized (this.lock) { if (this.store == null) { synchronized (this.lock) {
this.store = KeyStore.getInstance(this.type); try (InputStream stream = this.resource.getInputStream()) { this.store.load(stream, this.password); } } } } RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password); Certificate certificate = this.store.getCertificate(alias); PublicKey publicKey = null; if (certificate != null) { publicKey = certificate.getPublicKey(); } else if (key != null) { RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); } return new KeyPair(publicKey, key); } catch (Exception ex) { throw new IllegalStateException("Cannot load keys from store: " + this.resource, ex); } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\KeyStoreKeyFactory.java
1
请完成以下Java代码
public class SetTimerJobRetriesCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; private final String jobId; private final int retries; public SetTimerJobRetriesCmd(String jobId, int retries) { if (jobId == null || jobId.length() < 1) { throw new ActivitiIllegalArgumentException( "The job id is mandatory, but '" + jobId + "' has been provided." ); } if (retries < 0) { throw new ActivitiIllegalArgumentException( "The number of job retries must be a non-negative Integer, but '" + retries + "' has been provided." ); } this.jobId = jobId; this.retries = retries; } public Void execute(CommandContext commandContext) {
TimerJobEntity job = commandContext.getTimerJobEntityManager().findById(jobId); if (job != null) { job.setRetries(retries); if (commandContext.getEventDispatcher().isEnabled()) { commandContext .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, job)); } } else { throw new ActivitiObjectNotFoundException("No timer job found with id '" + jobId + "'.", Job.class); } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetTimerJobRetriesCmd.java
1