instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public Long getTotal() { return this.query().getTotalElements(); } public Object getContent() { return this.query().getContent(); } } public class PaginationFormatting { private PaginationMultiTypeValuesHelper multiValue = new PaginationMultiTypeValuesHelper(); private Map<String, PaginationMultiTypeValuesHelper> results = new HashMap<>(); public Map<String, PaginationMultiTypeValuesHelper> filterQuery(String sex, String email, Pageable pageable) { Types typeInstance; if (sex.length() == 0 && email.length() == 0) { typeInstance = new AllType(sex, email, pageable); } else if (sex.length() > 0 && email.length() > 0) { typeInstance = new SexEmailType(sex, email, pageable); } else {
typeInstance = new SexType(sex, email, pageable); } this.multiValue.setCount(typeInstance.getCount()); this.multiValue.setPage(typeInstance.getPageNumber() + 1); this.multiValue.setResults(typeInstance.getContent()); this.multiValue.setTotal(typeInstance.getTotal()); this.results.put("data", this.multiValue); return results; } }
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\pagination\PaginationFormatting.java
2
请完成以下Java代码
public static abstract class AbstractImportResourceResolver extends AbstractCacheResourceResolver implements ImportResourceResolver { /** * @inheritDoc */ @Override public Optional<Resource> resolve(@NonNull Region<?, ?> region) { Assert.notNull(region, "Region must not be null"); String resourceLocation = getResourceLocation(region, CACHE_DATA_IMPORT_RESOURCE_LOCATION_PROPERTY_NAME); Optional<Resource> resource = resolve(resourceLocation); boolean exists = resource.isPresent(); boolean readable = exists && resource.filter(Resource::isReadable).isPresent(); if (!exists) { getLogger().warn("Resource [{}] for Region [{}] could not be found; skipping import for Region", resourceLocation, region.getFullPath()); } else { Assert.state(readable, () -> String.format("Resource [%1$s] for Region [%2$s] is not readable", resourceLocation, region.getFullPath())); } return resource;
} @Nullable @Override protected Resource onMissingResource(@Nullable Resource resource, @NonNull String location) { getLogger().warn("Resource [{}] at location [{}] does not exist; skipping import", ResourceUtils.nullSafeGetDescription(resource), location); return null; } } /** * Resolves the {@link Resource} to {@literal import} from the {@literal classpath}. */ public static class ClassPathImportResourceResolver extends AbstractImportResourceResolver { @Override protected @NonNull String getResourcePath() { return ResourcePrefix.CLASSPATH_URL_PREFIX.toUrlPrefix(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\support\ResourceCapableCacheDataImporterExporter.java
1
请完成以下Java代码
public ExternalTaskQueryTopicBuilder processInstanceVariableEquals(String name, Object value) { currentInstruction.addFilterVariable(name, value); return this; } public ExternalTaskQueryTopicBuilder businessKey(String businessKey) { currentInstruction.setBusinessKey(businessKey); return this; } public ExternalTaskQueryTopicBuilder processDefinitionId(String processDefinitionId) { currentInstruction.setProcessDefinitionId(processDefinitionId); return this; } public ExternalTaskQueryTopicBuilder processDefinitionIdIn(String... processDefinitionIds) { currentInstruction.setProcessDefinitionIds(processDefinitionIds); return this; } public ExternalTaskQueryTopicBuilder processDefinitionKey(String processDefinitionKey) { currentInstruction.setProcessDefinitionKey(processDefinitionKey); return this; } public ExternalTaskQueryTopicBuilder processDefinitionKeyIn(String... processDefinitionKeys) { currentInstruction.setProcessDefinitionKeys(processDefinitionKeys); return this; } public ExternalTaskQueryTopicBuilder processDefinitionVersionTag(String processDefinitionVersionTag) { currentInstruction.setProcessDefinitionVersionTag(processDefinitionVersionTag); return this; }
public ExternalTaskQueryTopicBuilder withoutTenantId() { currentInstruction.setTenantIds(null); return this; } public ExternalTaskQueryTopicBuilder tenantIdIn(String... tenantIds) { currentInstruction.setTenantIds(tenantIds); return this; } protected void submitCurrentInstruction() { if (currentInstruction != null) { this.instructions.put(currentInstruction.getTopicName(), currentInstruction); } } public ExternalTaskQueryTopicBuilder enableCustomObjectDeserialization() { currentInstruction.setDeserializeVariables(true); return this; } public ExternalTaskQueryTopicBuilder localVariables() { currentInstruction.setLocalVariables(true); return this; } public ExternalTaskQueryTopicBuilder includeExtensionProperties() { currentInstruction.setIncludeExtensionProperties(true); return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\ExternalTaskQueryTopicBuilderImpl.java
1
请完成以下Java代码
public class DependencyGroup { private String name; @JsonIgnore private String compatibilityRange; @JsonIgnore private String bom; @JsonIgnore private String repository; final List<Dependency> content = new ArrayList<>(); /** * Return the name of this group. * @return the name of the group */ public String getName() { return this.name; } public void setName(String name) { this.name = name; } /** * Return the default compatibility range to apply to all dependencies of this group * unless specified otherwise. * @return the compatibility range */ public String getCompatibilityRange() { return this.compatibilityRange; } public void setCompatibilityRange(String compatibilityRange) { this.compatibilityRange = compatibilityRange; } /** * Return the default bom to associate to all dependencies of this group unless * specified otherwise. * @return the BOM */ public String getBom() { return this.bom; }
public void setBom(String bom) { this.bom = bom; } /** * Return the default repository to associate to all dependencies of this group unless * specified otherwise. * @return the repository */ public String getRepository() { return this.repository; } public void setRepository(String repository) { this.repository = repository; } /** * Return the {@link Dependency dependencies} of this group. * @return the content */ public List<Dependency> getContent() { return this.content; } /** * Create a new {@link DependencyGroup} instance with the given name. * @param name the name of the group * @return a new {@link DependencyGroup} instance */ public static DependencyGroup create(String name) { DependencyGroup group = new DependencyGroup(); group.setName(name); return group; } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependencyGroup.java
1
请在Spring Boot框架中完成以下Java代码
private <R> Result<R> checkEntityInternal(DegradeRuleEntity entity) { if (StringUtil.isBlank(entity.getApp())) { return Result.ofFail(-1, "app can't be blank"); } if (StringUtil.isBlank(entity.getIp())) { return Result.ofFail(-1, "ip can't be null or empty"); } if (entity.getPort() == null || entity.getPort() <= 0) { return Result.ofFail(-1, "invalid port: " + entity.getPort()); } if (StringUtil.isBlank(entity.getLimitApp())) { return Result.ofFail(-1, "limitApp can't be null or empty"); } if (StringUtil.isBlank(entity.getResource())) { return Result.ofFail(-1, "resource can't be null or empty"); } Double threshold = entity.getCount(); if (threshold == null || threshold < 0) { return Result.ofFail(-1, "invalid threshold: " + threshold); } Integer recoveryTimeoutSec = entity.getTimeWindow(); if (recoveryTimeoutSec == null || recoveryTimeoutSec <= 0) { return Result.ofFail(-1, "recoveryTimeout should be positive"); } Integer strategy = entity.getGrade(); if (strategy == null) { return Result.ofFail(-1, "circuit breaker strategy cannot be null"); } if (strategy < CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType() || strategy > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
return Result.ofFail(-1, "Invalid circuit breaker strategy: " + strategy); } if (entity.getMinRequestAmount() == null || entity.getMinRequestAmount() <= 0) { return Result.ofFail(-1, "Invalid minRequestAmount"); } if (entity.getStatIntervalMs() == null || entity.getStatIntervalMs() <= 0) { return Result.ofFail(-1, "Invalid statInterval"); } if (strategy == RuleConstant.DEGRADE_GRADE_RT) { Double slowRatio = entity.getSlowRatioThreshold(); if (slowRatio == null) { return Result.ofFail(-1, "SlowRatioThreshold is required for slow request ratio strategy"); } else if (slowRatio < 0 || slowRatio > 1) { return Result.ofFail(-1, "SlowRatioThreshold should be in range: [0.0, 1.0]"); } } else if (strategy == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) { if (threshold > 1) { return Result.ofFail(-1, "Ratio threshold should be in range: [0.0, 1.0]"); } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\DegradeController.java
2
请完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public long getPriority() { return priority; } public void setPriority(long priority) { this.priority = priority; } public int getState() { return state; } public void setState(int state) { this.state = state; } @Override public boolean isCreationLog() { return state == ExternalTaskState.CREATED.getStateCode(); } @Override
public boolean isFailureLog() { return state == ExternalTaskState.FAILED.getStateCode(); } @Override public boolean isSuccessLog() { return state == ExternalTaskState.SUCCESSFUL.getStateCode(); } @Override public boolean isDeletionLog() { return state == ExternalTaskState.DELETED.getStateCode(); } @Override public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricExternalTaskLogEntity.java
1
请完成以下Java代码
public class POCacheSourceModel implements ICacheSourceModel { public static void setRootRecordReference(@NonNull final PO po, @Nullable final TableRecordReference rootRecordReference) { ATTR_RootRecordReference.setValue(po, rootRecordReference); } private static final ModelDynAttributeAccessor<PO, TableRecordReference> // ATTR_RootRecordReference = new ModelDynAttributeAccessor<>(ModelCacheInvalidationService.class.getName(), "RootRecordReference", TableRecordReference.class); private final PO po; POCacheSourceModel(@NonNull final PO po) { this.po = po; } @Override public String getTableName() { return po.get_TableName(); } @Override public int getRecordId() { return po.get_ID(); }
@Override public TableRecordReference getRootRecordReferenceOrNull() { return ATTR_RootRecordReference.getValue(po); } @Override public Integer getValueAsInt(final String columnName, final Integer defaultValue) { return po.get_ValueAsInt(columnName, defaultValue); } @Override public boolean isValueChanged(final String columnName) { return po.is_ValueChanged(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\POCacheSourceModel.java
1
请完成以下Java代码
public final class ModelDynAttributeAccessor<ModelType, AttributeType> { @Getter private final String attributeName; private final Class<AttributeType> attributeType; public ModelDynAttributeAccessor(@NonNull final Class<AttributeType> attributeTypeClass) { this.attributeName = attributeTypeClass.getName(); this.attributeType = attributeTypeClass; } public ModelDynAttributeAccessor( @NonNull final String attributeName, @NonNull final Class<AttributeType> attributeTypeClass) { this.attributeName = attributeName; this.attributeType = attributeTypeClass; } public ModelDynAttributeAccessor(final String attributeGroupName, final String attributeName, final Class<AttributeType> attributeTypeClass) { this(attributeGroupName + "#" + attributeName // attributeName , attributeTypeClass); } public Class<AttributeType> getAttributeType() { Check.assumeNotNull(attributeType, "attributeType not null"); return attributeType; } public AttributeType getValue(final ModelType model) { return InterfaceWrapperHelper.getDynAttribute(model, attributeName); } public AttributeType getValue(final ModelType model, final AttributeType defaultValueIfNull) { final AttributeType attributeValue = getValue(model); if (attributeValue == null) { return defaultValueIfNull; } return attributeValue; } public Optional<AttributeType> getValueIfExists(final ModelType model) { final AttributeType attributeValue = getValue(model); return Optional.ofNullable(attributeValue); } public void setValue(final ModelType model, @Nullable final AttributeType attributeValue) { InterfaceWrapperHelper.setDynAttribute(model, attributeName, attributeValue); } public IAutoCloseable temporarySetValue(final ModelType model, final AttributeType value) {
final AttributeType valueOld = getValue(model); setValue(model, value); return () -> setValue(model, valueOld); } public boolean isSet(final ModelType model) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName); return attributeValue != null; } public boolean isNull(final ModelType model) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName); return attributeValue == null; } /** * @return true if given <code>model</code>'s attribute equals with <code>expectedValue</code> */ public boolean is(final ModelType model, final AttributeType expectedValue) { final Object attributeValue = InterfaceWrapperHelper.getDynAttribute(model, attributeName); return Objects.equals(attributeValue, expectedValue); } public void reset(final ModelType model) { setValue(model, null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelDynAttributeAccessor.java
1
请完成以下Java代码
private RestTemplate createRestTemplate() { return new RestTemplateBuilder().rootUri(BASE_URL).build(); } private HttpHeaders createHeaders() { final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON)); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.set(HttpHeaders.AUTHORIZATION, "Bearer " + authToken); return httpHeaders; } private static AdempiereException convertException(@NonNull final RuntimeException rte) { if (rte instanceof HttpClientErrorException) {
final HttpClientErrorException hcee = (HttpClientErrorException)rte; final JSONObjectMapper<ErrorResponse> mapper = JSONObjectMapper.forClass(ErrorResponse.class); final ErrorResponse errorResponse = mapper.readValue(hcee.getResponseBodyAsString()); return new AdempiereException(errorResponse.getError().getMessage(), hcee) .markAsUserValidationError() .appendParametersToMessage() .setParameter("code", errorResponse.getError().getCode()) .setParameter("message", errorResponse.getError().getMessage()); } return AdempiereException.wrapIfNeeded(rte) .appendParametersToMessage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\CleverReachLowLevelClient.java
1
请完成以下Java代码
public boolean voidIt() { log.info(toString()); // Before Void m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_VOID); if (m_processMsg != null) return false; if (DOCSTATUS_Closed.equals(getDocStatus()) || DOCSTATUS_Reversed.equals(getDocStatus()) || DOCSTATUS_Voided.equals(getDocStatus())) { m_processMsg = "Document Closed: " + getDocStatus(); return false; } // Not Processed if (DOCSTATUS_Drafted.equals(getDocStatus()) || DOCSTATUS_Invalid.equals(getDocStatus()) || DOCSTATUS_InProgress.equals(getDocStatus()) || DOCSTATUS_Approved.equals(getDocStatus()) || DOCSTATUS_NotApproved.equals(getDocStatus())) { // Set lines to 0 for (I_M_ShippingPackage line : getLines(false)) { line.setProcessed(true); line.setIsActive(false); line.setPackageWeight(BigDecimal.ZERO); line.setPackageNetTotal(BigDecimal.ZERO); InterfaceWrapperHelper.save(line); } } // After Void m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_VOID); if (m_processMsg != null) return false; setPackageWeight(BigDecimal.ZERO); setPackageNetTotal(BigDecimal.ZERO); setProcessed(true); setDocAction(DOCACTION_None); return true; } // voidIt /** * String Representation * * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("MMShipperTransportation["); sb.append(get_ID()).append("-").append(getSummary()) .append("]"); return sb.toString(); } // toString /** * Package Lines */ private List<I_M_ShippingPackage> m_lines = null; /**
* Get Lines * * @param requery requery * @return array of lines */ private List<I_M_ShippingPackage> getLines(boolean requery) { final String trxName = get_TrxName(); if (m_lines != null && !requery) { m_lines.forEach(line -> InterfaceWrapperHelper.setTrxName(line, trxName)); return m_lines; } final String whereClause = I_M_ShippingPackage.COLUMNNAME_M_ShipperTransportation_ID + "=?"; m_lines = new Query(getCtx(), I_M_ShippingPackage.Table_Name, whereClause, trxName) .setParameters(new Object[] { getM_ShipperTransportation_ID() }) .listImmutable(I_M_ShippingPackage.class); return m_lines; } /** * Before Delete * * @return true of it can be deleted */ @Override protected boolean beforeDelete() { if (isProcessed()) return false; getLines(false).forEach(InterfaceWrapperHelper::delete); return true; } // beforeDelete } // MMShipperTransportation
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\MMShipperTransportation.java
1
请完成以下Java代码
private String buildDescription(final I_GL_DistributionLine line) { final I_GL_Distribution distribution = getGLDistribution(); final StringBuilder description = new StringBuilder() .append(distribution.getName()).append(" #").append(line.getLine()); final String lineDescription = StringUtils.trimBlankToNull(line.getDescription()); if (lineDescription != null) { description.append(" - ").append(lineDescription); } return description.toString(); } public GLDistributionBuilder setGLDistribution(final I_GL_Distribution distribution) { _glDistribution = distribution; return this; } private I_GL_Distribution getGLDistribution() { Check.assumeNotNull(_glDistribution, "glDistribution not null"); return _glDistribution; } private List<I_GL_DistributionLine> getGLDistributionLines() { final I_GL_Distribution glDistribution = getGLDistribution(); return glDistributionDAO.retrieveLines(glDistribution); } public GLDistributionBuilder setCurrencyId(final CurrencyId currencyId) { _currencyId = currencyId; _precision = null; return this; } private CurrencyId getCurrencyId() { Check.assumeNotNull(_currencyId, "currencyId not null"); return _currencyId; } private CurrencyPrecision getPrecision() { if (_precision == null) { _precision = currencyDAO.getStdPrecision(getCurrencyId()); }
return _precision; } public GLDistributionBuilder setAmountToDistribute(final BigDecimal amountToDistribute) { _amountToDistribute = amountToDistribute; return this; } private BigDecimal getAmountToDistribute() { Check.assumeNotNull(_amountToDistribute, "amountToDistribute not null"); return _amountToDistribute; } public GLDistributionBuilder setAmountSign(@NonNull final Sign amountSign) { _amountSign = amountSign; return this; } private Sign getAmountSign() { Check.assumeNotNull(_amountSign, "amountSign not null"); return _amountSign; } public GLDistributionBuilder setQtyToDistribute(final BigDecimal qtyToDistribute) { _qtyToDistribute = qtyToDistribute; return this; } private BigDecimal getQtyToDistribute() { Check.assumeNotNull(_qtyToDistribute, "qtyToDistribute not null"); return _qtyToDistribute; } public GLDistributionBuilder setAccountDimension(final AccountDimension accountDimension) { _accountDimension = accountDimension; return this; } private AccountDimension getAccountDimension() { Check.assumeNotNull(_accountDimension, "_accountDimension not null"); return _accountDimension; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\GLDistributionBuilder.java
1
请完成以下Java代码
default <T> T getAttributeOrDefault(String name, T defaultValue) { T result = getAttribute(name); return (result != null) ? result : defaultValue; } /** * Gets the attribute names that have a value associated with it. Each value can be * passed into {@link org.springframework.session.Session#getAttribute(String)} to * obtain the attribute value. * @return the attribute names that have a value associated with it. * @see #getAttribute(String) */ Set<String> getAttributeNames(); /** * Sets the attribute value for the provided attribute name. If the attributeValue is * null, it has the same result as removing the attribute with * {@link org.springframework.session.Session#removeAttribute(String)} . * @param attributeName the attribute name to set * @param attributeValue the value of the attribute to set. If null, the attribute * will be removed. */ void setAttribute(String attributeName, Object attributeValue); /** * Removes the attribute with the provided attribute name. * @param attributeName the name of the attribute to remove */ void removeAttribute(String attributeName); /** * Gets the time when this session was created. * @return the time when this session was created. */ Instant getCreationTime(); /** * Sets the last accessed time. * @param lastAccessedTime the last accessed time */ void setLastAccessedTime(Instant lastAccessedTime);
/** * Gets the last time this {@link Session} was accessed. * @return the last time the client sent a request associated with the session */ Instant getLastAccessedTime(); /** * Sets the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. * @param interval the amount of time that the {@link Session} should be kept alive * between client requests. */ void setMaxInactiveInterval(Duration interval); /** * Gets the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. * @return the maximum inactive interval between requests before this session will be * invalidated. A negative time indicates that the session will never timeout. */ Duration getMaxInactiveInterval(); /** * Returns true if the session is expired. * @return true if the session is expired, else false. */ boolean isExpired(); }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\Session.java
1
请完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; this.activity = null; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; EventSubscriptionEntity other = (EventSubscriptionEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override
public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); if (executionId != null) { referenceIdAndClass.put(executionId, ExecutionEntity.class); } return referenceIdAndClass; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", eventName=" + eventName + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", activityId=" + activityId + ", tenantId=" + tenantId + ", configuration=" + configuration + ", revision=" + revision + ", created=" + created + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class JobStatsService { private final TbQueueProducer<TbProtoQueueMsg<JobStatsMsg>> producer; public JobStatsService(TaskProcessorQueueFactory queueFactory) { this.producer = queueFactory.createJobStatsProducer(); } public void reportTaskResult(TenantId tenantId, JobId jobId, TaskResult result) { report(tenantId, jobId, JobStatsMsg.newBuilder() .setTaskResult(TaskResultProto.newBuilder() .setValue(JacksonUtil.toString(result)) .build())); } public void reportAllTasksSubmitted(TenantId tenantId, JobId jobId, int tasksCount) {
report(tenantId, jobId, JobStatsMsg.newBuilder() .setTotalTasksCount(tasksCount)); } private void report(TenantId tenantId, JobId jobId, JobStatsMsg.Builder statsMsg) { log.debug("[{}][{}] Reporting: {}", tenantId, jobId, statsMsg); statsMsg.setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setJobIdMSB(jobId.getId().getMostSignificantBits()) .setJobIdLSB(jobId.getId().getLeastSignificantBits()); // using job id as msg key so that all stats for a certain job are submitted to the same partition TbProtoQueueMsg<JobStatsMsg> msg = new TbProtoQueueMsg<>(jobId.getId(), statsMsg.build()); producer.send(TopicPartitionInfo.builder().topic(producer.getDefaultTopic()).build(), msg, TbQueueCallback.EMPTY); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\task\JobStatsService.java
2
请在Spring Boot框架中完成以下Java代码
public static CreateViewRequest createViewRequest(@NonNull final InOutId customerReturnsId) { return CreateViewRequest.builder(Window_ID) .setParameter(PARAM_HUsToReturnViewContext, HUsToReturnViewContext.builder() .customerReturnsId(customerReturnsId) .build()) .build(); } @Override protected void customizeViewLayout( @NonNull final ViewLayout.Builder viewLayoutBuilder, final JSONViewDataType viewDataType) { viewLayoutBuilder .clearElements() .addElementsFromViewRowClassAndFieldNames(HUEditorRow.class, viewDataType, ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUCode).restrictToMediaType(MediaType.SCREEN).build(), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_Locator), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_Product), ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_PackingInfo).restrictToMediaType(MediaType.SCREEN).build(), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_QtyCU), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_UOM), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_SerialNo), ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_ServiceContract), ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUStatus).restrictToMediaType(MediaType.SCREEN).build()); }
@Override protected void customizeHUEditorView(final HUEditorViewBuilder huViewBuilder) { huViewBuilder.assertParameterSet(PARAM_HUsToReturnViewContext); huViewBuilder.considerTableRelatedProcessDescriptors(false) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(HUsToReturn_SelectHU.class)) .addAdditionalRelatedProcessDescriptor(createProcessDescriptor(HUsToReturn_CreateShippedHU.class)); } @Nullable @Override protected String getAdditionalSqlWhereClause() { return I_M_HU.COLUMNNAME_HUStatus + "=" + DB.TO_STRING(X_M_HU.HUSTATUS_Shipped); } /** * This view is not configuration dependent always should be false to execute the customizeViewLayout method */ @Override protected boolean isAlwaysUseSameLayout() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\HUsToReturnViewFactory.java
2
请完成以下Java代码
public class Country extends BaseEntity { /** * 名称 */ private String countryname; /** * 代码 */ private String countrycode; /** * 获取名称 * * @return countryname - 名称 */ public String getCountryname() { return countryname; } /** * 设置名称 * * @param countryname 名称 */ public void setCountryname(String countryname) { this.countryname = countryname; } /** * 获取代码 * * @return countrycode - 代码
*/ public String getCountrycode() { return countrycode; } /** * 设置代码 * * @param countrycode 代码 */ public void setCountrycode(String countrycode) { this.countrycode = countrycode; } }
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\model\Country.java
1
请在Spring Boot框架中完成以下Java代码
public final class SessionsEndpointAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnBean(SessionRepository.class) static class ServletSessionEndpointConfiguration { @Bean @ConditionalOnMissingBean SessionsEndpoint sessionEndpoint(SessionRepository<?> sessionRepository, ObjectProvider<FindByIndexNameSessionRepository<?>> indexedSessionRepository) { return new SessionsEndpoint(sessionRepository, indexedSessionRepository.getIfAvailable()); } }
@Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.REACTIVE) @ConditionalOnBean(ReactiveSessionRepository.class) static class ReactiveSessionEndpointConfiguration { @Bean @ConditionalOnMissingBean ReactiveSessionsEndpoint sessionsEndpoint(ReactiveSessionRepository<?> sessionRepository, ObjectProvider<ReactiveFindByIndexNameSessionRepository<?>> indexedSessionRepository) { return new ReactiveSessionsEndpoint(sessionRepository, indexedSessionRepository.getIfAvailable()); } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionsEndpointAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
protected void doInTransactionWithoutResult( TransactionStatus status) { log.info("Starting first transaction ..."); Author author = authorRepository.findById(1L).orElseThrow(); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult( TransactionStatus status) { log.info("Starting second transaction ...");
Author author = authorRepository.findById(1L).orElseThrow(); author.setGenre("Horror"); log.info("Commit second transaction ..."); } }); log.info("Resuming first transaction ..."); log.info("Commit first transaction ..."); } }); log.info("Done!"); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPessimisticLocks\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
protected static void insertText(JTextComponent editor, String text) { if (Check.isEmpty(text, false)) return; // final Document document = editor.getDocument(); // find out the text position where the new text should be inserted final int caretOffset = editor.getSelectionStart(); // find out if the have selected text to be replaces with the new snippet final String selText = editor.getSelectedText(); // try { if (selText != null) { document.remove(caretOffset, selText.length()); } document.insertString(caretOffset, text, null); } catch (BadLocationException e1) { MetasfreshLastError.saveError(log, "BadlocationException: " + e1.getMessage() + "; Illegal offset: " + e1.offsetRequested(), e1); } } private static Frame getParentFrame(Component c) { Frame parent = null; Container e = c.getParent(); while (e != null) { if (e instanceof Frame) { parent = (Frame)e; break; } e = e.getParent(); } return parent; } private static JTextComponent getTextComponent(Object c) { if (c == null) { return null; } if (c instanceof JTextComponent) { return (JTextComponent)c; } if (c instanceof Container) { final Container container = (Container)c; for (Component cc : container.getComponents()) { if (cc instanceof JTextComponent) { return (JTextComponent)cc;
} else if (cc instanceof Container) { return getTextComponent(cc); } } } return null; } public static boolean isAdvancedText(GridField gridField) { if (gridField == null) { log.warn("gridField is null"); return false; } final GridTab gridTab = gridField.getGridTab(); if (gridTab == null) return false; final MColumn column = MTable.get(Env.getCtx(), gridTab.getTableName()).getColumn(gridField.getColumnName()); if (column == null) return false; final I_AD_Column bean = InterfaceWrapperHelper.create(column, I_AD_Column.class); return bean.isAdvancedText(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\BoilerPlateMenu.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setOffsetName (final @Nullable java.lang.String OffsetName) { set_Value (COLUMNNAME_OffsetName, OffsetName); } @Override public java.lang.String getOffsetName() { return get_ValueAsString(COLUMNNAME_OffsetName); } @Override public void setSQL_Select (final @Nullable java.lang.String SQL_Select) { set_Value (COLUMNNAME_SQL_Select, SQL_Select); } @Override public java.lang.String getSQL_Select() { return get_ValueAsString(COLUMNNAME_SQL_Select); } @Override public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol) { set_Value (COLUMNNAME_UOMSymbol, UOMSymbol); } @Override public java.lang.String getUOMSymbol() { return get_ValueAsString(COLUMNNAME_UOMSymbol); } @Override public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID)
{ if (WEBUI_KPI_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID); } @Override public int getWEBUI_KPI_Field_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class); } @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java
1
请完成以下Java代码
public EntityImpl create() { return getDataManager().create(); } @Override public void insert(EntityImpl entity) { insert(entity, true); } @Override public void insert(EntityImpl entity, boolean fireCreateEvent) { getDataManager().insert(entity); if (fireCreateEvent) { fireEntityInsertedEvent(entity); } } protected void fireEntityInsertedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_CREATED, entity), engineType); eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_INITIALIZED, entity), engineType); } } @Override public EntityImpl update(EntityImpl entity) { return update(entity, true); } @Override public EntityImpl update(EntityImpl entity, boolean fireUpdateEvent) { EntityImpl updatedEntity = getDataManager().update(entity); if (fireUpdateEvent) { fireEntityUpdatedEvent(entity); } return updatedEntity; } protected void fireEntityUpdatedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { getEventDispatcher().dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, entity), engineType); } } @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); FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (fireDeleteEvent && eventDispatcher != null && eventDispatcher.isEnabled()) { fireEntityDeletedEvent(entity); } } protected void fireEntityDeletedEvent(Entity entity) { FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, entity), engineType); } } protected FlowableEntityEvent createEntityEvent(FlowableEngineEventType eventType, Entity entity) { return new FlowableEntityEventImpl(entity, eventType); } protected DM getDataManager() { return dataManager; } protected void setDataManager(DM dataManager) { this.dataManager = dataManager; } protected abstract FlowableEventDispatcher getEventDispatcher(); }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\AbstractEntityManager.java
1
请完成以下Java代码
public class DefaultDataLoaderObservationConvention implements DataLoaderObservationConvention { private static final String DEFAULT_NAME = "graphql.dataloader"; private static final KeyValue ERROR_TYPE_NONE = KeyValue.of(DataLoaderLowCardinalityKeyNames.ERROR_TYPE, "NONE"); private static final KeyValue LOADER_TYPE_UNKNOWN = KeyValue.of(DataLoaderLowCardinalityKeyNames.LOADER_NAME, "unknown"); private static final KeyValue OUTCOME_SUCCESS = KeyValue.of(DataLoaderLowCardinalityKeyNames.OUTCOME, "SUCCESS"); private static final KeyValue OUTCOME_ERROR = KeyValue.of(DataLoaderLowCardinalityKeyNames.OUTCOME, "ERROR"); @Override public String getName() { return DEFAULT_NAME; } @Override public String getContextualName(DataLoaderObservationContext context) { List<?> result = context.getResult(); if (result.isEmpty()) { return "graphql dataloader"; } else { return "graphql dataloader " + result.get(0).getClass().getSimpleName().toLowerCase(Locale.ROOT); } } @Override public KeyValues getLowCardinalityKeyValues(DataLoaderObservationContext context) { return KeyValues.of(errorType(context), loaderType(context), outcome(context)); } @Override public KeyValues getHighCardinalityKeyValues(DataLoaderObservationContext context) { return KeyValues.of(loaderSize(context)); } protected KeyValue errorType(DataLoaderObservationContext context) { if (context.getError() != null) {
return KeyValue.of(DataLoaderLowCardinalityKeyNames.ERROR_TYPE, context.getError().getClass().getSimpleName()); } return ERROR_TYPE_NONE; } protected KeyValue loaderType(DataLoaderObservationContext context) { if (StringUtils.hasText(context.getDataLoader().getName())) { return KeyValue.of(DataLoaderLowCardinalityKeyNames.LOADER_NAME, context.getDataLoader().getName()); } return LOADER_TYPE_UNKNOWN; } protected KeyValue outcome(DataLoaderObservationContext context) { if (context.getError() != null) { return OUTCOME_ERROR; } return OUTCOME_SUCCESS; } protected KeyValue loaderSize(DataLoaderObservationContext context) { return KeyValue.of(DataLoaderHighCardinalityKeyNames.LOADER_SIZE, String.valueOf(context.getResult().size())); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultDataLoaderObservationConvention.java
1
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_ShipperTransportation_ID (final int M_ShipperTransportation_ID) { if (M_ShipperTransportation_ID < 1) set_Value (COLUMNNAME_M_ShipperTransportation_ID, null); else set_Value (COLUMNNAME_M_ShipperTransportation_ID, M_ShipperTransportation_ID); } @Override public int getM_ShipperTransportation_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipperTransportation_ID); } @Override public void setNetWeightKg (final @Nullable BigDecimal NetWeightKg) { set_Value (COLUMNNAME_NetWeightKg, NetWeightKg); } @Override public BigDecimal getNetWeightKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NetWeightKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override
public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrder.java
1
请完成以下Java代码
public class DefaultLwM2MSessionManager implements LwM2MSessionManager { private final TransportService transportService; private final LwM2MAttributesService attributesService; private final LwM2MRpcRequestHandler rpcHandler; private final LwM2mUplinkMsgHandler uplinkHandler; public DefaultLwM2MSessionManager(TransportService transportService, @Lazy LwM2MAttributesService attributesService, @Lazy LwM2MRpcRequestHandler rpcHandler, @Lazy LwM2mUplinkMsgHandler uplinkHandler) { this.transportService = transportService; this.attributesService = attributesService; this.rpcHandler = rpcHandler; this.uplinkHandler = uplinkHandler; } @Override
public void register(TransportProtos.SessionInfoProto sessionInfo) { transportService.registerAsyncSession(sessionInfo, new LwM2mSessionMsgListener(uplinkHandler, attributesService, rpcHandler, sessionInfo, transportService)); TransportProtos.TransportToDeviceActorMsg msg = TransportProtos.TransportToDeviceActorMsg.newBuilder() .setSessionInfo(sessionInfo) .setSessionEvent(SESSION_EVENT_MSG_OPEN) .setSubscribeToAttributes(SUBSCRIBE_TO_ATTRIBUTE_UPDATES_ASYNC_MSG) .setSubscribeToRPC(SUBSCRIBE_TO_RPC_ASYNC_MSG) .build(); transportService.process(msg, null); } @Override public void deregister(TransportProtos.SessionInfoProto sessionInfo) { transportService.process(sessionInfo, SESSION_EVENT_MSG_CLOSED, null); transportService.deregisterSession(sessionInfo); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\session\DefaultLwM2MSessionManager.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("processId", processId) // .add("documentType", windowId) .add("documentId", documentId) .add("tabId", tabId) .add("rowId", rowId) // .add("viewRowIdsSelection", viewRowIdsSelection) .add("parentViewRowIdsSelection", parentViewRowIdsSelection) .add("childViewRowIdsSelection", childViewRowIdsSelection) // .add("selectedTab", selectedTab) .toString(); } private static DocumentPath createDocumentPathOrNull(final WindowId windowId, final String documentId, final String tabId, final String rowIdStr) { if (windowId != null && !Check.isEmpty(documentId)) { if (Check.isEmpty(tabId) && Check.isEmpty(rowIdStr)) { return DocumentPath.rootDocumentPath(windowId, documentId); } else { return DocumentPath.includedDocumentPath(windowId, documentId, tabId, rowIdStr); } } return null; } private static List<DocumentPath> createSelectedIncludedDocumentPaths(final WindowId windowId, final String documentIdStr, final JSONSelectedIncludedTab selectedTab) { if (windowId == null || Check.isEmpty(documentIdStr, true) || selectedTab == null) { return ImmutableList.of(); } final DocumentId documentId = DocumentId.of(documentIdStr);
final DetailId selectedTabId = DetailId.fromJson(selectedTab.getTabId()); return selectedTab.getRowIds() .stream() .map(DocumentId::of) .map(rowId -> DocumentPath.includedDocumentPath(windowId, documentId, selectedTabId, rowId)) .collect(ImmutableList.toImmutableList()); } public DocumentQueryOrderByList getViewOrderBys() { return JSONViewOrderBy.toDocumentQueryOrderByList(viewOrderBy); } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @Data public static final class JSONSelectedIncludedTab { @JsonProperty("tabId") private final String tabId; @JsonProperty("rowIds") private final List<String> rowIds; private JSONSelectedIncludedTab(@NonNull @JsonProperty("tabId") final String tabId, @JsonProperty("rowIds") final List<String> rowIds) { this.tabId = tabId; this.rowIds = rowIds != null ? ImmutableList.copyOf(rowIds) : ImmutableList.of(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONCreateProcessInstanceRequest.java
1
请完成以下Java代码
public void setBottomCategories(List<BottomCategory> bottomCategories) { this.bottomCategories = bottomCategories; } public TopCategory getTopCategory() { return topCategory; } public void setTopCategory(TopCategory topCategory) { this.topCategory = topCategory; } @Override public int hashCode() { return 2018; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof MiddleCategory)) { return false; } return id != null && id.equals(((MiddleCategory) obj).id); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\entity\MiddleCategory.java
1
请完成以下Java代码
public class WidgetTypeDetails extends WidgetType implements HasName, HasTenantId, HasImage, ExportableEntity<WidgetTypeId> { @Schema(description = "Relative or external image URL. Replaced with image data URL (Base64) in case of relative URL and 'inlineImages' option enabled.") private String image; @NoXss @Length(fieldName = "description", max = 1024) @Schema(description = "Description of the widget") private String description; @NoXss @Schema(description = "Tags of the widget type") private String[] tags; private WidgetTypeId externalId; private List<ResourceExportData> resources; public WidgetTypeDetails() { super(); }
public WidgetTypeDetails(WidgetTypeId id) { super(id); } public WidgetTypeDetails(BaseWidgetType baseWidgetType) { super(baseWidgetType); } public WidgetTypeDetails(WidgetTypeDetails widgetTypeDetails) { super(widgetTypeDetails); this.image = widgetTypeDetails.getImage(); this.description = widgetTypeDetails.getDescription(); this.tags = widgetTypeDetails.getTags(); this.externalId = widgetTypeDetails.getExternalId(); this.resources = widgetTypeDetails.getResources() != null ? new ArrayList<>(widgetTypeDetails.getResources()) : null; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\widget\WidgetTypeDetails.java
1
请完成以下Java代码
public void setParent_Activity_ID (int Parent_Activity_ID) { if (Parent_Activity_ID < 1) set_Value (COLUMNNAME_Parent_Activity_ID, null); else set_Value (COLUMNNAME_Parent_Activity_ID, Integer.valueOf(Parent_Activity_ID)); } /** Get Hauptkostenstelle. @return Hauptkostenstelle */ @Override public int getParent_Activity_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_Activity_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Activity.java
1
请完成以下Java代码
public @Nullable NavigableSet<LogLevel> getLevels() { return this.levels; } public @Nullable Map<String, LoggerLevelsDescriptor> getLoggers() { return this.loggers; } public @Nullable Map<String, GroupLoggerLevelsDescriptor> getGroups() { return this.groups; } } /** * Description of levels configured for a given logger. */ public static class LoggerLevelsDescriptor implements OperationResponseBody { private final @Nullable String configuredLevel; public LoggerLevelsDescriptor(@Nullable LogLevel configuredLevel) { this.configuredLevel = (configuredLevel != null) ? configuredLevel.name() : null; } LoggerLevelsDescriptor(@Nullable LevelConfiguration directConfiguration) { this.configuredLevel = (directConfiguration != null) ? directConfiguration.getName() : null; } protected final @Nullable String getName(@Nullable LogLevel level) { return (level != null) ? level.name() : null; } public @Nullable String getConfiguredLevel() { return this.configuredLevel; } } /** * Description of levels configured for a given group logger. */ public static class GroupLoggerLevelsDescriptor extends LoggerLevelsDescriptor { private final List<String> members; public GroupLoggerLevelsDescriptor(@Nullable LogLevel configuredLevel, List<String> members) {
super(configuredLevel); this.members = members; } public List<String> getMembers() { return this.members; } } /** * Description of levels configured for a given single logger. */ public static class SingleLoggerLevelsDescriptor extends LoggerLevelsDescriptor { private final String effectiveLevel; public SingleLoggerLevelsDescriptor(LoggerConfiguration configuration) { super(configuration.getLevelConfiguration(ConfigurationScope.DIRECT)); this.effectiveLevel = configuration.getLevelConfiguration().getName(); } public String getEffectiveLevel() { return this.effectiveLevel; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\logging\LoggersEndpoint.java
1
请完成以下Java代码
public static PPRoutingActivityId ofRepoIdOrNull(final int AD_Workflow_ID, final int AD_WF_Node_ID) { if (AD_WF_Node_ID <= 0) { return null; } final PPRoutingId routingId = PPRoutingId.ofRepoIdOrNull(AD_Workflow_ID); if (routingId == null) { return null; } return new PPRoutingActivityId(routingId, AD_WF_Node_ID); } public static int toRepoId(final PPRoutingActivityId id) {
return id != null ? id.getRepoId() : -1; } PPRoutingId routingId; int repoId; private PPRoutingActivityId(@NonNull final PPRoutingId routingId, final int repoId) { this.routingId = routingId; this.repoId = Check.assumeGreaterThanZero(repoId, "AD_WF_Node_ID"); } @JsonValue public int toJson() { return getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPRoutingActivityId.java
1
请完成以下Java代码
public class EasyReader { /** * 根目录 */ String root; /** * 是否输出进度 */ boolean verbose = true; /** * 构造 * @param root 根目录 */ public EasyReader(String root) { this.root = root; } /** * 构造 * @param root 根目录 * @param verbose 是否输出进度 */ public EasyReader(String root, boolean verbose) { this.root = root; this.verbose = verbose; } /** * 读取 * @param handler 处理逻辑 * @param size 读取多少个文件 * @throws Exception */ public void read(LineHandler handler, int size) throws Exception { File rootFile = new File(root); File[] files; if (rootFile.isDirectory()) { files = rootFile.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && !pathname.getName().endsWith(".bin"); } }); if (files == null) { if (rootFile.isFile()) files = new File[]{rootFile}; else return; } } else { files = new File[]{rootFile};
} int n = 0; int totalAddress = 0; long start = System.currentTimeMillis(); for (File file : files) { if (size-- == 0) break; if (file.isDirectory()) continue; if (verbose) System.out.printf("正在处理%s, %d / %d\n", file.getName(), ++n, files.length); IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(file.getAbsolutePath()); while (lineIterator.hasNext()) { ++totalAddress; String line = lineIterator.next(); if (line.length() == 0) continue; handler.handle(line); } } handler.done(); if (verbose) System.out.printf("处理了 %.2f 万行,花费了 %.2f min\n", totalAddress / 10000.0, (System.currentTimeMillis() - start) / 1000.0 / 60.0); } /** * 读取 * @param handler 处理逻辑 * @throws Exception */ public void read(LineHandler handler) throws Exception { read(handler, Integer.MAX_VALUE); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\EasyReader.java
1
请完成以下Java代码
protected PlanItemControl getItemControl(CmmnElement element) { if (isPlanItem(element)) { PlanItem planItem = (PlanItem) element; return planItem.getItemControl(); } else if (isDiscretionaryItem(element)) { DiscretionaryItem discretionaryItem = (DiscretionaryItem) element; return discretionaryItem.getItemControl(); } return null; } protected String getName(CmmnElement element) { String name = null; if (isPlanItem(element)) { PlanItem planItem = (PlanItem) element; name = planItem.getName(); } if (name == null || name.isEmpty()) { PlanItemDefinition definition = getDefinition(element); if (definition != null) { name = definition.getName(); } } return name; } protected PlanItemDefinition getDefinition(CmmnElement element) { if (isPlanItem(element)) { PlanItem planItem = (PlanItem) element; return planItem.getDefinition(); } else if (isDiscretionaryItem(element)) { DiscretionaryItem discretionaryItem = (DiscretionaryItem) element; return discretionaryItem.getDefinition(); } return null; } protected Collection<Sentry> getEntryCriterias(CmmnElement element) { if (isPlanItem(element)) { PlanItem planItem = (PlanItem) element; return planItem.getEntryCriteria(); } return new ArrayList<Sentry>(); } protected Collection<Sentry> getExitCriterias(CmmnElement element) { if (isPlanItem(element)) { PlanItem planItem = (PlanItem) element; return planItem.getExitCriteria(); } return new ArrayList<Sentry>(); } protected String getDesciption(CmmnElement element) { String description = element.getDescription(); if (description == null) { PlanItemDefinition definition = getDefinition(element);
description = definition.getDescription(); } return description; } protected String getDocumentation(CmmnElement element) { Collection<Documentation> documentations = element.getDocumentations(); if (documentations.isEmpty()) { PlanItemDefinition definition = getDefinition(element); documentations = definition.getDocumentations(); } if (documentations.isEmpty()) { return null; } StringBuilder builder = new StringBuilder(); for (Documentation doc : documentations) { String content = doc.getTextContent(); if (content == null || content.isEmpty()) { continue; } if (builder.length() != 0) { builder.append("\n\n"); } builder.append(content.trim()); } return builder.toString(); } protected boolean isPlanItem(CmmnElement element) { return element instanceof PlanItem; } protected boolean isDiscretionaryItem(CmmnElement element) { return element instanceof DiscretionaryItem; } protected abstract List<String> getStandardEvents(CmmnElement element); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\ItemHandler.java
1
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String url = WebUtils.getSourceUrl(request); if (!allowPreview(url)) { response.getWriter().write(this.notTrustDirView); response.getWriter().close(); } else { chain.doFilter(request, response); } } @Override public void destroy() { } private boolean allowPreview(String urlPath) { //判断URL是否合法 if(!StringUtils.hasText(urlPath) || !WebUtils.isValidUrl(urlPath)) {
return false ; } try { URL url = WebUtils.normalizedURL(urlPath); if ("file".equals(url.getProtocol().toLowerCase(Locale.ROOT))) { String filePath = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name()); if (OSUtils.IS_OS_WINDOWS) { filePath = filePath.replaceAll("/", "\\\\"); } return filePath.startsWith(ConfigConstants.getFileDir()) || filePath.startsWith(ConfigConstants.getLocalPreviewDir()); } return true; } catch (IOException | GalimatiasParseException e) { logger.error("解析URL异常,url:{}", urlPath, e); return false; } } }
repos\kkFileView-master\server\src\main\java\cn\keking\web\filter\TrustDirFilter.java
1
请完成以下Java代码
private CurrencyCode extractCurrencyCode(final I_C_Invoice invoiceRecord) { final CurrencyId currencyId = CurrencyId.ofRepoId(invoiceRecord.getC_Currency_ID()); return currenciesRepo.getCurrencyCodeById(currencyId); } private IQueryBuilder<I_C_Invoice> createCommonQueryBuilder(@NonNull final OrgId orgId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_AD_Org_ID, orgId) .addEqualsFilter(I_C_Invoice.COLUMN_IsSOTrx, true) .addEqualsFilter(I_C_Invoice.COLUMN_DocStatus, IDocument.STATUS_Completed) .orderBy(I_C_Invoice.COLUMN_DateInvoiced) .orderBy(I_C_Invoice.COLUMN_C_Invoice_ID) .setOption(IQuery.OPTION_ReturnReadOnlyRecords, true); } @Value public static class PaymentStatusQuery { String orgValue; String invoiceDocumentNoPrefix; LocalDate dateInvoicedFrom; LocalDate dateInvoicedTo; @Builder private PaymentStatusQuery(
@NonNull final String orgValue, @Nullable final String invoiceDocumentNoPrefix, @Nullable final LocalDate dateInvoicedFrom, @Nullable final LocalDate dateInvoicedTo) { this.orgValue = assumeNotEmpty(orgValue, "Parameter 'orgValue' may not be empty"); this.invoiceDocumentNoPrefix = invoiceDocumentNoPrefix; this.dateInvoicedFrom = dateInvoicedFrom; this.dateInvoicedTo = dateInvoicedTo; if (isBlank(invoiceDocumentNoPrefix)) { Check.assumeNotNull(dateInvoicedFrom, "If parameter 'invoiceDocumentNoPrefix' is empty, then both dateInvoicedFrom and dateInvoicedTo need to be set, but dateInvoicedFrom is null"); Check.assumeNotNull(dateInvoicedTo, "If parameter 'invoiceDocumentNoPrefix' is empty, then both dateInvoicedFrom and dateInvoicedTo need to be set, but dateInvoicedTo is null"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoice\impl\SalesInvoicePaymentStatusRepository.java
1
请完成以下Java代码
public java.lang.String getSystemStatus () { return (java.lang.String)get_Value(COLUMNNAME_SystemStatus); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_ValueNoCheck (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); }
/** Set ZK WebUI URL. @param WebUI_URL ZK WebUI root URL */ @Override public void setWebUI_URL (java.lang.String WebUI_URL) { set_Value (COLUMNNAME_WebUI_URL, WebUI_URL); } /** Get ZK WebUI URL. @return ZK WebUI root URL */ @Override public java.lang.String getWebUI_URL () { return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java
1
请完成以下Java代码
public int getLagTotal() { return storage.values().stream().map(BlockingQueue::size).reduce(0, Integer::sum); } @Override public int getLag(String topic) { return Optional.ofNullable(storage.get(topic)).map(Collection::size).orElse(0); } @Override public boolean put(String topic, TbQueueMsg msg) { return storage.computeIfAbsent(topic, (t) -> new LinkedBlockingQueue<>()).add(msg); } @SuppressWarnings("unchecked") @Override public <T extends TbQueueMsg> List<T> get(String topic) throws InterruptedException { final BlockingQueue<TbQueueMsg> queue = storage.get(topic); if (queue != null) {
final TbQueueMsg firstMsg = queue.poll(); if (firstMsg != null) { final int queueSize = queue.size(); if (queueSize > 0) { final List<TbQueueMsg> entities = new ArrayList<>(Math.min(queueSize, 999) + 1); entities.add(firstMsg); queue.drainTo(entities, 999); return (List<T>) entities; } return Collections.singletonList((T) firstMsg); } } return Collections.emptyList(); } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\DefaultInMemoryStorage.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderCostRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private OrderCostRepositorySession newSession() { return new OrderCostRepositorySession(queryBL); } public List<OrderCost> getByOrderId(@NonNull final OrderId orderId) { return newSession().getByOrderId(orderId); } public List<OrderCost> getByOrderIds(@NonNull final Set<OrderId> orderIds) { return newSession().getByOrderIds(orderIds); } public List<OrderCost> getByOrderLineIds(@NonNull final Set<OrderLineId> orderLineIds) { return newSession().getByOrderLineIds(orderLineIds); } public OrderCost getById(@NonNull final OrderCostId orderCostId) { return CollectionUtils.singleElement(getByIds(ImmutableSet.of(orderCostId))); } public List<OrderCost> getByIds(@NonNull final Collection<OrderCostId> orderCostIds) { return newSession().getByIds(orderCostIds); } public void saveAll(final Collection<OrderCost> orderCostsList) { newSession().saveAll(orderCostsList); } public void save(final OrderCost orderCost) { newSession().save(orderCost); } public void changeByOrderLineId(@NonNull final OrderLineId orderLineId, @NonNull final Consumer<OrderCost> consumer) { newSession().changeByOrderLineId(orderLineId, consumer); } public void deleteDetails(@NonNull final OrderCostId orderCostId) { queryBL.createQueryBuilder(I_C_Order_Cost_Detail.class) .addEqualsFilter(I_C_Order_Cost_Detail.COLUMNNAME_C_Order_Cost_ID, orderCostId) .create() .delete(); } public boolean hasCostsByCreatedOrderLineIds(final ImmutableSet<OrderLineId> orderLineIds) {
if (orderLineIds.isEmpty()) { return false; } return queryBL.createQueryBuilder(I_C_Order_Cost.class) .addInArrayFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, orderLineIds) .create() .anyMatch(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { final I_C_Order_Cost orderCostRecord = queryBL.createQueryBuilder(I_C_Order_Cost.class) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_C_Order_ID, createdOrderLineId.getOrderId()) .addEqualsFilter(I_C_Order_Cost.COLUMNNAME_Created_OrderLine_ID, createdOrderLineId.getOrderLineId()) .create() .firstOnly(); if (orderCostRecord == null) { return; } final OrderCostId orderCostId = OrderCostId.ofRepoId(orderCostRecord.getC_Order_Cost_ID()); deleteDetails(orderCostId); InterfaceWrapperHelper.delete(orderCostRecord, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepository.java
2
请完成以下Java代码
public static void main(String[] args) { // // Connect to cluster (default is localhost:27017) // setup(); // // Update a document using updateOne method // updateOne(); // // Update documents using updateMany method // updateMany(); // // replace a document using replaceOne method // replaceOne();
// // replace a document using findOneAndReplace method // findOneAndReplace(); // // Update a document using findOneAndUpdate method // findOneAndUpdate(); } }
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\update\UpdateFields.java
1
请完成以下Java代码
public Mono<Void> append(List<InstanceEvent> events) { return Mono.fromRunnable(() -> { while (true) { if (doAppend(events)) { return; } } }); } protected boolean doAppend(List<InstanceEvent> events) { if (events.isEmpty()) { return true; } InstanceId id = events.get(0).getInstance(); if (!events.stream().allMatch((event) -> event.getInstance().equals(id))) { throw new IllegalArgumentException("'events' must only refer to the same instance."); } List<InstanceEvent> oldEvents = eventLog.computeIfAbsent(id, (key) -> new ArrayList<>(maxLogSizePerAggregate + 1)); long lastVersion = getLastVersion(oldEvents); if (lastVersion >= events.get(0).getVersion()) { throw createOptimisticLockException(events.get(0), lastVersion); } List<InstanceEvent> newEvents = new ArrayList<>(oldEvents); newEvents.addAll(events); if (newEvents.size() > maxLogSizePerAggregate) { log.debug("Threshold for {} reached. Compacting events", id); compact(newEvents); } if (eventLog.replace(id, oldEvents, newEvents)) { log.debug("Events appended to log {}", events);
return true; } log.debug("Unsuccessful attempt append the events {} ", events); return false; } private void compact(List<InstanceEvent> events) { BinaryOperator<InstanceEvent> latestEvent = (e1, e2) -> (e1.getVersion() > e2.getVersion()) ? e1 : e2; Map<Class<?>, Optional<InstanceEvent>> latestPerType = events.stream() .collect(groupingBy(InstanceEvent::getClass, reducing(latestEvent))); events.removeIf((e) -> !Objects.equals(e, latestPerType.get(e.getClass()).orElse(null))); } private OptimisticLockingException createOptimisticLockException(InstanceEvent event, long lastVersion) { return new OptimisticLockingException( "Version " + event.getVersion() + " was overtaken by " + lastVersion + " for " + event.getInstance()); } protected static long getLastVersion(List<InstanceEvent> events) { return events.isEmpty() ? -1 : events.get(events.size() - 1).getVersion(); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\eventstore\ConcurrentMapEventStore.java
1
请完成以下Java代码
public class Action { @Id private String id; private String description; private ZonedDateTime time; public Action(String id, String description, ZonedDateTime time) { this.id = id; this.description = description; this.time = time; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; } public ZonedDateTime getTime() { return time; } public void setTime(ZonedDateTime time) { this.time = time; } @Override public String toString() { return "Action{id='" + id + "', description='" + description + "', time=" + time + '}'; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-4\src\main\java\com\baeldung\zoneddatetime\model\Action.java
1
请完成以下Java代码
public void run() { new ATask(title, task); } }.start(); } // start /************************************************************************** * Full Constructor * @param title title * @param task task */ public ATask (String title, MTask task) { super (title); this.setIconImage(Adempiere.getProductIconSmall()); try { jbInit(); AEnv.showCenterScreen(this); // if (task.isServerProcess()) info.setText("Executing on Server ..."); else info.setText("Executing locally ..."); String result = task.execute(); info.setText(result); confirmPanel.getCancelButton().setEnabled(false); confirmPanel.getOKButton().setEnabled(true); } catch(Exception e) { log.error(task.toString(), e); } } // ATask private Task m_task = null; /** Logger */ private static Logger log = LogManager.getLogger(ATask.class); private ConfirmPanel confirmPanel = ConfirmPanel.newWithOKAndCancel();
private JScrollPane infoScrollPane = new JScrollPane(); private JTextArea info = new JTextArea(); /** * Static Layout * @throws Exception */ private void jbInit() throws Exception { info.setEditable(false); info.setBackground(AdempierePLAF.getFieldBackground_Inactive()); infoScrollPane.getViewport().add(info, null); infoScrollPane.setPreferredSize(new Dimension(500,300)); this.getContentPane().add(infoScrollPane, BorderLayout.CENTER); this.getContentPane().add(confirmPanel, BorderLayout.SOUTH); // confirmPanel.setActionListener(this); confirmPanel.getOKButton().setEnabled(false); } // jbInit /** * Action Listener * @param e */ @Override public void actionPerformed (ActionEvent e) { if (m_task != null && m_task.isAlive()) m_task.interrupt(); dispose(); } // actionPerformed } // ATask
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ATask.java
1
请完成以下Java代码
public long getPzn() { return pzn; } /** * Sets the value of the pzn property. * */ public void setPzn(long value) { this.pzn = value; } /** * Gets the value of the menge property. * */ public int getMenge() { return menge; } /** * Sets the value of the menge property. * */ public void setMenge(int value) { this.menge = value; } /** * Gets the value of the liefervorgabe property. * * @return * possible object is * {@link Liefervorgabe } *
*/ public Liefervorgabe getLiefervorgabe() { return liefervorgabe; } /** * Sets the value of the liefervorgabe property. * * @param value * allowed object is * {@link Liefervorgabe } * */ public void setLiefervorgabe(Liefervorgabe value) { this.liefervorgabe = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\BestellungPosition.java
1
请完成以下Java代码
public String getRequestId() { return requestId; } /** * Sets the value of the requestId property. * * @param value * allowed object is * {@link String } * */ public void setRequestId(String value) { this.requestId = value; } /** * Gets the value of the reminderLevel property. * * @return * possible object is * {@link String } * */ public String getReminderLevel() { if (reminderLevel == null) { return "1"; } else { return reminderLevel; } } /** * Sets the value of the reminderLevel property. * * @param value * allowed object is * {@link String } * */ public void setReminderLevel(String value) { this.reminderLevel = value; } /** * Gets the value of the reminderText property.
* * @return * possible object is * {@link String } * */ public String getReminderText() { return reminderText; } /** * Sets the value of the reminderText property. * * @param value * allowed object is * {@link String } * */ public void setReminderText(String value) { this.reminderText = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ReminderType.java
1
请完成以下Java代码
public String generateKey() { byte[] bytes = this.keyGenerator.generateKey(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { int offset = Math.abs(b % 20); sb.append(VALID_CHARS[offset]); } sb.insert(4, '-'); return sb.toString(); } } private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> { private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator(); @Nullable
@Override public OAuth2UserCode generate(OAuth2TokenContext context) { if (context.getTokenType() == null || !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive()); return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
1
请完成以下Java代码
public class InterpolationSearch { public static int interpolationSearch(int[] data, int item) { int highEnd = (data.length - 1); int lowEnd = 0; while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) { int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]); if (highEnd == lowEnd) { if (data[lowEnd] == item) { return lowEnd; } else { return -1; }
} if (data[probe] == item) { return probe; } if (data[probe] < item) { lowEnd = probe + 1; } else { highEnd = probe - 1; } } return -1; } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\interpolationsearch\InterpolationSearch.java
1
请完成以下Java代码
public @Nullable String getPassword() { return this.password; } @Override public void setPassword(@Nullable String password) { this.password = password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.delegate.getAuthorities(); } @Override public String getUsername() { return this.delegate.getUsername(); } @Override public boolean isAccountNonExpired() { return this.delegate.isAccountNonExpired(); }
@Override public boolean isAccountNonLocked() { return this.delegate.isAccountNonLocked(); } @Override public boolean isCredentialsNonExpired() { return this.delegate.isCredentialsNonExpired(); } @Override public boolean isEnabled() { return this.delegate.isEnabled(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\MutableUser.java
1
请完成以下Java代码
protected List<String> getIpAddress() throws Exception { List<String> result = null; //获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { result = inetAddresses.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList()); } return result; } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: WindowsServerInfos.java </p> * <p>方法描述: 获取 Mac 地址 </p> * <p>创建时间: 2020/10/10 11:23 </p> * * @return java.util.List<java.lang.String> * @author 方瑞冬 * @version 1.0 */ @Override protected List<String> getMacAddress() throws Exception { List<String> result = null; //1. 获取所有网络接口 List<InetAddress> inetAddresses = getLocalAllInetAddress(); if (inetAddresses != null && inetAddresses.size() > 0) { //2. 获取所有网络接口的 Mac 地址 result = inetAddresses.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList()); } return result; } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: WindowsServerInfos.java </p> * <p>方法描述: 获取 CPU 序列号 </p> * <p>创建时间: 2020/10/10 11:23 </p> * * @return java.lang.String * @author 方瑞冬 * @version 1.0 */ @Override protected String getCPUSerial() throws Exception { //序列号 String serialNumber = "";
//使用 WMIC 获取 CPU 序列号 Process process = Runtime.getRuntime().exec("wmic cpu get processorid"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if (scanner.hasNext()) { scanner.next(); } if (scanner.hasNext()) { serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: WindowsServerInfos.java </p> * <p>方法描述: 获取主板序列号 </p> * <p>创建时间: 2020/10/10 11:23 </p> * * @return java.lang.String * @author 方瑞冬 * @version 1.0 */ @Override protected String getMainBoardSerial() throws Exception { //序列号 String serialNumber = ""; //使用 WMIC 获取主板序列号 Process process = Runtime.getRuntime().exec("wmic baseboard get serialnumber"); process.getOutputStream().close(); Scanner scanner = new Scanner(process.getInputStream()); if (scanner.hasNext()) { scanner.next(); } if (scanner.hasNext()) { serialNumber = scanner.next().trim(); } scanner.close(); return serialNumber; } }
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\WindowsServerInfos.java
1
请完成以下Java代码
public class Farewell { private String message; private Integer remainingMinutes; public Farewell() { } public Farewell(String message, Integer remainingMinutes) { this.message = message; this.remainingMinutes = remainingMinutes; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message;
} public Integer getRemainingMinutes() { return remainingMinutes; } public void setRemainingMinutes(Integer remainingMinutes) { this.remainingMinutes = remainingMinutes; } @Override public String toString() { return message + ". In " + remainingMinutes + "!"; } }
repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\retryable\Farewell.java
1
请完成以下Spring Boot application配置
server.port=80 # \u6570\u636E\u6E90\u914D\u7F6E spring.datasource.url=jdbc:h2:mem:ssb_test spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=root spring.datasource.password=root spring.datasource.schema=classpath:db/schema.sql spring.datasource.data=classpath:db/data.sql # \u8FDB\u884C\u8BE5\u914D\u7F6E\u540E\uFF0Ch2 web consloe\u5C31\u53EF\u4EE5\u5728\u8FDC\u7A0B\u8BBF\u95EE\u4E86\u3002\u5426\u5219\u53EA\u80FD\u5728\u672C\u673A\u8BBF\u95EE\u3002 spring.h2.console.settings.web-allow-others=true # \u8FDB\u884C\u8BE5\u914D\u7F6E\uFF0C\u4F60\u5C31\u53EF\u4EE5\u901A\u8FC7YOUR_URL/h2-console\u8BBF\u95EEh2 web consloe\u3002YOUR_URL\u662F\u4F60\u7A0B\u5E8F\u7684\u8BBF\u95EEURl\u3002 spring.h2.console.path=/h2-console #\u8FDE\u63A5\u6C60\u914D\u7F6E spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource #\u521D\u59CB\u5316\u8FDE\u63A5:\u8FDE\u63A5\u6C60\u542F\u52A8\u65F6\u521B\u5EFA\u7684\u521D\u59CB\u5316\u8FDE\u63A5\u6570\u91CF spring.datasource.dbcp2.initial-size=50 #\u6700\u5927\u6D3B\u52A8\u8FDE\u63A5:\u8FDE\u63A5\u6C60\u5728\u540C\u4E00\u65F6\u95F4\u80FD\u591F\u5206\u914D\u7684\u6700\u5927\u6D3B\u52A8\u8FDE\u63A5\u7684\u6570\u91CF, \u5982\u679C\u8BBE\u7F6E\u4E3A\u975E\u6B63\u6570\u5219\u8868\u793A\u4E0D\u9650\u5236 spring.datasource.dbcp2.max-active=250 #\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5:\u8FDE\u63A5\u6C60\u4E2D\u5BB9\u8BB8\u4FDD\u6301\u7A7A\u95F2\u72B6\u6001\u7684\u6700\u5927\u8FDE\u63A5\u6570\u91CF,\u8D85\u8FC7\u7684\u7A7A\u95F2\u8FDE\u63A5\u5C06\u88AB\u91CA\u653E,\u5982\u679C\u8BBE\u7F6E\u4E3A\u8D1F\u6570\u8868\u793A\u4E0D\u9650\u5236 spring.datasource.dbcp2.max-idle=50 #\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5:\u8FDE\u63A5\u6C60\u4E2D\u5BB9\u8BB8\u4FDD\u6301\u7A7A\u95F2\u72B6\u6001\u7684\u6700\u5C0F\u8FDE\u63A5\u6570\u91CF,\u4F4E\u4E8E\u8FD9\u4E2A\u6570\u91CF\u5C06\u521B\u5EFA\u65B0\u7684\u8FDE\u63A5,\u5982\u679C\u8BBE\u7F6E\u4E3A0\u5219\u4E0D\u521B\u5EFA spring.datasource.dbcp2.min-idle=5 #\u6700\u5927\u7B49\u5F85\u65F6\u95F4:\u5F53\u6CA1\u6709\u53EF\u7528\u8FDE\u63A5\u65F6,\u8FDE\u63A5\u6C60\u7B49\u5F85\u8FDE\u63A5\u88AB\u5F52\u8FD8\u7684\u6700\u5927\u65F6\u95F4(\u4EE5\u6BEB\u79D2\u8BA1\u6570),\u8D85\u8FC7\u65F6\u95F4\u5219\u629B\u51FA\u5F02\u5E38,\u5982\u679C\u8BBE\u7F6E\u4E3A-1\u8868\u793A\u65E0\u9650\u7B49\u5F85 spring.datasource.dbcp2.max-wait-millis=10000 #SQL\u67E5\u8BE2,\u7528\u6765\u9A8C\u8BC1\u4ECE\u8FDE\u63A5\u6C60\u53D6\u51FA\u7684\u8FDE\u63A5,\u5728\u5C06\u8FDE\u63A5\u8FD4\u56DE\u7ED9\u8C03\u7528\u8005\u4E4B\u524D.\u5982\u679C\u6307\u5B9A,\u5219\u67E5\u8BE2\u5FC5\u987B\u662F\u4E00\u4E2ASQL SELECT\u5E76\u4E14\u5FC5\u987B\u8FD4\u56DE\u81F3\u5C11\u4E00\u884C\u8BB0\u5F55 spring.datasource.dbcp2.validation-query=SELECT 1 #\u5F53\u5EFA\u7ACB\u65B0\u8FDE\u63A5\u65F6\u88AB\u53D1\u9001\u7ED9JDBC\u9A71\u52A8\u7684\u8FDE\u63A5\u53C2\u6570\uFF0C\u683C\u5F0F\u5FC5\u987B\u662F [propertyName=property;]\u3002\u6CE8\u610F\uFF1A\u53C2\u6570user/password\u5C06\u88AB\u660E\u786E\u4F20\u9012\uFF0C\u6240\u4EE5\u4E0D\u9700\u8981\u5305\u62EC\u5728\u8FD9\u91CC\u3002 spring.datasource.dbcp2.connection-properties=characterEncoding=utf8 # JPA\u914D\u7F6E #hibernate\u63D0\u4F9B\u4E86\u6839\u636E\u5B9E\u4F53\u7C7B\u81EA\u52A8\u7EF4\u62A4\u6570\u636E\u5E93\u8868\u7ED3\u6784\u7684\u529F\u80FD\uFF0C\u53EF\u901A\u8FC7spring.jpa.hibernate.ddl-auto\u6765\u914D\u7F6E\uFF0C\u6709\u4E0B\u5217\u53EF\u9009\u9879\uFF1A #1\u3001create\uFF1A\u542F\u52A8\u65F6\u5220\u9664\u4E0A\u4E00\u6B21\u75
1F\u6210\u7684\u8868\uFF0C\u5E76\u6839\u636E\u5B9E\u4F53\u7C7B\u751F\u6210\u8868\uFF0C\u8868\u4E2D\u6570\u636E\u4F1A\u88AB\u6E05\u7A7A\u3002 #2\u3001create-drop\uFF1A\u542F\u52A8\u65F6\u6839\u636E\u5B9E\u4F53\u7C7B\u751F\u6210\u8868\uFF0CsessionFactory\u5173\u95ED\u65F6\u8868\u4F1A\u88AB\u5220\u9664\u3002 #3\u3001update\uFF1A\u542F\u52A8\u65F6\u4F1A\u6839\u636E\u5B9E\u4F53\u7C7B\u751F\u6210\u8868\uFF0C\u5F53\u5B9E\u4F53\u7C7B\u5C5E\u6027\u53D8\u52A8\u7684\u65F6\u5019\uFF0C\u8868\u7ED3\u6784\u4E5F\u4F1A\u66F4\u65B0\uFF0C\u5728\u521D\u671F\u5F00\u53D1\u9636\u6BB5\u4F7F\u7528\u6B64\u9009\u9879\u3002 #4\u3001validate\uFF1A\u542F\u52A8\u65F6\u9A8C\u8BC1\u5B9E\u4F53\u7C7B\u548C\u6570\u636E\u8868\u662F\u5426\u4E00\u81F4\uFF0C\u5728\u6211\u4EEC\u6570\u636E\u7ED3\u6784\u7A33\u5B9A\u65F6\u91C7\u7528\u6B64\u9009\u9879\u3002 #5\u3001none\uFF1A\u4E0D\u91C7\u53D6\u4EFB\u4F55\u63AA\u65BD\u3002 spring.jpa.hibernate.ddl-auto=validate #spring.jpa.show-sql\u7528\u6765\u8BBE\u7F6Ehibernate\u64CD\u4F5C\u7684\u65F6\u5019\u5728\u63A7\u5236\u53F0\u663E\u793A\u5176\u771F\u5B9E\u7684sql\u8BED\u53E5\u3002 spring.jpa.show-sql=true #\u8BA9\u63A7\u5236\u5668\u8F93\u51FA\u7684json\u5B57\u7B26\u4E32\u683C\u5F0F\u66F4\u7F8E\u89C2\u3002 spring.jackson.serialization.indent-output=true #\u65E5\u5FD7\u914D\u7F6E logging.level.com.xiaolyuh=debug logging.level.org.springframework.web=debug logging.level.org.springframework.transaction=debug logging.level.org.apache.commons.dbcp2=debug debug=false
repos\spring-boot-student-master\spring-boot-student-cache\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class SAPGLJournalLineCreateRequest { @NonNull PostingSign postingSign; @NonNull Account account; @NonNull BigDecimal amount; @Nullable CurrencyId expectedCurrencyId; @Nullable TaxId taxId; @Nullable String description; @Nullable BPartnerId bpartnerId; @NonNull Dimension dimension; boolean determineTaxBaseSAP; boolean isTaxIncluded; @Nullable @With FAOpenItemTrxInfo openItemTrxInfo; boolean isFieldsReadOnlyInUI; @Nullable @With SAPGLJournalLineId alreadyReservedId; @NonNull public static SAPGLJournalLineCreateRequest of(
@NonNull final SAPGLJournalLine line, @NonNull final Boolean negateAmounts) { return SAPGLJournalLineCreateRequest.builder() .postingSign(line.getPostingSign()) .account(line.getAccount()) .amount(line.getAmount().negateIf(negateAmounts).toBigDecimal()) .dimension(line.getDimension()) .description(line.getDescription()) .taxId(line.getTaxId()) .determineTaxBaseSAP(line.isDetermineTaxBaseSAP()) .isTaxIncluded(line.isTaxIncluded()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalLineCreateRequest.java
2
请在Spring Boot框架中完成以下Java代码
public class CompositeBook { @Id private Long id; @Id private Long isbn; private String title; private String author; public CompositeBook() { } public CompositeBook(BookId bookId, String title, String author) { this.id = bookId.id(); this.isbn = bookId.isbn(); this.title = title; this.author = author; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getIsbn() { return isbn; }
public void setIsbn(Long isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\recordswithjpa\entity\CompositeBook.java
2
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setM_WarehouseSource_ID (final int M_WarehouseSource_ID) { if (M_WarehouseSource_ID < 1) set_Value (COLUMNNAME_M_WarehouseSource_ID, null); else set_Value (COLUMNNAME_M_WarehouseSource_ID, M_WarehouseSource_ID); } @Override public int getM_WarehouseSource_ID() { return get_ValueAsInt(COLUMNNAME_M_WarehouseSource_ID); } @Override public void setPercent (final BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } @Override public BigDecimal getPercent() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percent); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPriorityNo (final int PriorityNo) { set_Value (COLUMNNAME_PriorityNo, PriorityNo); } @Override
public int getPriorityNo() { return get_ValueAsInt(COLUMNNAME_PriorityNo); } @Override public void setTransfertTime (final @Nullable BigDecimal TransfertTime) { set_Value (COLUMNNAME_TransfertTime, TransfertTime); } @Override public BigDecimal getTransfertTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValidFrom (final @Nullable 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 @Nullable 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\eevolution\model\X_DD_NetworkDistributionLine.java
1
请完成以下Java代码
public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); }
@Override public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } protected Map<String, Object> getVariables() { if (this.scopeContainer instanceof VariableScope) { return ((VariableScope) this.scopeContainer).getVariables(); } return Collections.emptyMap(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public static final <T> Builder<T> builder() { return new Builder<>(); } public static <T> IncludeExcludeListPredicate<T> empty() { @SuppressWarnings("unchecked") final IncludeExcludeListPredicate<T> emptyCasted = (IncludeExcludeListPredicate<T>)EMPTY; return emptyCasted; } private final Set<T> includes; private final Set<T> excludes; private IncludeExcludeListPredicate(final Builder<T> builder) { super(); this.includes = ImmutableSet.copyOf(builder.includes); this.excludes = ImmutableSet.copyOf(builder.excludes); } /** * Empty constructor */ private IncludeExcludeListPredicate() { super(); includes = ImmutableSet.of(); excludes = ImmutableSet.of(); } @Override public String toString() { return ObjectUtils.toString(this); } @Override public boolean test(final T item) { if (item == null) { return false; } // Don't accept it if it's explicitelly excluded if (excludes.contains(item)) { return false; } // Accept it right away if it explicitelly included if (includes.contains(item)) { return true; } // // Accept it ONLY if there are NO particular items to be included. // Else, we assume the user want's to include ONLY those. final boolean acceptAllByDefault = includes.isEmpty(); return acceptAllByDefault; } public static class Builder<T> { private final Set<T> includes = new LinkedHashSet<>(); private final Set<T> excludes = new LinkedHashSet<>(); private IncludeExcludeListPredicate<T> lastBuilt = null;
private Builder() { super(); } public IncludeExcludeListPredicate<T> build() { if (lastBuilt != null) { return lastBuilt; } if (isEmpty()) { lastBuilt = empty(); } else { lastBuilt = new IncludeExcludeListPredicate<>(this); } return lastBuilt; } public final boolean isEmpty() { return includes.isEmpty() && excludes.isEmpty(); } public Builder<T> include(final T itemToInclude) { Check.assumeNotNull(itemToInclude, "itemToInclude not null"); final boolean added = includes.add(itemToInclude); // Reset last built, in case of change if (added) { lastBuilt = null; } return this; } public Builder<T> exclude(final T itemToExclude) { // guard against null: tollerate it but do nothing if (itemToExclude == null) { return this; } final boolean added = excludes.add(itemToExclude); // Reset last built, in case of change if (added) { lastBuilt = null; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IncludeExcludeListPredicate.java
1
请在Spring Boot框架中完成以下Java代码
public String getPlantName() { return plantName; } /** * Sets the value of the plantName property. * * @param value * allowed object is * {@link String } * */ public void setPlantName(String value) { this.plantName = value; } /** * Gets the value of the plantCity property. * * @return * possible object is * {@link String } * */ public String getPlantCity() { return plantCity; } /** * Sets the value of the plantCity property. * * @param value * allowed object is * {@link String } * */ public void setPlantCity(String value) { this.plantCity = value; } /** * Gets the value of the deliverTo property. * * @return * possible object is * {@link String } * */ public String getDeliverTo() { return deliverTo; } /** * Sets the value of the deliverTo property. * * @param value * allowed object is * {@link String } * */ public void setDeliverTo(String value) { this.deliverTo = value; } /** * Gets the value of the productionDescription property. * * @return
* possible object is * {@link String } * */ public String getProductionDescription() { return productionDescription; } /** * Sets the value of the productionDescription property. * * @param value * allowed object is * {@link String } * */ public void setProductionDescription(String value) { this.productionDescription = value; } /** * Gets the value of the kanbanCardNumberRange1Start property. * * @return * possible object is * {@link String } * */ public String getKanbanCardNumberRange1Start() { return kanbanCardNumberRange1Start; } /** * Sets the value of the kanbanCardNumberRange1Start property. * * @param value * allowed object is * {@link String } * */ public void setKanbanCardNumberRange1Start(String value) { this.kanbanCardNumberRange1Start = value; } /** * Gets the value of the kanbanCardNumberRange1End property. * * @return * possible object is * {@link String } * */ public String getKanbanCardNumberRange1End() { return kanbanCardNumberRange1End; } /** * Sets the value of the kanbanCardNumberRange1End property. * * @param value * allowed object is * {@link String } * */ public void setKanbanCardNumberRange1End(String value) { this.kanbanCardNumberRange1End = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingIdentificationType.java
2
请完成以下Java代码
public java.math.BigDecimal getPrev_CurrentQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Preis. @param Price Price */ @Override public void setPrice (java.math.BigDecimal Price) { throw new IllegalArgumentException ("Price is virtual column"); } /** Get Preis. @return Price */ @Override public java.math.BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return BigDecimal.ZERO; return bd; } /** 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 Menge. @param Qty
Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public void setSourceAmt (final @Nullable BigDecimal SourceAmt) { set_Value (COLUMNNAME_SourceAmt, SourceAmt); } @Override public BigDecimal getSourceAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SourceAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSource_Currency_ID (final int Source_Currency_ID) { if (Source_Currency_ID < 1) set_Value (COLUMNNAME_Source_Currency_ID, null); else set_Value (COLUMNNAME_Source_Currency_ID, Source_Currency_ID); } @Override public int getSource_Currency_ID() { return get_ValueAsInt(COLUMNNAME_Source_Currency_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostDetail.java
1
请完成以下Java代码
public class PP_Product_BOM_DocHandler implements DocumentHandler { private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); @Override public String getSummary(final DocumentTableFields docFields) { return extractProductBom(docFields).getDocumentNo(); } @Override public String getDocumentInfo(final DocumentTableFields docFields) { return getSummary(docFields); } @Override public int getDoc_User_ID(final DocumentTableFields docFields) { return extractProductBom(docFields).getCreatedBy(); } @Nullable @Override public LocalDate getDocumentDate(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(productBom.getAD_Org_ID())); return TimeUtil.asLocalDate(productBom.getDateDoc(), timeZone); } @Override public String completeIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBomRecord = extractProductBom(docFields);
productBomRecord.setDocAction(X_C_RemittanceAdvice.DOCACTION_Re_Activate); productBomRecord.setProcessed(true); return X_PP_Product_BOM.DOCSTATUS_Completed; } @Override public void reactivateIt(final DocumentTableFields docFields) { final I_PP_Product_BOM productBom = extractProductBom(docFields); productBom.setProcessed(false); productBom.setDocAction(X_PP_Product_BOM.DOCACTION_Complete); } private static I_PP_Product_BOM extractProductBom(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_PP_Product_BOM.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\document\PP_Product_BOM_DocHandler.java
1
请在Spring Boot框架中完成以下Java代码
public List<ServerDeployDto> queryAll(ServerDeployQueryCriteria criteria){ return serverDeployMapper.toDto(serverDeployRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override public ServerDeployDto findById(Long id) { ServerDeploy server = serverDeployRepository.findById(id).orElseGet(ServerDeploy::new); ValidationUtil.isNull(server.getId(),"ServerDeploy","id",id); return serverDeployMapper.toDto(server); } @Override public ServerDeployDto findByIp(String ip) { ServerDeploy deploy = serverDeployRepository.findByIp(ip); return serverDeployMapper.toDto(deploy); } @Override public Boolean testConnect(ServerDeploy resources) { ExecuteShellUtil executeShellUtil = null; try { executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort()); return executeShellUtil.execute("ls")==0; } catch (Exception e) { return false; }finally { if (executeShellUtil != null) { executeShellUtil.close(); } } } @Override @Transactional(rollbackFor = Exception.class) public void create(ServerDeploy resources) { serverDeployRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(ServerDeploy resources) { ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new);
ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId()); serverDeploy.copy(resources); serverDeployRepository.save(serverDeploy); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { serverDeployRepository.deleteById(id); } } @Override public void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (ServerDeployDto deployDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("服务器名称", deployDto.getName()); map.put("服务器IP", deployDto.getIp()); map.put("端口", deployDto.getPort()); map.put("账号", deployDto.getAccount()); map.put("创建日期", deployDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\ServerDeployServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Mono<ResponseEntity<User>> getUser(@PathVariable String id) { return userService.getUser(id) .map(user -> new ResponseEntity<>(user, HttpStatus.OK)) .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } /** * 根据年龄段来查找 */ @GetMapping("/age/{from}/{to}") public Flux<User> getUserByAge(@PathVariable Integer from, @PathVariable Integer to) { return userService.getUserByAge(from, to); } @GetMapping(value = "/stream/age/{from}/{to}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<User> getUserByAgeStream(@PathVariable Integer from, @PathVariable Integer to) { return userService.getUserByAge(from, to); } /** * 根据用户名查找 */ @GetMapping("/name/{name}") public Flux<User> getUserByName(@PathVariable String name) { return userService.getUserByName(name); } @GetMapping(value = "/stream/name/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<User> getUserByNameStream(@PathVariable String name) { return userService.getUserByName(name); } /** * 根据用户描述模糊查找 */ @GetMapping("/description/{description}") public Flux<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description); } @GetMapping(value = "/stream/description/{description}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<User> getUserByDescriptionStream(@PathVariable String description) { return userService.getUserByDescription(description); } /** * 根据多个检索条件查询 */ @GetMapping("/condition") public Flux<User> getUserByCondition(int size, int page, User user) { return userService.getUserByCondition(size, page, user); } @GetMapping("/condition/count") public Mono<Long> getUserByConditionCount(User user) { return userService.getUserByConditionCount(user); } }
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\controller\UserController.java
2
请完成以下Java代码
public void setContentType (final @Nullable java.lang.String ContentType) { set_ValueNoCheck (COLUMNNAME_ContentType, ContentType); } @Override public java.lang.String getContentType() { return get_ValueAsString(COLUMNNAME_ContentType); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_ValueNoCheck (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFileName (final @Nullable java.lang.String FileName) { set_ValueNoCheck (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setM_Product_AttachmentEntry_ReferencedRecord_v_ID (final int M_Product_AttachmentEntry_ReferencedRecord_v_ID) { if (M_Product_AttachmentEntry_ReferencedRecord_v_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_ID, M_Product_AttachmentEntry_ReferencedRecord_v_ID); } @Override public int getM_Product_AttachmentEntry_ReferencedRecord_v_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AttachmentEntry_ReferencedRecord_v_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 setType (final boolean Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public boolean isType() { return get_ValueAsBoolean(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_AttachmentEntry_ReferencedRecord_v.java
1
请完成以下Java代码
public static final class Builder extends AbstractAttributeDefinitionBuilder<Builder, FixedObjectTypeAttributeDefinition> { private String suffix; private final AttributeDefinition[] valueTypes; public Builder(final String name, final AttributeDefinition... valueTypes) { super(name, ModelType.OBJECT, true); this.valueTypes = valueTypes; } public static Builder of(final String name, final AttributeDefinition... valueTypes) { return new Builder(name, valueTypes); } public static Builder of(final String name, final AttributeDefinition[] valueTypes, final AttributeDefinition[] moreValueTypes) { ArrayList<AttributeDefinition> list = new ArrayList<>(Arrays.asList(valueTypes)); list.addAll(Arrays.asList(moreValueTypes)); AttributeDefinition[] allValueTypes = new AttributeDefinition[list.size()]; list.toArray(allValueTypes); return new Builder(name, allValueTypes); } public FixedObjectTypeAttributeDefinition build() { ParameterValidator validator = getValidator(); if (validator == null) { ObjectTypeValidator objectTypeValidator = new ObjectTypeValidator(isAllowNull(), valueTypes);
setValidator(objectTypeValidator); } return new FixedObjectTypeAttributeDefinition(this, suffix, valueTypes); } /* -------------------------- added for binary compatibility for running compatibilty tests */ @Override public Builder setAllowNull(boolean allowNull) { return super.setAllowNull(allowNull); } } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\util\FixedObjectTypeAttributeDefinition.java
1
请完成以下Java代码
private static BigDecimal computeQtySupply_Sum(@NonNull final I_MD_Cockpit dataRecord) { return dataRecord.getQtySupply_PurchaseOrder_AtDate() .add(dataRecord.getQtySupply_PP_Order_AtDate()) .add(dataRecord.getQtySupply_DD_Order_AtDate()); } /** * The quantity required according to material disposition that is not yet addressed by purchase order, production-receipt or distribution order. * * @param dataRecord I_MD_Cockpit * @return dataRecord.QtySupplyRequired - dataRecord.QtySupplySum */ public static BigDecimal computeQtySupplyToSchedule(@NonNull final I_MD_Cockpit dataRecord) { return CoalesceUtil.firstPositiveOrZero( dataRecord.getQtySupplyRequired_AtDate().subtract(dataRecord.getQtySupplySum_AtDate())); } /** * Current pending supplies minus pending demands * * @param dataRecord I_MD_Cockpit * @return dataRecord.QtyStockCurrent + dataRecord.QtySupplySum - dataRecord.QtyDemandSum */
public static BigDecimal computeQtyExpectedSurplus(@NonNull final I_MD_Cockpit dataRecord) { return dataRecord.getQtySupplySum_AtDate().subtract(dataRecord.getQtyDemandSum_AtDate()); } @NonNull private static BigDecimal computeSum(@NonNull final BigDecimal... args) { final BigDecimal sum = Stream.of(args) .reduce(BigDecimal::add) .orElse(BigDecimal.ZERO); return stripTrailingDecimalZeros(sum); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\mainrecord\MainDataRequestHandler.java
1
请完成以下Java代码
protected CmmnActivity getScope(CmmnExecution execution) { return execution.getActivity(); } public boolean isAsync(CmmnExecution execution) { return false; } protected void eventNotificationsCompleted(CmmnExecution execution) { repetition(execution); preTransitionNotification(execution); performTransitionNotification(execution); postTransitionNotification(execution); } protected void repetition(CmmnExecution execution) { CmmnActivityBehavior behavior = getActivityBehavior(execution); behavior.repeat(execution, getEventName()); }
protected void preTransitionNotification(CmmnExecution execution) { } protected void performTransitionNotification(CmmnExecution execution) { String eventName = getEventName(); CmmnExecution parent = execution.getParent(); if (parent != null) { parent.handleChildTransition(execution, eventName); } } protected void postTransitionNotification(CmmnExecution execution) { // noop } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AbstractCmmnEventAtomicOperation.java
1
请完成以下Java代码
private <T> PropertySource<T> instantiatePropertySource(PropertySource<T> propertySource) { PropertySource<T> encryptablePropertySource; if (needsProxyAnyway(propertySource)) { encryptablePropertySource = proxyPropertySource(propertySource); } else if (propertySource instanceof SystemEnvironmentPropertySource) { encryptablePropertySource = (PropertySource<T>) new EncryptableSystemEnvironmentPropertySourceWrapper((SystemEnvironmentPropertySource) propertySource, propertyResolver, propertyFilter); } else if (propertySource instanceof MapPropertySource) { encryptablePropertySource = (PropertySource<T>) new EncryptableMapPropertySourceWrapper((MapPropertySource) propertySource, propertyResolver, propertyFilter); } else if (propertySource instanceof EnumerablePropertySource) { encryptablePropertySource = new EncryptableEnumerablePropertySourceWrapper<>((EnumerablePropertySource) propertySource, propertyResolver, propertyFilter); } else { encryptablePropertySource = new EncryptablePropertySourceWrapper<>(propertySource, propertyResolver, propertyFilter); } return encryptablePropertySource; } @SuppressWarnings("unchecked") private static boolean needsProxyAnyway(PropertySource<?> ps) { return needsProxyAnyway((Class<? extends PropertySource<?>>) ps.getClass()); } private static boolean needsProxyAnyway(Class<? extends PropertySource<?>> psClass) {
return needsProxyAnyway(psClass.getName()); } /** * Some Spring Boot code actually casts property sources to this specific type so must be proxied. */ @SuppressWarnings({"ConstantConditions", "SimplifyStreamApiCallChains"}) private static boolean needsProxyAnyway(String className) { // Turned off for now return Stream.of( // "org.springframework.boot.context.config.ConfigFileApplicationListener$ConfigurationPropertySources", // "org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource" ).anyMatch(className::equals); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\EncryptablePropertySourceConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class WEBUI_M_HU_CreateReceipt_MovementAndAcctDateParams extends WEBUI_M_HU_CreateReceipt_Base implements IProcessPrecondition { private final static String MOVEMENT_DATE_PARAM_NAME = I_M_ReceiptSchedule.COLUMNNAME_MovementDate; @Param(parameterName = MOVEMENT_DATE_PARAM_NAME, mandatory = true) private LocalDate movementDate; private final static String ACCT_DATE_PARAM_NAME = I_M_InOut.COLUMNNAME_DateAcct; @Param(parameterName = ACCT_DATE_PARAM_NAME) private LocalDate dateAcct; @Override protected void customizeParametersBuilder(@NonNull final IHUReceiptScheduleBL.CreateReceiptsParameters.CreateReceiptsParametersBuilder parametersBuilder) { final LocalDate dateAcctToUse = CoalesceUtil.coalesce(dateAcct, movementDate); final ReceiptScheduleExternalInfo scheduleExternalInfo = ReceiptScheduleExternalInfo.builder() .movementDate(movementDate)
.dateAcct(dateAcctToUse) .build(); final ImmutableMap<ReceiptScheduleId, ReceiptScheduleExternalInfo> externalInfoByScheduleId = getM_ReceiptSchedules() .stream() .map(I_M_ReceiptSchedule::getM_ReceiptSchedule_ID) .map(ReceiptScheduleId::ofRepoId) .distinct() .collect(ImmutableMap.toImmutableMap(Function.identity(), (ignored) -> scheduleExternalInfo)); parametersBuilder .movementDateRule(ReceiptMovementDateRule.EXTERNAL_DATE_IF_AVAIL) .externalInfoByReceiptScheduleId(externalInfoByScheduleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_MovementAndAcctDateParams.java
2
请完成以下Java代码
public void fireAfterCommit(final ITrx trx) { // Execute the "afterCommit", but don't fail because we are not allowed to fail by method's contract fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_COMMIT, trx); } @Override public void fireAfterRollback(final ITrx trx) { // Execute the "afterRollback", but don't fail because we are not allowed to fail by method's contract fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_ROLLBACK, trx); } @Override public void fireAfterClose(final ITrx trx) { // Execute the "afterClose", but don't fail because we are not allowed to fail by method's contract fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_CLOSE, trx); } private final void fireListeners( @NonNull final OnError onError, @NonNull final TrxEventTiming timingInfo, @NonNull final ITrx trx) { if (listeners == null) { return; } runningWithinTrxEventTiming.set(timingInfo); try { listeners.hardList().stream() .filter(Objects::nonNull) .filter(listener -> timingInfo.equals(listener.getTiming())) .forEach(listener -> fireListener(onError, timingInfo, trx, listener)); } finally { runningWithinTrxEventTiming.set(TrxEventTiming.NONE); } } private void fireListener( @NonNull final OnError onError, @NonNull final TrxEventTiming timingInfo, @NonNull final ITrx trx, @Nullable final RegisterListenerRequest listener) { // shouldn't be necessary but in fact i just had an NPE at this place if (listener == null || !listener.isActive()) {
return; } // Execute the listener method try { listener.getHandlingMethod().onTransactionEvent(trx); } catch (final Exception ex) { handleException(onError, timingInfo, listener, ex); } finally { if (listener.isInvokeMethodJustOnce()) { listener.deactivate(); } } } private void handleException( @NonNull final OnError onError, @NonNull final TrxEventTiming timingInfo, @NonNull final RegisterListenerRequest listener, @NonNull final Exception ex) { if (onError == OnError.LogAndSkip) { logger.warn("Error while invoking {} using {}. Error was discarded.", timingInfo, listener, ex); } else // if (onError == OnError.ThrowException) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("listener", listener) .setParameter(timingInfo) .appendParametersToMessage(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxListenerManager.java
1
请完成以下Java代码
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbLogNodeConfiguration.class); standard = isStandard(config); scriptEngine = standard ? null : createScriptEngine(ctx, config); } ScriptEngine createScriptEngine(TbContext ctx, TbLogNodeConfiguration config) { return ctx.createScriptEngine(config.getScriptLang(), ScriptLanguage.TBEL.equals(config.getScriptLang()) ? config.getTbelScript() : config.getJsScript()); } @Override public void onMsg(TbContext ctx, TbMsg msg) { if (!log.isInfoEnabled()) { ctx.tellSuccess(msg); return; } if (standard) { logStandard(ctx, msg); return; } Futures.addCallback(scriptEngine.executeToStringAsync(msg), new FutureCallback<>() { @Override public void onSuccess(@Nullable String result) { log.info(result); ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }, MoreExecutors.directExecutor()); //usually js responses runs on js callback executor }
boolean isStandard(TbLogNodeConfiguration conf) { Objects.requireNonNull(conf, "node config is null"); final TbLogNodeConfiguration defaultConfig = new TbLogNodeConfiguration().defaultConfiguration(); if (conf.getScriptLang() == null || conf.getScriptLang().equals(ScriptLanguage.JS)) { return defaultConfig.getJsScript().equals(conf.getJsScript()); } else if (conf.getScriptLang().equals(ScriptLanguage.TBEL)) { return defaultConfig.getTbelScript().equals(conf.getTbelScript()); } else { log.warn("No rule to define isStandard script for script language [{}], assuming that is non-standard", conf.getScriptLang()); return false; } } void logStandard(TbContext ctx, TbMsg msg) { log.info(toLogMessage(msg)); ctx.tellSuccess(msg); } String toLogMessage(TbMsg msg) { return "\n" + "Incoming message:\n" + msg.getData() + "\n" + "Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData()); } @Override public void destroy() { if (scriptEngine != null) { scriptEngine.destroy(); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbLogNode.java
1
请完成以下Java代码
protected void suspendAllJobs(CommandContext commandContext) { if (getNewState() == SuspensionState.ACTIVE) { List<SuspendedJobEntity> suspendedJobs = commandContext .getSuspendedJobEntityManager() .findJobsByProcessInstanceId(processInstanceId); for (SuspendedJobEntity suspendedJob : suspendedJobs) { commandContext.getJobManager().activateSuspendedJob(suspendedJob); } } else { List<TimerJobEntity> timerJobs = commandContext .getTimerJobEntityManager() .findJobsByProcessInstanceId(processInstanceId); for (TimerJobEntity timerJob : timerJobs) { commandContext.getJobManager().moveJobToSuspendedJob(timerJob); } List<JobEntity> jobs = commandContext.getJobEntityManager().findJobsByProcessInstanceId(processInstanceId); for (JobEntity job : jobs) { commandContext.getJobManager().moveJobToSuspendedJob(job); } } } protected void updateChildrenSuspensionState(CommandContext commandContext) { Collection<ExecutionEntity> childExecutions = commandContext .getExecutionEntityManager() .findChildExecutionsByProcessInstanceId(processInstanceId); for (ExecutionEntity childExecution : childExecutions) { if (!childExecution.getId().equals(processInstanceId)) { SuspensionStateUtil.setSuspensionState(childExecution, getNewState());
commandContext.getExecutionEntityManager().update(childExecution, false); } } } protected void updateTaskSuspensionState(CommandContext commandContext) { List<TaskEntity> tasks = commandContext.getTaskEntityManager().findTasksByProcessInstanceId(processInstanceId); for (TaskEntity taskEntity : tasks) { SuspensionStateUtil.setSuspensionState(taskEntity, getNewState()); commandContext.getTaskEntityManager().update(taskEntity, false); } } protected abstract SuspensionState getNewState(); }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AbstractSetProcessInstanceStateCmd.java
1
请完成以下Java代码
public void setConverter(HttpMessageConverter<Object> converter) { Assert.notNull(converter, "converter cannot be null"); this.converter = converter; } /** * Sets the {@link RequestCache} to use. The default is * {@link HttpSessionRequestCache}. * @param requestCache the {@link RequestCache} to use. Cannot be null */ public void setRequestCache(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { final SavedRequest savedRequest = this.requestCache.getRequest(request, response); final String redirectUrl = (savedRequest != null) ? savedRequest.getRedirectUrl() : request.getContextPath() + "/"; this.requestCache.removeRequest(request, response); this.converter.write(new AuthenticationSuccess(redirectUrl), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response)); } /** * A response object used to write the JSON response for successful authentication. * * NOTE: We should be careful about writing {@link Authentication} or * {@link Authentication#getPrincipal()} to the response since it contains
* credentials. */ public static final class AuthenticationSuccess { private final String redirectUrl; private AuthenticationSuccess(String redirectUrl) { this.redirectUrl = redirectUrl; } public String getRedirectUrl() { return this.redirectUrl; } public boolean isAuthenticated() { return true; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\HttpMessageConverterAuthenticationSuccessHandler.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_C_AllocationHdr getReversal() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class); } @Override public void setReversal(org.compiere.model.I_C_AllocationHdr Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class, Reversal); } /** Set Reversal ID. @param Reversal_ID ID of document reversal */ @Override
public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) { set_Value (COLUMNNAME_Reversal_ID, null); } else { set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } } /** Get Reversal ID. @return ID of document reversal */ @Override public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationHdr.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // 定义了两个客户端应用的通行证 clients.inMemory() .withClient("sheep1") .secret(new BCryptPasswordEncoder().encode("123456")) .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("all") .autoApprove(false) .and() .withClient("sheep2") .secret(new BCryptPasswordEncoder().encode("123456")) .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("all") .autoApprove(false); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter()); DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices(); tokenServices.setTokenStore(endpoints.getTokenStore()); tokenServices.setSupportRefreshToken(true);
tokenServices.setClientDetailsService(endpoints.getClientDetailsService()); tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer()); tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 一天有效期 endpoints.tokenServices(tokenServices); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.tokenKeyAccess("isAuthenticated()"); } @Bean public TokenStore jwtTokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter(){ JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("testKey"); return converter; } }
repos\Spring-Boot-In-Action-master\springbt_sso_jwt\codesheep-server\src\main\java\cn\codesheep\config\AuthorizationServerConfig.java
2
请完成以下Java代码
String readHeader() throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; StringBuilder content = new StringBuilder(BUFFER_SIZE); while (content.indexOf(HEADER_END) == -1) { int amountRead = checkedRead(buffer, 0, BUFFER_SIZE); content.append(new String(buffer, 0, amountRead)); } return content.substring(0, content.indexOf(HEADER_END)); } /** * Repeatedly read the underlying {@link InputStream} until the requested number of * bytes have been loaded. * @param buffer the destination buffer * @param offset the buffer offset * @param length the amount of data to read * @throws IOException in case of I/O errors */ void readFully(byte[] buffer, int offset, int length) throws IOException { while (length > 0) { int amountRead = checkedRead(buffer, offset, length); offset += amountRead; length -= amountRead; } } /** * Read a single byte from the stream (checking that the end of the stream hasn't been * reached). * @return the content * @throws IOException in case of I/O errors */ int checkedRead() throws IOException { int b = read();
if (b == -1) { throw new IOException("End of stream"); } return (b & 0xff); } /** * Read a number of bytes from the stream (checking that the end of the stream hasn't * been reached). * @param buffer the destination buffer * @param offset the buffer offset * @param length the length to read * @return the amount of data read * @throws IOException in case of I/O errors */ int checkedRead(byte[] buffer, int offset, int length) throws IOException { int amountRead = read(buffer, offset, length); if (amountRead == -1) { throw new IOException("End of stream"); } return amountRead; } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\ConnectionInputStream.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public org.compiere.model.I_Fact_Acct getFact_Acct() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class); } @Override public void setFact_Acct(org.compiere.model.I_Fact_Acct Fact_Acct) { set_ValueFromPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class, Fact_Acct); } /** Set Accounting Fact. @param Fact_Acct_ID Accounting Fact */ @Override public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ @Override public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationAcct.java
1
请完成以下Java代码
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } public String updateProcessBusinessKey(String bzKey) { if (isProcessInstanceType() && bzKey != null) { setBusinessKey(bzKey); Context.getCommandContext().getHistoryManager().updateProcessBusinessKeyInHistory(this); if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } return bzKey; } return null; } public void deleteIdentityLink(String userId, String groupId, String type) { List<IdentityLinkEntity> identityLinks = Context.getCommandContext().getIdentityLinkEntityManager() .findIdentityLinkByProcessInstanceUserGroupAndType(id, userId, groupId, type); for (IdentityLinkEntity identityLink : identityLinks) { Context.getCommandContext().getIdentityLinkEntityManager().deleteIdentityLink(identityLink, true); } getIdentityLinks().removeAll(identityLinks); } // NOT IN V5 @Override public boolean isMultiInstanceRoot() { return false;
} @Override public void setMultiInstanceRoot(boolean isMultiInstanceRoot) { } @Override public String getPropagatedStageInstanceId() { return null; } protected void callJobProcessors(JobProcessorContext.Phase processorType, AbstractJobEntity abstractJobEntity, ProcessEngineConfigurationImpl processEngineConfiguration) { JobProcessorContextImpl jobProcessorContext = new JobProcessorContextImpl(processorType, abstractJobEntity); for (JobProcessor jobProcessor : processEngineConfiguration.getJobProcessors()) { jobProcessor.process(jobProcessorContext); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntity.java
1
请在Spring Boot框架中完成以下Java代码
public int update(Long id, UmsMenu umsMenu) { umsMenu.setId(id); updateLevel(umsMenu); return menuMapper.updateByPrimaryKeySelective(umsMenu); } @Override public UmsMenu getItem(Long id) { return menuMapper.selectByPrimaryKey(id); } @Override public int delete(Long id) { return menuMapper.deleteByPrimaryKey(id); } @Override public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); UmsMenuExample example = new UmsMenuExample(); example.setOrderByClause("sort desc"); example.createCriteria().andParentIdEqualTo(parentId); return menuMapper.selectByExample(example); } @Override public List<UmsMenuNode> treeList() { List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample()); List<UmsMenuNode> result = menuList.stream() .filter(menu -> menu.getParentId().equals(0L)) .map(menu -> covertMenuNode(menu, menuList)) .collect(Collectors.toList()); return result; } @Override public int updateHidden(Long id, Integer hidden) { UmsMenu umsMenu = new UmsMenu();
umsMenu.setId(id); umsMenu.setHidden(hidden); return menuMapper.updateByPrimaryKeySelective(umsMenu); } /** * 将UmsMenu转化为UmsMenuNode并设置children属性 */ private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) { UmsMenuNode node = new UmsMenuNode(); BeanUtils.copyProperties(menu, node); List<UmsMenuNode> children = menuList.stream() .filter(subMenu -> subMenu.getParentId().equals(menu.getId())) .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList()); node.setChildren(children); return node; } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) {
this.endTime = endTime; } @ApiModelProperty(example = "86400056") public Long getDurationInMillis() { return durationInMillis; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
2
请完成以下Java代码
private UserMenuInfo getUserMenuInfo() { final IUserRolePermissions userRolePermissions = getUserRolePermissions(); if (!userRolePermissions.hasPermission(IUserRolePermissions.PERMISSION_MenuAvailable)) { return UserMenuInfo.NONE; } return userRolePermissions.getMenuInfo(); } public MenuTreeLoader setAD_Language(final String adLanguage) { this._adLanguage = adLanguage; return this; }
@NonNull private String getAD_Language() { return _adLanguage; } private long getVersion() { if (_version < 0) { _version = userRolePermissionsDAO.getCacheVersion(); } return _version; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeLoader.java
1
请完成以下Java代码
public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script);
} /** * Determine if this element needs a line break, if pretty printing. */ public boolean getNeedLineBreak () { java.util.Enumeration en = elements (); int i = 0; int j = 0; while (en.hasMoreElements ()) { j++; Object obj = en.nextElement (); if (obj instanceof img) i++; } if (i == j) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\a.java
1
请完成以下Java代码
public void setRoot_ID (int Root_ID) { if (Root_ID < 1) set_Value (COLUMNNAME_Root_ID, null); else set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID)); } /** Get Root Entry. @return Root Entry */ @Override public int getRoot_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); }
/** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java
1
请完成以下Java代码
public class X_M_Product_AlbertaPackagingUnit extends org.compiere.model.PO implements I_M_Product_AlbertaPackagingUnit, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1129871042L; /** Standard Constructor */ public X_M_Product_AlbertaPackagingUnit (final Properties ctx, final int M_Product_AlbertaPackagingUnit_ID, @Nullable final String trxName) { super (ctx, M_Product_AlbertaPackagingUnit_ID, trxName); } /** Load Constructor */ public X_M_Product_AlbertaPackagingUnit (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * ArticleUnit AD_Reference_ID=541280 * Reference name: ArticleUnit */ public static final int ARTICLEUNIT_AD_Reference_ID=541280; /** PCE = Stk */ public static final String ARTICLEUNIT_PCE = "Stk"; /** BOX = Ktn */ public static final String ARTICLEUNIT_BOX = "Ktn"; @Override public void setArticleUnit (final String ArticleUnit) { set_Value (COLUMNNAME_ArticleUnit, ArticleUnit); } @Override public String getArticleUnit() { return get_ValueAsString(COLUMNNAME_ArticleUnit); } @Override public void setM_Product_AlbertaPackagingUnit_ID (final int M_Product_AlbertaPackagingUnit_ID) { if (M_Product_AlbertaPackagingUnit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaPackagingUnit_ID, M_Product_AlbertaPackagingUnit_ID); } @Override public int getM_Product_AlbertaPackagingUnit_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaPackagingUnit_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 @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaPackagingUnit.java
1
请在Spring Boot框架中完成以下Java代码
void processing(RoundEnvironment roundEnv) { for (Element element : roundEnv.getRootElements()) { if (element instanceof TypeElement) { this.processedSourceTypes.add(this.typeUtils.getQualifiedName(element)); } } } MetadataCollector getModuleMetadataCollector() { return this.metadataCollector; } MetadataCollector getMetadataCollector(TypeElement element) { return this.metadataTypeCollectors.computeIfAbsent(element, (ignored) -> new MetadataCollector(this::shouldBeMerged, this.metadataStore.readMetadata(element))); }
Set<TypeElement> getSourceTypes() { return this.metadataTypeCollectors.keySet(); } private boolean shouldBeMerged(ItemMetadata itemMetadata) { String sourceType = itemMetadata.getSourceType(); return (sourceType != null && !deletedInCurrentBuild(sourceType) && !processedInCurrentBuild(sourceType)); } private boolean deletedInCurrentBuild(String sourceType) { return this.processingEnvironment.getElementUtils().getTypeElement(sourceType.replace('$', '.')) == null; } private boolean processedInCurrentBuild(String sourceType) { return this.processedSourceTypes.contains(sourceType); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\MetadataCollectors.java
2
请完成以下Java代码
public void setIsDynamic (final boolean IsDynamic) { set_Value (COLUMNNAME_IsDynamic, IsDynamic); } @Override public boolean isDynamic() { return get_ValueAsBoolean(COLUMNNAME_IsDynamic); } @Override public void setIsPickingRackSystem (final boolean IsPickingRackSystem) { set_Value (COLUMNNAME_IsPickingRackSystem, IsPickingRackSystem); } @Override public boolean isPickingRackSystem() { return get_ValueAsBoolean(COLUMNNAME_IsPickingRackSystem); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_Value (COLUMNNAME_M_HU_ID, null); else set_Value (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); }
@Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_PickingSlot_ID (final int M_PickingSlot_ID) { if (M_PickingSlot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID); } @Override public int getM_PickingSlot_ID() { return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setPickingSlot (final java.lang.String PickingSlot) { set_Value (COLUMNNAME_PickingSlot, PickingSlot); } @Override public java.lang.String getPickingSlot() { return get_ValueAsString(COLUMNNAME_PickingSlot); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_PickingSlot.java
1
请完成以下Java代码
public void setBinaryData (final @Nullable byte[] BinaryData) { set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData); } @Override public byte[] getBinaryData() { return (byte[])get_Value(COLUMNNAME_BinaryData); } @Override public void setContentType (final @Nullable java.lang.String ContentType) { set_Value (COLUMNNAME_ContentType, ContentType); } @Override public java.lang.String getContentType() { return get_ValueAsString(COLUMNNAME_ContentType); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setFileName (final java.lang.String FileName) { set_Value (COLUMNNAME_FileName, FileName); } @Override public java.lang.String getFileName() { return get_ValueAsString(COLUMNNAME_FileName); } @Override public void setTags (final @Nullable java.lang.String Tags) { set_Value (COLUMNNAME_Tags, Tags); }
@Override public java.lang.String getTags() { return get_ValueAsString(COLUMNNAME_Tags); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Local File-URL = LU */ public static final String TYPE_LocalFile_URL = "LU"; @Override public void setType (final java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry.java
1
请完成以下Java代码
public final class BooleanWithReason { public static BooleanWithReason trueBecause(@NonNull final String reason) { return trueBecause(toTrl(reason)); } public static BooleanWithReason trueBecause(@NonNull final ITranslatableString reason) { if (TranslatableStrings.isBlank(reason)) { return TRUE; } else { return new BooleanWithReason(true, reason); } } public static BooleanWithReason falseBecause(@NonNull final String reason) { return falseBecause(toTrl(reason)); } public static BooleanWithReason falseBecause(@NonNull final ITranslatableString reason) { if (TranslatableStrings.isBlank(reason)) { return FALSE; } else { return new BooleanWithReason(false, reason); } } public static BooleanWithReason falseBecause(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return falseBecause(TranslatableStrings.adMessage(adMessage, msgParameters)); } public static BooleanWithReason falseBecause(@NonNull final Exception exception) { return falseBecause(AdempiereException.extractMessageTrl(exception)); } public static BooleanWithReason falseIf(final boolean condition, @NonNull final String falseReason) { return condition ? falseBecause(falseReason) : TRUE; } private static ITranslatableString toTrl(@Nullable final String reasonStr) { if (reasonStr == null || Check.isBlank(reasonStr)) { return TranslatableStrings.empty(); } else { return TranslatableStrings.anyLanguage(reasonStr.trim()); } } public static final BooleanWithReason TRUE = new BooleanWithReason(true, TranslatableStrings.empty()); public static final BooleanWithReason FALSE = new BooleanWithReason(false, TranslatableStrings.empty()); private final boolean value; @NonNull @Getter private final ITranslatableString reason; private BooleanWithReason( final boolean value, @NonNull final ITranslatableString reason) {
this.value = value; this.reason = reason; } @Override public String toString() { final String valueStr = String.valueOf(value); final String reasonStr = !TranslatableStrings.isBlank(reason) ? reason.getDefaultValue() : null; return reasonStr != null ? valueStr + " because " + reasonStr : valueStr; } public boolean toBoolean() { return value; } public boolean isTrue() { return value; } public boolean isFalse() { return !value; } public String getReasonAsString() { return reason.getDefaultValue(); } public void assertTrue() { if (isFalse()) { throw new AdempiereException(reason); } } public BooleanWithReason and(@NonNull final Supplier<BooleanWithReason> otherSupplier) { return isFalse() ? this : Check.assumeNotNull(otherSupplier.get(), "otherSupplier shall not return null"); } public void ifTrue(@NonNull final Consumer<String> consumer) { if (isTrue()) { consumer.accept(getReasonAsString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\BooleanWithReason.java
1
请完成以下Java代码
public int getEventSize() { return eventSize; } public void setEventSize(int eventSize) { this.eventSize = eventSize; } public int getGatewaySize() { return gatewaySize; } public void setGatewaySize(int gatewaySize) { this.gatewaySize = gatewaySize; } public int getTaskWidth() { return taskWidth; } public void setTaskWidth(int taskWidth) { this.taskWidth = taskWidth; } public int getTaskHeight() { return taskHeight; }
public void setTaskHeight(int taskHeight) { this.taskHeight = taskHeight; } public int getSubProcessMargin() { return subProcessMargin; } public void setSubProcessMargin(int subProcessMargin) { this.subProcessMargin = subProcessMargin; } // Due to a bug (see // http://forum.jgraph.com/questions/5952/mxhierarchicallayout-not-correct-when-using-child-vertex) // We must extend the default hierarchical layout to tweak it a bit (see url // link) otherwise the layouting crashes. // // Verify again with a later release if fixed (ie the mxHierarchicalLayout // can be used directly) static class CustomLayout extends mxHierarchicalLayout { public CustomLayout(mxGraph graph, int orientation) { super(graph, orientation); this.traverseAncestors = false; } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BpmnAutoLayout.java
1
请完成以下Java代码
public class DocumentLayoutBuildException extends AdempiereException { public static DocumentLayoutBuildException wrapIfNeeded(final Throwable throwable) { if (throwable == null) { return null; } else if (throwable instanceof DocumentLayoutBuildException) { return (DocumentLayoutBuildException)throwable; } final Throwable cause = extractCause(throwable); if (cause != throwable) { return wrapIfNeeded(cause); } // default return new DocumentLayoutBuildException(cause.getLocalizedMessage(), cause); } public static Throwable extractCause(final Throwable throwable) { if (throwable.getClass().equals(DocumentLayoutBuildException.class)) { final DocumentLayoutBuildException documentLayoutBuildException = (DocumentLayoutBuildException) throwable; final Throwable cause = documentLayoutBuildException.getCause(); return cause != null ? cause : documentLayoutBuildException; } else
{ return AdempiereException.extractCause(throwable); } } public DocumentLayoutBuildException(final String message) { super(message); } private DocumentLayoutBuildException(final String message, final Throwable cause) { super(message, cause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\exceptions\DocumentLayoutBuildException.java
1
请完成以下Java代码
public boolean isReadOnly(ELContext context) throws ELException { return true; } @Override public Class<?> getType(ELContext context) throws ELException { return Object.class; } @Override public Class<?> getExpectedType() { return Object.class; } @Override public String getExpressionString() { return body.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof LambdaBodyValueExpression)) return false; LambdaBodyValueExpression other = (LambdaBodyValueExpression) obj; return body.equals(other.body) && bindings.equals(other.bindings); }
@Override public int hashCode() { return body.hashCode() * 31 + bindings.hashCode(); } @Override public boolean isLiteralText() { return false; } @Override public ValueReference getValueReference(ELContext context) { return null; } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaExpression.java
1
请完成以下Java代码
public Map<String, String> getParams() { return params; } public void setParams(Map<String, String> params) { this.params = params; } @Override public String toString() { StringBuilder strb = new StringBuilder(); strb.append("[Validation set: '" + validatorSetName + "' | Problem: '" + problem + "'] : "); strb.append(defaultDescription); strb.append(" - [Extra info : "); boolean extraInfoAlreadyPresent = false; if (processDefinitionId != null) { strb.append("processDefinitionId = " + processDefinitionId); extraInfoAlreadyPresent = true; } if (processDefinitionName != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("processDefinitionName = " + processDefinitionName + " | "); extraInfoAlreadyPresent = true; } if (activityId != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("id = " + activityId + " | "); extraInfoAlreadyPresent = true; } if (activityName != null) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append("activityName = " + activityName + " | "); extraInfoAlreadyPresent = true; } if (xmlLineNumber > 0 && xmlColumnNumber > 0) { strb.append(" ( line: " + xmlLineNumber + ", column: " + xmlColumnNumber + ")"); } if (key != null) {
if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append(" ( key: " + key + " )"); extraInfoAlreadyPresent = true; } if (params != null && !params.isEmpty()) { if (extraInfoAlreadyPresent) { strb.append(" | "); } strb.append(" ( "); for (Map.Entry<String, String> param : params.entrySet()) { strb.append(param.getKey() + " = " + param.getValue() + " | "); } strb.append(")"); extraInfoAlreadyPresent = true; } strb.append("]"); return strb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\ValidationError.java
1
请完成以下Java代码
public void deleteSlide(XMLSlideShow ppt, int slideNumber) { ppt.removeSlide(slideNumber); } /** * Re-order the slides inside a presentation * * @param ppt * The presentation * @param slideNumber * The number of the slide to move * @param newSlideNumber * The new position of the slide (0-base) */ public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) { List<XSLFSlide> slides = ppt.getSlides(); XSLFSlide secondSlide = slides.get(slideNumber); ppt.setSlideOrder(secondSlide, newSlideNumber); } /** * Retrieve the placeholder inside a slide * * @param slide * The slide * @return List of placeholder inside a slide */ public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) { List<XSLFShape> placeholders = new ArrayList<>(); for (XSLFShape shape : slide.getShapes()) { if (shape instanceof XSLFAutoShape) { placeholders.add(shape); } } return placeholders; } /** * Create a table * * @param slide * Slide */ private void createTable(XSLFSlide slide) { XSLFTable tbl = slide.createTable(); tbl.setAnchor(new Rectangle(50, 50, 450, 300)); int numColumns = 3; int numRows = 5; // header XSLFTableRow headerRow = tbl.addRow(); headerRow.setHeight(50); for (int i = 0; i < numColumns; i++) { XSLFTableCell th = headerRow.addCell(); XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextParagraph.TextAlign.CENTER); XSLFTextRun r = p.addNewTextRun(); r.setText("Header " + (i + 1)); r.setBold(true); r.setFontColor(Color.white); th.setFillColor(new Color(79, 129, 189)); th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0); th.setBorderColor(TableCell.BorderEdge.bottom, Color.white); // all columns are equally sized tbl.setColumnWidth(i, 150); } // data for (int rownum = 0; rownum < numRows; rownum++) { XSLFTableRow tr = tbl.addRow(); tr.setHeight(50); for (int i = 0; i < numColumns; i++) { XSLFTableCell cell = tr.addCell(); XSLFTextParagraph p = cell.addNewTextParagraph(); XSLFTextRun r = p.addNewTextRun(); r.setText("Cell " + (i * rownum + 1)); if (rownum % 2 == 0) { cell.setFillColor(new Color(208, 216, 232)); } else { cell.setFillColor(new Color(233, 247, 244)); } } } } }
repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\powerpoint\PowerPointHelper.java
1
请完成以下Java代码
public POSProductsSearchResult getProducts( @NonNull final POSTerminalId posTerminalId, @NonNull final Instant evalDate, @Nullable final String queryString) { return productsService.getProducts(posTerminalId, evalDate, queryString); } public List<POSOrder> getOpenOrders( @NonNull final POSTerminalId posTerminalId, @NonNull final UserId userId, @Nullable final Set<POSOrderExternalId> onlyOrderExternalIds) { return ordersService.list(POSOrderQuery.builder() .posTerminalId(posTerminalId) .cashierId(userId) .isOpen(true) .onlyOrderExternalIds(onlyOrderExternalIds) .build()); } public POSOrder changeStatusTo( @NonNull final POSTerminalId posTerminalId, @NonNull final POSOrderExternalId externalId, @NonNull final POSOrderStatus nextStatus, @NonNull final UserId userId) { return ordersService.changeStatusTo(posTerminalId, externalId, nextStatus, userId); }
public POSOrder updateOrderFromRemote( @NonNull final RemotePOSOrder remoteOrder, @NonNull final UserId userId) { return ordersService.updateOrderFromRemote(remoteOrder, userId); } public POSOrder checkoutPayment(@NonNull POSPaymentCheckoutRequest request) { return ordersService.checkoutPayment(request); } public POSOrder refundPayment( @NonNull final POSTerminalId posTerminalId, @NonNull final POSOrderExternalId posOrderExternalId, @NonNull final POSPaymentExternalId posPaymentExternalId, @NonNull final UserId userId) { return ordersService.refundPayment(posTerminalId, posOrderExternalId, posPaymentExternalId, userId); } public Optional<Resource> getReceiptPdf(@NonNull final POSOrderExternalId externalId) { return ordersService.getReceiptPdf(externalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSService.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Product_SupplierApproval_Norm_ID (final int M_Product_SupplierApproval_Norm_ID) { if (M_Product_SupplierApproval_Norm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, M_Product_SupplierApproval_Norm_ID); } @Override public int getM_Product_SupplierApproval_Norm_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_SupplierApproval_Norm_ID); } /**
* SupplierApproval_Norm AD_Reference_ID=541363 * Reference name: SupplierApproval_Norm */ public static final int SUPPLIERAPPROVAL_NORM_AD_Reference_ID=541363; /** ISO 9100 Luftfahrt = ISO9100 */ public static final String SUPPLIERAPPROVAL_NORM_ISO9100Luftfahrt = "ISO9100"; /** TS 16949 = TS16949 */ public static final String SUPPLIERAPPROVAL_NORM_TS16949 = "TS16949"; @Override public void setSupplierApproval_Norm (final java.lang.String SupplierApproval_Norm) { set_Value (COLUMNNAME_SupplierApproval_Norm, SupplierApproval_Norm); } @Override public java.lang.String getSupplierApproval_Norm() { return get_ValueAsString(COLUMNNAME_SupplierApproval_Norm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_SupplierApproval_Norm.java
1
请在Spring Boot框架中完成以下Java代码
public ConsumerFactory<String, Message> consumerFactory() { Map<String, Object> props = new HashMap<>(); props.put( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); props.put( ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId); props.put( ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); // props.put( // ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, // StringDeserializer.class); // props.put( // ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, // StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>( props, new StringDeserializer(), new JsonDeserializer<>(Message.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, Message> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, Message> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); // factory.setRecordFilterStrategy( // r -> r.value().contains("fuck") // ); return factory; } }
repos\SpringAll-master\54.Spring-Boot-Kafka\src\main\java\com\example\demo\config\KafkaConsumerConfig.java
2
请完成以下Java代码
protected AstNode nonliteral() throws Scanner.ScanException, ParseException { AstNode v = null; switch (token.getSymbol()) { case IDENTIFIER: String name = consumeToken().getImage(); if (token.getSymbol() == Scanner.Symbol.COLON && lookahead(0).getSymbol() == Scanner.Symbol.IDENTIFIER && lookahead(1).getSymbol() == Scanner.Symbol.LPAREN) { // ns:f(...) consumeToken(); name += ":" + token.getImage(); consumeToken(); } if (token.getSymbol() == Scanner.Symbol.LPAREN) { // function v = function(name, params()); } else { // identifier v = identifier(name); } break; case LPAREN: consumeToken(); v = expr(true); consumeToken(Scanner.Symbol.RPAREN); v = new AstNested(v); break; } return v; } /** * params := &lt;LPAREN&gt; (expr (&lt;COMMA&gt; expr)*)? &lt;RPAREN&gt; */ protected AstParameters params() throws Scanner.ScanException, ParseException { consumeToken(Scanner.Symbol.LPAREN); List<AstNode> l = Collections.emptyList(); AstNode v = expr(false); if (v != null) { l = new ArrayList<AstNode>(); l.add(v); while (token.getSymbol() == Scanner.Symbol.COMMA) { consumeToken(); l.add(expr(true)); } } consumeToken(Scanner.Symbol.RPAREN); return new AstParameters(l); } /** * literal := &lt;TRUE&gt; | &lt;FALSE&gt; | &lt;STRING&gt; | &lt;INTEGER&gt; | &lt;FLOAT&gt; | &lt;NULL&gt; */ protected AstNode literal() throws Scanner.ScanException, ParseException { AstNode v = null; switch (token.getSymbol()) {
case TRUE: v = new AstBoolean(true); consumeToken(); break; case FALSE: v = new AstBoolean(false); consumeToken(); break; case STRING: v = new AstString(token.getImage()); consumeToken(); break; case INTEGER: v = new AstNumber(parseInteger(token.getImage())); consumeToken(); break; case FLOAT: v = new AstNumber(parseFloat(token.getImage())); consumeToken(); break; case NULL: v = new AstNull(); consumeToken(); break; case EXTENSION: if (getExtensionHandler(token).getExtensionPoint() == ExtensionPoint.LITERAL) { v = getExtensionHandler(consumeToken()).createAstNode(); break; } } return v; } protected final AstFunction function(String name, AstParameters params) { if (functions.isEmpty()) { functions = new ArrayList<FunctionNode>(4); } AstFunction function = createAstFunction(name, functions.size(), params); functions.add(function); return function; } protected final AstIdentifier identifier(String name) { if (identifiers.isEmpty()) { identifiers = new ArrayList<IdentifierNode>(4); } AstIdentifier identifier = createAstIdentifier(name, identifiers.size()); identifiers.add(identifier); return identifier; } }
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\Parser.java
1
请完成以下Java代码
private Optional<CachedResponse> getCachedResponse(ServerWebExchange exchange, String metadataKey) { Optional<CachedResponse> cached; if (shouldRevalidate(exchange)) { cached = Optional.empty(); } else { cached = responseCacheManager.getFromCache(exchange.getRequest(), metadataKey); } return cached; } private boolean shouldRevalidate(ServerWebExchange exchange) { return LocalResponseCacheUtils.isNoCacheRequest(exchange.getRequest()); } private class CachingResponseDecorator extends ServerHttpResponseDecorator { private final String metadataKey; private final ServerWebExchange exchange; CachingResponseDecorator(String metadataKey, ServerWebExchange exchange) { super(exchange.getResponse()); this.metadataKey = metadataKey; this.exchange = exchange; } @Override public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
final ServerHttpResponse response = exchange.getResponse(); Flux<DataBuffer> decoratedBody; if (responseCacheManager.isResponseCacheable(response) && !responseCacheManager.isNoCacheRequestWithoutUpdate(exchange.getRequest())) { decoratedBody = responseCacheManager.processFromUpstream(metadataKey, exchange, Flux.from(body)); } else { decoratedBody = Flux.from(body); } return super.writeWith(decoratedBody); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheGatewayFilter.java
1
请完成以下Java代码
public java.lang.String getLetterSubject () { return (java.lang.String)get_Value(COLUMNNAME_LetterSubject); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\letters\model\X_C_Letter.java
1
请完成以下Java代码
public DataFetcherResult<CommentPayload> createComment( @InputArgument("slug") String slug, @InputArgument("body") String body) { User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new); Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); Comment comment = new Comment(body, user.getId(), article.getId()); commentRepository.save(comment); CommentData commentData = commentQueryService .findById(comment.getId(), user) .orElseThrow(ResourceNotFoundException::new); return DataFetcherResult.<CommentPayload>newResult() .localContext(commentData) .data(CommentPayload.newBuilder().build()) .build(); } @DgsData(parentType = MUTATION.TYPE_NAME, field = MUTATION.DeleteComment) public DeletionStatus removeComment( @InputArgument("slug") String slug, @InputArgument("id") String commentId) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new); Article article = articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new); return commentRepository .findById(article.getId(), commentId) .map( comment -> { if (!AuthorizationService.canWriteComment(user, article, comment)) { throw new NoAuthorizationException(); } commentRepository.remove(comment); return DeletionStatus.newBuilder().success(true).build(); }) .orElseThrow(ResourceNotFoundException::new); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\CommentMutation.java
1
请完成以下Java代码
public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent
*/ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java
1
请完成以下Java代码
public class Post { private String title; private String author; private Metadata metadata; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Metadata getMetadata() { return metadata; }
public void setMetadata(Metadata metadata) { this.metadata = metadata; } public static class Metadata { private int wordCount; public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } } }
repos\tutorials-master\core-java-modules\core-java-reflection-3\src\main\java\com\baeldung\reflectionbeans\Post.java
1
请完成以下Java代码
protected boolean executeLogin(ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader(TOKEN); JWTToken jwtToken = new JWTToken(token); try { getSubject(request, response).login(jwtToken); return true; } catch (Exception e) { log.error(e.getMessage()); return false; } } /** * 对跨域提供支持 */
@Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域时会首先发送一个 option请求,这里我们给 option请求直接返回正常状态 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTFilter.java
1
请完成以下Java代码
public void setConditionLanguage(String conditionLanguage) { this.conditionLanguage = conditionLanguage; } public String getSourceRef() { return sourceRef; } public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public FlowElement getSourceFlowElement() { return sourceFlowElement; } public void setSourceFlowElement(FlowElement sourceFlowElement) { this.sourceFlowElement = sourceFlowElement; } public FlowElement getTargetFlowElement() { return targetFlowElement; } public void setTargetFlowElement(FlowElement targetFlowElement) { this.targetFlowElement = targetFlowElement; }
public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } @Override public String toString() { return sourceRef + " --> " + targetRef; } @Override public SequenceFlow clone() { SequenceFlow clone = new SequenceFlow(); clone.setValues(this); return clone; } public void setValues(SequenceFlow otherFlow) { super.setValues(otherFlow); setConditionExpression(otherFlow.getConditionExpression()); setConditionLanguage(otherFlow.getConditionLanguage()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setSkipExpression(otherFlow.getSkipExpression()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SequenceFlow.java
1