instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
private I_MSV3_Vendor_Config createOrUpdateRecord(@NonNull final MSV3ClientConfig config)
{
final I_MSV3_Vendor_Config configRecord;
if (config.getConfigId() != null)
{
final int repoId = config.getConfigId().getRepoId();
configRecord = load(repoId, I_MSV3_Vendor_Config.class);
}
else
{
configRecord = newInstance(I_MSV3_Vendor_Config.class);
}
configRecord.setC_BPartner_ID(config.getBpartnerId().getBpartnerId());
configRecord.setMSV3_BaseUrl(config.getBaseUrl().toExternalForm());
configRecord.setPassword(config.getAuthPassword());
configRecord.setUserID(config.getAuthUsername());
|
return configRecord;
}
private ClientSoftwareId retrieveSoftwareIndentifier()
{
try
{
final ADSystemInfo adSystem = Services.get(ISystemBL.class).get();
return ClientSoftwareId.of("metasfresh-" + adSystem.getDbVersion());
}
catch (final RuntimeException e)
{
return ClientSoftwareId.of("metasfresh-<unable to retrieve version!>");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\config\MSV3ClientConfigRepository.java
| 2
|
请完成以下Java代码
|
public class DataEntryDetailsRowsLoader
{
IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class);
@NonNull
LookupDataSource departmentLookup;
@NonNull
LookupDataSource uomLookup;
@NonNull
FlatrateDataEntryService flatrateDataEntryService;
@NonNull
FlatrateDataEntryRepo flatrateDataEntryRepo;
@NonNull
FlatrateDataEntryId flatrateDataEntryId;
@NonNull
public DataEntryDetailsRowsData load()
{
final ImmutableList<DataEntryDetailsRow> rows = loadRows();
return new DataEntryDetailsRowsData(flatrateDataEntryId, rows, flatrateDataEntryRepo, this);
}
private ImmutableList<DataEntryDetailsRow> loadRows()
{
return loadAllRows();
}
private ImmutableList<DataEntryDetailsRow> loadAllRows()
{
final Predicate<FlatrateDataEntryDetail> all = detail -> true;
return loadMatchingRows(all);
}
public ImmutableList<DataEntryDetailsRow> loadMatchingRows(@NonNull final Predicate<FlatrateDataEntryDetail> filter)
{
final FlatrateDataEntry entry = flatrateDataEntryRepo.getById(flatrateDataEntryId);
final FlatrateDataEntry entryWithAllDetails;
if (!entry.isProcessed())
{
entryWithAllDetails = flatrateDataEntryService.addMissingDetails(entry);
}
else
{
entryWithAllDetails = entry;
}
final LookupValue uom = Check.assumeNotNull(uomLookup.findById(entryWithAllDetails.getUomId()),
"UOM lookup may not be null for C_UOM_ID={}; C_Flatrate_DataEntry_ID={}",
UomId.toRepoId(entryWithAllDetails.getUomId()),
FlatrateDataEntryId.toRepoId(entryWithAllDetails.getId()));
final ImmutableList.Builder<DataEntryDetailsRow> result = ImmutableList.builder();
for (final FlatrateDataEntryDetail detail : entryWithAllDetails.getDetails())
{
if (filter.test(detail))
{
final DataEntryDetailsRow row = toRow(entryWithAllDetails.isProcessed(), uom, detail);
result.add(row);
|
}
}
return result.build();
}
private DataEntryDetailsRow toRow(
final boolean processed,
@NonNull final LookupValue uom,
@NonNull final FlatrateDataEntryDetail detail)
{
final ProductASIDescription productASIDescription = ProductASIDescription.ofString(attributeSetInstanceBL.getASIDescriptionById(detail.getAsiId()));
final DocumentId documentId = DataEntryDetailsRowUtil.createDocumentId(detail);
final BPartnerDepartment bPartnerDepartment = detail.getBPartnerDepartment();
final LookupValue department;
if (bPartnerDepartment.isNone())
{
department = null;
}
else
{
department = departmentLookup.findById(bPartnerDepartment.getId());
}
final DataEntryDetailsRow.DataEntryDetailsRowBuilder row = DataEntryDetailsRow.builder()
.processed(processed)
.id(documentId)
.asi(productASIDescription)
.department(department)
.uom(uom);
if (detail.getQuantity() != null)
{
row.qty(detail.getQuantity().toBigDecimal());
}
return row.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\model\DataEntryDetailsRowsLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class ScheduledBeanLazyInitializationExcludeFilter implements LazyInitializationExcludeFilter {
private final Set<Class<?>> nonAnnotatedClasses = ConcurrentHashMap.newKeySet(64);
ScheduledBeanLazyInitializationExcludeFilter() {
// Ignore AOP infrastructure such as scoped proxies.
this.nonAnnotatedClasses.add(AopInfrastructureBean.class);
this.nonAnnotatedClasses.add(TaskScheduler.class);
this.nonAnnotatedClasses.add(ScheduledExecutorService.class);
}
@Override
public boolean isExcluded(String beanName, BeanDefinition beanDefinition, Class<?> beanType) {
return hasScheduledTask(beanType);
}
private boolean hasScheduledTask(Class<?> type) {
Class<?> targetType = ClassUtils.getUserClass(type);
|
if (!this.nonAnnotatedClasses.contains(targetType)
&& AnnotationUtils.isCandidateClass(targetType, Arrays.asList(Scheduled.class, Schedules.class))) {
Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetType,
(MethodIntrospector.MetadataLookup<Set<Scheduled>>) (method) -> {
Set<Scheduled> scheduledAnnotations = AnnotatedElementUtils
.getMergedRepeatableAnnotations(method, Scheduled.class, Schedules.class);
return (!scheduledAnnotations.isEmpty() ? scheduledAnnotations : null);
});
if (annotatedMethods.isEmpty()) {
this.nonAnnotatedClasses.add(targetType);
}
return !annotatedMethods.isEmpty();
}
return false;
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\ScheduledBeanLazyInitializationExcludeFilter.java
| 2
|
请完成以下Java代码
|
protected Map<String, List<VariableInstance>> getSortedVariableInstances(Collection<String> variableNames, Collection<String> variableScopeIds) {
List<VariableInstance> variableInstances = queryVariablesInstancesByVariableScopeIds(variableNames, variableScopeIds);
Map<String, List<VariableInstance>> sortedVariableInstances = new HashMap<>();
for (VariableInstance variableInstance : variableInstances) {
String variableScopeId = ((VariableInstanceEntity) variableInstance).getVariableScopeId();
if (!sortedVariableInstances.containsKey(variableScopeId)) {
sortedVariableInstances.put(variableScopeId, new ArrayList<VariableInstance>());
}
sortedVariableInstances.get(variableScopeId).add(variableInstance);
}
return sortedVariableInstances;
}
protected List<VariableInstance> queryVariablesInstancesByVariableScopeIds(Collection<String> variableNames, Collection<String> variableScopeIds) {
VariableInstanceQueryImpl query = (VariableInstanceQueryImpl) getProcessEngine().getRuntimeService()
.createVariableInstanceQuery()
.disableBinaryFetching()
.disableCustomObjectDeserialization()
.variableNameIn(variableNames.toArray(new String[0]))
.variableScopeIdIn(variableScopeIds.toArray(new String[0]));
// the number of results is capped at:
// #tasks * #variableNames * 5 (we have five variable scopes per task)
// this value may exceed the configured query pagination limit, so we make an unbounded query.
// As #tasks is bounded by the pagination limit, it will never load an unbounded number of variables.
return query.unlimitedList();
}
protected boolean isEntityOfClass(Object entity, Class<?> entityClass) {
return entityClass.isAssignableFrom(entity.getClass());
}
|
protected boolean isEmptyJson(String jsonString) {
return jsonString == null || jsonString.trim().isEmpty() || EMPTY_JSON_BODY.matcher(jsonString).matches();
}
protected InvalidRequestException filterNotFound(Exception cause) {
return new InvalidRequestException(Status.NOT_FOUND, cause, "Filter with id '" + resourceId + "' does not exist.");
}
protected InvalidRequestException invalidQuery(Exception cause) {
return new InvalidRequestException(Status.BAD_REQUEST, cause, "Filter cannot be extended by an invalid query");
}
protected InvalidRequestException unsupportedEntityClass(Object entity) {
return new InvalidRequestException(Status.BAD_REQUEST, "Entities of class '" + entity.getClass().getCanonicalName() + "' are currently not supported by filters.");
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\FilterResourceImpl.java
| 1
|
请完成以下Java代码
|
public Result beforeHU(final IMutable<I_M_HU> hu)
{
huIdAndDownstream.add(HuId.ofRepoId(hu.getValue().getM_HU_ID()));
return Result.CONTINUE;
}
})
.iterate(getById(huId));
return huIdAndDownstream.build();
}
@Override
public <T> Stream<T> streamByQuery(@NonNull final IQueryBuilder<I_M_HU> queryBuilder, @NonNull final Function<I_M_HU, T> mapper)
{
return queryBuilder
.create()
.iterateAndStream()
.map(mapper);
}
@Override
public void createTUPackingInstructions(final CreateTUPackingInstructionsRequest request)
{
CreateTUPackingInstructionsCommand.builder()
.handlingUnitsDAO(this)
.request(request)
.build()
.execute();
}
@Override
public Optional<I_M_HU_PI_Item> getTUPIItemForLUPIAndItemProduct(final BPartnerId bpartnerId, final @NonNull HuPackingInstructionsId luPIId, final @NonNull HUPIItemProductId piItemProductId)
{
final I_M_HU_PI_Version luPIVersion = retrievePICurrentVersionOrNull(luPIId);
if (luPIVersion == null || !luPIVersion.isActive() || !luPIVersion.isCurrent() || !X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit.equals(luPIVersion.getHU_UnitType()))
|
{
return Optional.empty();
}
return queryBL.createQueryBuilder(I_M_HU_PI_Item_Product.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID, piItemProductId)
.andCollect(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID, I_M_HU_PI_Item.class)
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_Material)
.addInArrayFilter(I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID, bpartnerId, null)
.addOnlyActiveRecordsFilter()
.andCollect(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, I_M_HU_PI_Version.class)
.addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_HU_UnitType, X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit)
.addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_IsCurrent, true)
.addOnlyActiveRecordsFilter()
.andCollect(I_M_HU_PI_Version.COLUMNNAME_M_HU_PI_ID, I_M_HU_PI.class)
.andCollectChildren(I_M_HU_PI_Item.COLUMNNAME_Included_HU_PI_ID, I_M_HU_PI_Item.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_HandlingUnit)
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, luPIVersion.getM_HU_PI_Version_ID())
.orderBy(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID)
.create()
.firstOptional(I_M_HU_PI_Item.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsDAO.java
| 1
|
请完成以下Java代码
|
protected void dispatchExecutionCancelled(DelegateExecution execution, FlowElement terminateEndEvent) {
ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();
// subprocesses
for (DelegateExecution subExecution : executionEntityManager.findChildExecutionsByParentExecutionId(
execution.getId()
)) {
dispatchExecutionCancelled(subExecution, terminateEndEvent);
}
// call activities
ExecutionEntity subProcessInstance = Context.getCommandContext()
.getExecutionEntityManager()
.findSubProcessInstanceBySuperExecutionId(execution.getId());
if (subProcessInstance != null) {
dispatchExecutionCancelled(subProcessInstance, terminateEndEvent);
}
}
public static String createDeleteReason(String activityId) {
return activityId != null
? DeleteReason.TERMINATE_END_EVENT + ": " + activityId
: DeleteReason.TERMINATE_END_EVENT;
}
public boolean isTerminateAll() {
|
return terminateAll;
}
public void setTerminateAll(boolean terminateAll) {
this.terminateAll = terminateAll;
}
public boolean isTerminateMultiInstance() {
return terminateMultiInstance;
}
public void setTerminateMultiInstance(boolean terminateMultiInstance) {
this.terminateMultiInstance = terminateMultiInstance;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\TerminateEndEventActivityBehavior.java
| 1
|
请完成以下Java代码
|
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
public void setSKU (String SKU)
{
set_Value (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Tax Amount.
@param TaxAmt
Tax Amount for a document
*/
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Tax Indicator.
@param TaxIndicator
Short form for Tax to be printed on documents
*/
public void setTaxIndicator (String TaxIndicator)
{
|
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
/** Get Tax Indicator.
@return Short form for Tax to be printed on documents
*/
public String getTaxIndicator ()
{
return (String)get_Value(COLUMNNAME_TaxIndicator);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object createCollection() {
// 设置集合名称
String collectionName = "users1";
// 创建集合并返回集合信息
mongoTemplate.createCollection(collectionName);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建视图成功" : "创建视图失败";
}
/**
* 创建【固定大小集合】
*
* 创建集合并设置 `capped=true` 创建 `固定大小集合`,可以配置参数 `size` 限制文档大小,可以配置参数 `max` 限制集合文档数量。
*
* @return 创建集合的结果
*/
public Object createCollectionFixedSize() {
// 设置集合名称
String collectionName = "users2";
// 设置集合参数
long size = 1024L;
long max = 5L;
// 创建固定大小集合
CollectionOptions collectionOptions = CollectionOptions.empty()
// 创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。
.capped()
// 固定集合指定一个最大值,以千字节计(KB),如果 capped 为 true,也需要指定该字段。
.size(size)
// 指定固定集合中包含文档的最大数量。
.maxDocuments(max);
// 执行创建集合
mongoTemplate.createCollection(collectionName, collectionOptions);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建视图成功" : "创建视图失败";
}
/**
* 创建【验证文档数据】的集合
*
* 创建集合并在文档"插入"与"更新"时进行数据效验,如果符合创建集合设置的条件就进允许更新与插入,否则则按照设置的设置的策略进行处理。
*
* * 效验级别:
* - off:关闭数据校验。
* - strict:(默认值) 对所有的文档"插入"与"更新"操作有效。
* - moderate:仅对"插入"和满足校验规则的"文档"做"更新"操作有效。对已存在的不符合校验规则的"文档"无效。
* * 执行策略:
* - error:(默认值) 文档必须满足校验规则,才能被写入。
* - warn:对于"文档"不符合校验规则的 MongoDB 允许写入,但会记录一条告警到 mongod.log 中去。日志内容记录报错信息以及该"文档"的完整记录。
*
|
* @return 创建集合结果
*/
public Object createCollectionValidation() {
// 设置集合名称
String collectionName = "users3";
// 设置验证条件,只允许岁数大于20的用户信息插入
CriteriaDefinition criteria = Criteria.where("age").gt(20);
// 设置集合选项验证对象
CollectionOptions collectionOptions = CollectionOptions.empty()
.validator(Validator.criteria(criteria))
// 设置效验级别
.strictValidation()
// 设置效验不通过后执行的动作
.failOnValidationError();
// 执行创建集合
mongoTemplate.createCollection(collectionName, collectionOptions);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建集合成功" : "创建集合失败";
}
}
|
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\CreateCollectionService.java
| 2
|
请完成以下Java代码
|
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);
}
public I_AD_Window getPO_Window() throws RuntimeException
{
return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name)
.getPO(getPO_Window_ID(), get_TrxName()); }
/** Set PO Window.
@param PO_Window_ID
Purchase Order Window
*/
public void setPO_Window_ID (int PO_Window_ID)
{
if (PO_Window_ID < 1)
set_Value (COLUMNNAME_PO_Window_ID, null);
else
set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID));
}
/** Get PO Window.
@return Purchase Order Window
*/
public int getPO_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Query.
@param Query
SQL
*/
public void setQuery (String Query)
{
set_Value (COLUMNNAME_Query, Query);
}
|
/** Get Query.
@return SQL
*/
public String getQuery ()
{
return (String)get_Value(COLUMNNAME_Query);
}
/** Set Search Type.
@param SearchType
Which kind of search is used (Query or Table)
*/
public void setSearchType (String SearchType)
{
set_Value (COLUMNNAME_SearchType, SearchType);
}
/** Get Search Type.
@return Which kind of search is used (Query or Table)
*/
public String getSearchType ()
{
return (String)get_Value(COLUMNNAME_SearchType);
}
/** Set Transaction Code.
@param TransactionCode
The transaction code represents the search definition
*/
public void setTransactionCode (String TransactionCode)
{
set_Value (COLUMNNAME_TransactionCode, TransactionCode);
}
/** Get Transaction Code.
@return The transaction code represents the search definition
*/
public String getTransactionCode ()
{
return (String)get_Value(COLUMNNAME_TransactionCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MapPublicKeyCredentialUserEntityRepository implements PublicKeyCredentialUserEntityRepository {
private final Map<String, PublicKeyCredentialUserEntity> usernameToUserEntity = new HashMap<>();
private final Map<Bytes, PublicKeyCredentialUserEntity> idToUserEntity = new HashMap<>();
@Override
public @Nullable PublicKeyCredentialUserEntity findById(Bytes id) {
Assert.notNull(id, "id cannot be null");
return this.idToUserEntity.get(id);
}
@Override
public @Nullable PublicKeyCredentialUserEntity findByUsername(String username) {
Assert.notNull(username, "username cannot be null");
return this.usernameToUserEntity.get(username);
}
@Override
|
public void save(PublicKeyCredentialUserEntity userEntity) {
if (userEntity == null) {
throw new IllegalArgumentException("userEntity cannot be null");
}
this.usernameToUserEntity.put(userEntity.getName(), userEntity);
this.idToUserEntity.put(userEntity.getId(), userEntity);
}
@Override
public void delete(Bytes id) {
PublicKeyCredentialUserEntity existing = this.idToUserEntity.remove(id);
if (existing != null) {
this.usernameToUserEntity.remove(existing.getName());
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\MapPublicKeyCredentialUserEntityRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public ApiResponse<File> getSingleAttachmentWithHttpInfo(String apiKey, String id) throws ApiException {
com.squareup.okhttp.Call call = getSingleAttachmentValidateBeforeCall(apiKey, id, null, null);
Type localVarReturnType = new TypeToken<File>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Einzelne Anlage abrufen (asynchronously)
* Szenario - das WaWi ruft ein bestimmte Anlage als PDF ab
* @param apiKey (required)
* @param id (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getSingleAttachmentAsync(String apiKey, String id, final ApiCallback<File> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
|
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getSingleAttachmentValidateBeforeCall(apiKey, id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<File>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\api\AttachmentApi.java
| 2
|
请完成以下Java代码
|
public <D> Mono<D> toEntity(Class<D> entityType) {
return this.responseMono.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
@Override
public <D> Mono<D> toEntity(ParameterizedTypeReference<D> entityType) {
return this.responseMono.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@Override
public <D> Mono<List<D>> toEntityList(Class<D> elementType) {
return this.responseMono.map((response) -> {
ClientResponseField field = getValidField(response);
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
@Override
public <D> Mono<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) {
return this.responseMono.map((response) -> {
ClientResponseField field = getValidField(response);
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
}
private static class DefaultRetrieveSubscriptionSpec extends RetrieveSpecSupport implements RetrieveSubscriptionSpec {
private final Flux<ClientGraphQlResponse> responseFlux;
DefaultRetrieveSubscriptionSpec(Flux<ClientGraphQlResponse> responseFlux, String path) {
super(path);
this.responseFlux = responseFlux;
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
@Override
|
public <D> Flux<D> toEntity(Class<D> entityType) {
return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
@Override
public <D> Flux<D> toEntity(ParameterizedTypeReference<D> entityType) {
return this.responseFlux.mapNotNull(this::getValidField).mapNotNull((field) -> field.toEntity(entityType));
}
@Override
public <D> Flux<List<D>> toEntityList(Class<D> elementType) {
return this.responseFlux.map((response) -> {
ClientResponseField field = getValidField(response);
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
@Override
public <D> Flux<List<D>> toEntityList(ParameterizedTypeReference<D> elementType) {
return this.responseFlux.map((response) -> {
ClientResponseField field = getValidField(response);
return (field != null) ? field.toEntityList(elementType) : Collections.emptyList();
});
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultGraphQlClient.java
| 1
|
请完成以下Java代码
|
public Optional<OrderLineId> getOrderLineIdByReservedVhuId(@NonNull final HuId vhuId)
{
return getEntryByVhuId(vhuId)
.map(entry -> entry.getDocumentRef().getSalesOrderLineId());
}
private Optional<HUReservationEntry> getEntryByVhuId(@NonNull final HuId vhuId)
{
return entriesByVhuId.getOrLoad(vhuId, this::retrieveEntryByVhuId);
}
private Optional<HUReservationEntry> retrieveEntryByVhuId(@NonNull final HuId vhuId)
{
return queryBL.createQueryBuilder(I_M_HU_Reservation.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuId) // we have a UC constraint on VHU_ID
.create()
.firstOnlyOptional(I_M_HU_Reservation.class)
.map(HUReservationRepository::toHUReservationEntry);
}
private static HUReservationDocRef extractDocumentRef(@NonNull final I_M_HU_Reservation record)
{
return HUReservationDocRef.builder()
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLineSO_ID()))
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.pickingJobStepId(PickingJobStepId.ofRepoIdOrNull(record.getM_Picking_Job_Step_ID()))
.ddOrderLineId(DDOrderLineId.ofRepoIdOrNull(record.getDD_OrderLine_ID()))
.build();
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> onlyVHUIds)
{
if (from.size() == 1 && Objects.equals(from.iterator().next(), to))
{
|
return;
}
final List<I_M_HU_Reservation> records = retrieveRecordsByDocumentRef(from, onlyVHUIds);
if (records.isEmpty())
{
return;
}
for (final I_M_HU_Reservation record : records)
{
updateRecordFromDocumentRef(record, to);
saveRecord(record);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationRepository.java
| 1
|
请完成以下Java代码
|
public JSONAddressDocument createAddressDocument(@RequestBody final JSONCreateAddressRequest request)
{
userSession.assertLoggedIn();
return Execution.callInNewExecution("createAddressDocument", () -> {
final Document addressDoc = addressRepo.createNewFrom(LocationId.ofRepoIdOrNull(request.getTemplateId()));
return toJson(addressDoc);
});
}
private JSONAddressDocument toJson(final Document addressDoc)
{
return JSONAddressDocument.builder()
.id(addressDoc.getDocumentId())
.layout(JSONAddressLayout.of(addressRepo.getLayout(), newJsonDocumentLayoutOpts()))
.fieldsByName(JSONDocument.ofDocument(addressDoc, newJsonDocumentOpts()).getFieldsByName())
.build();
}
@GetMapping("/{docId}")
public JSONAddressDocument getAddressDocument(@PathVariable("docId") final int docId)
{
userSession.assertLoggedIn();
final Document addressDoc = addressRepo.getAddressDocumentForReading(docId);
return toJson(addressDoc);
}
@PatchMapping("/{docId}")
public List<JSONDocument> processChanges(
@PathVariable("docId") final int docId,
@RequestBody final List<JSONDocumentChangedEvent> events)
{
userSession.assertLoggedIn();
return Execution.callInNewExecution("processChanges", () -> {
final IDocumentChangesCollector changesCollector = Execution.getCurrentDocumentChangesCollectorOrNull();
addressRepo.processAddressDocumentChanges(docId, events, changesCollector);
return JSONDocument.ofEvents(changesCollector, newJsonDocumentOpts());
});
}
@GetMapping("/{docId}/field/{attributeName}/typeahead")
|
public JSONLookupValuesPage getAttributeTypeahead(
@PathVariable("docId") final int docId,
@PathVariable("attributeName") final String attributeName,
@RequestParam(name = "query") final String query)
{
userSession.assertLoggedIn();
return addressRepo.getAddressDocumentForReading(docId)
.getFieldLookupValuesForQuery(attributeName, query)
.transform(page -> JSONLookupValuesPage.of(page, userSession.getAD_Language()));
}
@GetMapping("/{docId}/field/{attributeName}/dropdown")
public JSONLookupValuesList getAttributeDropdown(
@PathVariable("docId") final int docId,
@PathVariable("attributeName") final String attributeName)
{
userSession.assertLoggedIn();
return addressRepo.getAddressDocumentForReading(docId)
.getFieldLookupValues(attributeName)
.transform(list -> JSONLookupValuesList.ofLookupValuesList(list, userSession.getAD_Language()));
}
@PostMapping("/{docId}/complete")
public JSONLookupValue complete(
@PathVariable("docId") final int docId,
@RequestBody final JSONCompleteASIRequest request)
{
userSession.assertLoggedIn();
return Execution.callInNewExecution(
"complete",
() -> addressRepo.complete(docId, request.getEvents())
.transform(lookupValue -> JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language())));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRestController.java
| 1
|
请完成以下Java代码
|
public String getSpecialty() {
return specialty;
}
/**
* Sets the value of the specialty property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialty(String value) {
this.specialty = value;
}
/**
* Gets the value of the uidNumber property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getUidNumber() {
return uidNumber;
}
/**
* Sets the value of the uidNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUidNumber(String value) {
this.uidNumber = 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\BillerAddressType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addParameter(String key, String value){
this.parameters.put(key, value);
}
public void addParameters(String key, Collection<String> values){
this.parameters.put(key, values);
}
public void setParameters(Map _parameters) {
this.parameters.putAll(_parameters);
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getCharSet() {
return charSet;
}
public void setCharSet(String charSet) {
this.charSet = charSet;
}
public boolean isSslVerify() {
return sslVerify;
}
public void setSslVerify(boolean sslVerify) {
this.sslVerify = sslVerify;
}
public int getMaxResultSize() {
return maxResultSize;
}
public void setMaxResultSize(int maxResultSize) {
this.maxResultSize = maxResultSize;
}
public Map getHeaders() {
return headers;
}
public void addHeader(String key, String value){
this.headers.put(key, value);
}
public void addHeaders(String key, Collection<String> values){
this.headers.put(key, values);
}
public void setHeaders(Map _headers) {
this.headers.putAll(_headers);
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
|
}
public boolean isIgnoreContentIfUnsuccess() {
return ignoreContentIfUnsuccess;
}
public void setIgnoreContentIfUnsuccess(boolean ignoreContentIfUnsuccess) {
this.ignoreContentIfUnsuccess = ignoreContentIfUnsuccess;
}
public String getPostData() {
return postData;
}
public void setPostData(String postData) {
this.postData = postData;
}
public ClientKeyStore getClientKeyStore() {
return clientKeyStore;
}
public void setClientKeyStore(ClientKeyStore clientKeyStore) {
this.clientKeyStore = clientKeyStore;
}
public com.roncoo.pay.trade.utils.httpclient.TrustKeyStore getTrustKeyStore() {
return TrustKeyStore;
}
public void setTrustKeyStore(com.roncoo.pay.trade.utils.httpclient.TrustKeyStore trustKeyStore) {
TrustKeyStore = trustKeyStore;
}
public boolean isHostnameVerify() {
return hostnameVerify;
}
public void setHostnameVerify(boolean hostnameVerify) {
this.hostnameVerify = hostnameVerify;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpParam.java
| 2
|
请完成以下Java代码
|
public String getF_INFOMOBIL() {
return F_INFOMOBIL;
}
public void setF_INFOMOBIL(String f_INFOMOBIL) {
F_INFOMOBIL = f_INFOMOBIL;
}
public String getF_INFOMAN() {
return F_INFOMAN;
}
public void setF_INFOMAN(String f_INFOMAN) {
F_INFOMAN = f_INFOMAN;
}
public String getF_LOGPASS() {
return F_LOGPASS;
}
public void setF_LOGPASS(String f_LOGPASS) {
F_LOGPASS = f_LOGPASS;
}
public String getF_STARTDATE() {
return F_STARTDATE;
}
public void setF_STARTDATE(String f_STARTDATE) {
F_STARTDATE = f_STARTDATE;
}
public String getF_STOPDATE() {
return F_STOPDATE;
}
public void setF_STOPDATE(String f_STOPDATE) {
F_STOPDATE = f_STOPDATE;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_AUDITER() {
return F_AUDITER;
|
}
public void setF_AUDITER(String f_AUDITER) {
F_AUDITER = f_AUDITER;
}
public String getF_AUDITTIME() {
return F_AUDITTIME;
}
public void setF_AUDITTIME(String f_AUDITTIME) {
F_AUDITTIME = f_AUDITTIME;
}
public String getF_ISAUDIT() {
return F_ISAUDIT;
}
public void setF_ISAUDIT(String f_ISAUDIT) {
F_ISAUDIT = f_ISAUDIT;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public Integer getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISPRINTBILL() {
return F_ISPRINTBILL;
}
public void setF_ISPRINTBILL(String f_ISPRINTBILL) {
F_ISPRINTBILL = f_ISPRINTBILL;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VersionProperties {
/** The defaultVersion. */
private String defaultVersion;
/**
* Flag whether to use API versions that appear in mappings for supported version
* validation (true), or use only explicitly configured versions (false). Defaults to
* true.
*/
private boolean detectSupportedVersions = true;
/** The header name used to extract the API Version. */
private String headerName;
/** The media type name used to extract the API Version. */
private MediaType mediaType;
/** The media type parameter name used to extract the API Version. */
private String mediaTypeParamName;
/** The index of a path segment used to extract the API Version. */
private Integer pathSegment;
/** The request parameter name used to extract the API Version. */
private String requestParamName;
private boolean required;
private List<String> supportedVersions = new ArrayList<>();
public String getDefaultVersion() {
return defaultVersion;
}
public void setDefaultVersion(String defaultVersion) {
this.defaultVersion = defaultVersion;
}
public boolean isDetectSupportedVersions() {
return detectSupportedVersions;
}
public void setDetectSupportedVersions(boolean detectSupportedVersions) {
this.detectSupportedVersions = detectSupportedVersions;
}
public String getHeaderName() {
return headerName;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public MediaType getMediaType() {
return mediaType;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public String getMediaTypeParamName() {
return mediaTypeParamName;
}
public void setMediaTypeParamName(String mediaTypeParamName) {
this.mediaTypeParamName = mediaTypeParamName;
}
public Integer getPathSegment() {
return pathSegment;
}
public void setPathSegment(Integer pathSegment) {
this.pathSegment = pathSegment;
}
public String getRequestParamName() {
|
return requestParamName;
}
public void setRequestParamName(String requestParamName) {
this.requestParamName = requestParamName;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<String> getSupportedVersions() {
return supportedVersions;
}
public void setSupportedVersions(List<String> supportedVersions) {
this.supportedVersions = supportedVersions;
}
@Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("defaultVersion", defaultVersion)
.append("detectSupportedVersions", detectSupportedVersions)
.append("headerName", headerName)
.append("mediaType", mediaType)
.append("mediaTypeParamName", mediaTypeParamName)
.append("pathSegment", pathSegment)
.append("requestParamName", requestParamName)
.append("required", required)
.append("supportedVersions", supportedVersions)
.toString();
// @formatter:on
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\VersionProperties.java
| 2
|
请完成以下Java代码
|
void demo() {
undefined_operations_produce_NaN();
operations_with_no_real_results_produce_NaN();
operations_with_NaN_produce_NaN();
comparison_with_NaN();
check_if_a_value_is_NaN();
assign_NaN_to_missing_values();
}
void undefined_operations_produce_NaN() {
System.out.println("Undefined Operations Produce NaN");
final double ZERO = 0;
System.out.println("ZERO / ZERO = " + (ZERO / ZERO));
System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY));
System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO));
System.out.println();
}
void operations_with_no_real_results_produce_NaN() {
System.out.println("Operations with no real results produce NaN");
System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1));
System.out.println("LOG OF -1 = " + Math.log(-1));
System.out.println();
}
void operations_with_NaN_produce_NaN() {
System.out.println("Operations with NaN produce NaN");
System.out.println("2 + NaN = " + (2 + Double.NaN));
System.out.println("2 - NaN = " + (2 - Double.NaN));
System.out.println("2 * NaN = " + (2 * Double.NaN));
System.out.println("2 / NaN = " + (2 / Double.NaN));
System.out.println();
}
void assign_NaN_to_missing_values() {
|
System.out.println("Assign NaN to Missing values");
double salaryRequired = Double.NaN;
System.out.println(salaryRequired);
System.out.println();
}
void comparison_with_NaN() {
System.out.println("Comparison with NaN");
final double NAN = Double.NaN;
System.out.println("NaN == 1 = " + (NAN == 1));
System.out.println("NaN > 1 = " + (NAN > 1));
System.out.println("NaN < 1 = " + (NAN < 1));
System.out.println("NaN != 1 = " + (NAN != 1));
System.out.println("NaN == NaN = " + (NAN == NAN));
System.out.println("NaN > NaN = " + (NAN > NAN));
System.out.println("NaN < NaN = " + (NAN < NAN));
System.out.println("NaN != NaN = " + (NAN != NAN));
System.out.println();
}
void check_if_a_value_is_NaN() {
System.out.println("Check if a value is NaN");
double x = 1;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
x = Double.NaN;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
System.out.println();
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\nan\NaNExample.java
| 1
|
请完成以下Java代码
|
private Optional<I_C_Order> getOrderIdFromIdentifier(final IdentifierString orderIdentifier, final OrgId orgId)
{
return orderDAO.retrieveByOrderCriteria(createOrderQuery(orderIdentifier, orgId));
}
private OrderQuery createOrderQuery(final IdentifierString identifierString, final OrgId orgId)
{
final IdentifierString.Type type = identifierString.getType();
final OrderQuery.OrderQueryBuilder builder = OrderQuery.builder().orgId(orgId);
if (IdentifierString.Type.METASFRESH_ID.equals(type))
{
return builder
.orderId(MetasfreshId.toValue(identifierString.asMetasfreshId()))
.build();
}
else if (IdentifierString.Type.EXTERNAL_ID.equals(type))
{
|
return builder
.externalId(identifierString.asExternalId())
.build();
}
else if (IdentifierString.Type.DOC.equals(type))
{
return builder
.documentNo(identifierString.asDoc())
.build();
}
else
{
throw new AdempiereException("Invalid identifierString: " + identifierString);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\payment\JsonPaymentService.java
| 1
|
请完成以下Java代码
|
public boolean hasNext()
{
try
{
boolean next = in.available() > 0;
if (!next) in.close();
return next;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public Document next()
{
try
{
|
return new Document(in);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
};
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\FileDataSet.java
| 1
|
请完成以下Java代码
|
public class SecureScriptContext extends Context {
private long startTime;
private long threadId;
private long startMemory;
protected SecureScriptContext(ContextFactory factory) {
super(factory);
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getThreadId() {
|
return threadId;
}
public void setThreadId(long threadId) {
this.threadId = threadId;
}
public long getStartMemory() {
return startMemory;
}
public void setStartMemory(long startMemory) {
this.startMemory = startMemory;
}
}
|
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\impl\SecureScriptContext.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
validateInput();
ExternalTaskEntity externalTask = commandContext.getExternalTaskManager().findExternalTaskById(externalTaskId);
EnsureUtil.ensureNotNull(NotFoundException.class,
"Cannot find external task with id " + externalTaskId, "externalTask", externalTask);
if (validateWorkerViolation(externalTask)) {
throw new BadUserRequestException(getErrorMessageOnWrongWorkerAccess() + "'. It is locked by worker '" + externalTask.getWorkerId() + "'.");
}
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateProcessInstanceById(externalTask.getProcessInstanceId());
}
try {
execute(externalTask);
} catch (NotFoundException e) {
// wrap up NotFoundExceptions reported for entities different than external tasks
throw new ProcessEngineException(e.getMessage(), e);
}
return null;
}
/**
* Returns the error message. Which is used to create an specific message
* for the BadUserRequestException if an worker has no rights to execute commands of the external task.
*
* @return the specific error message
*/
public abstract String getErrorMessageOnWrongWorkerAccess();
|
/**
* Validates the current input of the command.
*/
@Override
protected void validateInput() {
EnsureUtil.ensureNotNull("workerId", workerId);
}
/**
* Validates the caller's workerId against the workerId of the external task.
*/
protected boolean validateWorkerViolation(ExternalTaskEntity externalTask) {
return !workerId.equals(externalTask.getWorkerId());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\HandleExternalTaskCmd.java
| 1
|
请完成以下Java代码
|
public class TransitionInstanceImpl extends ProcessElementInstanceImpl implements TransitionInstance {
protected String executionId;
protected String activityId;
protected String activityName;
protected String activityType;
protected String subProcessInstanceId;
protected String[] incidentIds = NO_IDS;
protected Incident[] incidents = new Incident[0];
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getTargetActivityId() {
return activityId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
@Override
public String[] getIncidentIds() {
return incidentIds;
}
public void setIncidentIds(String[] incidentIds) {
this.incidentIds = incidentIds;
}
@Override
public Incident[] getIncidents() {
return incidents;
}
|
public void setIncidents(Incident[] incidents) {
this.incidents = incidents;
}
public void setSubProcessInstanceId(String subProcessInstanceId) {
this.subProcessInstanceId = subProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public String toString() {
return this.getClass().getSimpleName()
+ "[executionId=" + executionId
+ ", targetActivityId=" + activityId
+ ", activityName=" + activityName
+ ", activityType=" + activityType
+ ", id=" + id
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ ", incidentIds=" + Arrays.toString(incidentIds)
+ ", incidents=" + Arrays.toString(incidents)
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TransitionInstanceImpl.java
| 1
|
请完成以下Java代码
|
public IReplRequestHandlerResult handleRequest(final PO po, IReplRequestHandlerCtx ctx)
{
final Properties ctxToUse = ctx.getEnvCtxToUse();
if (!Util.same(po.getCtx(), ctxToUse))
{
// this shall not happen, it's an internal error
throw new ReplicationException("PO does not have same context as we need it to use")
.setParameter("PO", po)
.setParameter("Ctx", po.getCtx())
.setParameter("CtxToUse", ctxToUse);
// Alternative: reload the given PO with 'ctxToUse' and therefore see if the current role really has access
// final PO poToSend = MTable.get(ctxToUse, po.get_Table_ID()).getPO(po.get_ID(), po.get_TrxName());
}
final IReplRequestHandlerResult result = Services.get(IReplRequestHandlerBL.class).createInitialRequestHandlerResult();
final IUserRolePermissions role = Env.getUserRolePermissions(ctxToUse);
final boolean allowResponse = role.canUpdate(
ClientId.ofRepoId(po.getAD_Client_ID()),
OrgId.ofRepoId(po.getAD_Org_ID()),
po.get_Table_ID(),
po.get_ID(),
false // createError
);
if (!allowResponse)
{
logger.warn("Response not allowed because there is no access to '{}'", po);
|
return result;
}
final PO poToSend = createResponse(ctx, po);
result.setPOToExport(poToSend);
return result;
}
protected PO createResponse(IReplRequestHandlerCtx ctx, PO requestPO)
{
final PO responsePO = requestPO;
return responsePO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\spi\impl\LoadPORequestHandler.java
| 1
|
请完成以下Java代码
|
private static ThreadPoolTaskScheduler registrationTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(1);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("registrationTask");
return taskScheduler;
}
RegistrationApplicationListener(ApplicationRegistrator registrator, ThreadPoolTaskScheduler taskScheduler) {
this.registrator = registrator;
this.taskScheduler = taskScheduler;
}
@EventListener
@Order(Ordered.LOWEST_PRECEDENCE)
public void onApplicationReady(ApplicationReadyEvent event) {
if (autoRegister) {
startRegisterTask();
}
}
@EventListener
@Order(Ordered.LOWEST_PRECEDENCE)
public void onClosedContext(ContextClosedEvent event) {
if (event.getApplicationContext().getParent() == null
|| "bootstrap".equals(event.getApplicationContext().getParent().getId())) {
stopRegisterTask();
if (autoDeregister) {
registrator.deregister();
}
}
}
public void startRegisterTask() {
if (scheduledTask != null && !scheduledTask.isDone()) {
return;
}
scheduledTask = taskScheduler.scheduleAtFixedRate(registrator::register, registerPeriod);
LOGGER.debug("Scheduled registration task for every {}ms", registerPeriod.toMillis());
}
|
public void stopRegisterTask() {
if (scheduledTask != null && !scheduledTask.isDone()) {
scheduledTask.cancel(true);
LOGGER.debug("Canceled registration task");
}
}
public void setAutoDeregister(boolean autoDeregister) {
this.autoDeregister = autoDeregister;
}
public void setAutoRegister(boolean autoRegister) {
this.autoRegister = autoRegister;
}
public void setRegisterPeriod(Duration registerPeriod) {
this.registerPeriod = registerPeriod;
}
@Override
public void afterPropertiesSet() {
taskScheduler.afterPropertiesSet();
}
@Override
public void destroy() {
taskScheduler.destroy();
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\RegistrationApplicationListener.java
| 1
|
请完成以下Java代码
|
public void setDataInputRefs(List<String> dataInputRefs) {
this.dataInputRefs = dataInputRefs;
}
public List<String> getDataOutputRefs() {
return dataOutputRefs;
}
public void setDataOutputRefs(List<String> dataOutputRefs) {
this.dataOutputRefs = dataOutputRefs;
}
@Override
public IOSpecification clone() {
IOSpecification clone = new IOSpecification();
clone.setValues(this);
return clone;
}
public void setValues(IOSpecification otherSpec) {
super.setValues(otherSpec);
dataInputs = new ArrayList<>();
|
if (otherSpec.getDataInputs() != null && !otherSpec.getDataInputs().isEmpty()) {
for (DataSpec dataSpec : otherSpec.getDataInputs()) {
dataInputs.add(dataSpec.clone());
}
}
dataOutputs = new ArrayList<>();
if (otherSpec.getDataOutputs() != null && !otherSpec.getDataOutputs().isEmpty()) {
for (DataSpec dataSpec : otherSpec.getDataOutputs()) {
dataOutputs.add(dataSpec.clone());
}
}
dataInputRefs = new ArrayList<>(otherSpec.getDataInputRefs());
dataOutputRefs = new ArrayList<>(otherSpec.getDataOutputRefs());
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\IOSpecification.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object visitPrimitiveAsShort(PrimitiveType type, Void parameter) {
return (short) 0;
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, Void parameter) {
return 0;
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, Void parameter) {
return 0L;
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, Void parameter) {
return null;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, Void parameter) {
return 0F;
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, Void parameter) {
return 0D;
}
}
/**
* Visitor that gets the default using coercion.
*/
private static final class DefaultValueCoercionTypeVisitor extends TypeKindVisitor8<Object, String> {
static final DefaultValueCoercionTypeVisitor INSTANCE = new DefaultValueCoercionTypeVisitor();
private <T extends Number> T parseNumber(String value, Function<String, T> parser,
PrimitiveType primitiveType) {
try {
return parser.apply(value);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(
String.format("Invalid %s representation '%s'", primitiveType, value));
}
}
@Override
public Object visitPrimitiveAsBoolean(PrimitiveType type, String value) {
return Boolean.parseBoolean(value);
}
@Override
public Object visitPrimitiveAsByte(PrimitiveType type, String value) {
|
return parseNumber(value, Byte::parseByte, type);
}
@Override
public Object visitPrimitiveAsShort(PrimitiveType type, String value) {
return parseNumber(value, Short::parseShort, type);
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, String value) {
return parseNumber(value, Integer::parseInt, type);
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, String value) {
return parseNumber(value, Long::parseLong, type);
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, String value) {
if (value.length() > 1) {
throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value));
}
return value;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, String value) {
return parseNumber(value, Float::parseFloat, type);
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, String value) {
return parseNumber(value, Double::parseDouble, type);
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ParameterPropertyDescriptor.java
| 2
|
请完成以下Java代码
|
public String getParentActivityInstanceId() {
return parentActivityInstanceId;
}
/** the id of the activity */
public String getActivityId() {
return activityId;
}
/** type of the activity, corresponds to BPMN element name in XML (e.g. 'userTask') */
public String getActivityType() {
return activityType;
}
/** the process instance id */
public String getProcessInstanceId() {
return processInstanceId;
}
/** the process definition id */
public String getProcessDefinitionId() {
return processDefinitionId;
}
/** Returns the child activity instances.
* Returns an empty list if there are no child instances. */
public ActivityInstanceDto[] getChildActivityInstances() {
return childActivityInstances;
}
public TransitionInstanceDto[] getChildTransitionInstances() {
return childTransitionInstances;
}
/** the list of executions that are currently waiting in this activity instance */
public String[] getExecutionIds() {
return executionIds;
}
/** the activity name */
public String getActivityName() {
return activityName;
}
/**
* deprecated; the JSON field with this name was never documented, but existed
* from 7.0 to 7.2
*/
public String getName() {
return activityName;
}
public String[] getIncidentIds() {
return incidentIds;
}
|
public ActivityInstanceIncidentDto[] getIncidents() {
return incidents;
}
public static ActivityInstanceDto fromActivityInstance(ActivityInstance instance) {
ActivityInstanceDto result = new ActivityInstanceDto();
result.id = instance.getId();
result.parentActivityInstanceId = instance.getParentActivityInstanceId();
result.activityId = instance.getActivityId();
result.activityType = instance.getActivityType();
result.processInstanceId = instance.getProcessInstanceId();
result.processDefinitionId = instance.getProcessDefinitionId();
result.childActivityInstances = fromListOfActivityInstance(instance.getChildActivityInstances());
result.childTransitionInstances = TransitionInstanceDto.fromListOfTransitionInstance(instance.getChildTransitionInstances());
result.executionIds = instance.getExecutionIds();
result.activityName = instance.getActivityName();
result.incidentIds = instance.getIncidentIds();
result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents());
return result;
}
public static ActivityInstanceDto[] fromListOfActivityInstance(ActivityInstance[] instances) {
ActivityInstanceDto[] result = new ActivityInstanceDto[instances.length];
for (int i = 0; i < result.length; i++) {
result[i] = fromActivityInstance(instances[i]);
}
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ActivityInstanceDto.java
| 1
|
请完成以下Java代码
|
private void addExceptionDetails(Throwable t, ServerWebExchange exchange) {
if (t != null) {
exchange.getAttributes().put(CIRCUITBREAKER_EXECUTION_EXCEPTION_ATTR, t);
}
}
@Override
public String name() {
return NAME;
}
public static class Config implements HasRouteId {
private @Nullable String name;
private @Nullable URI fallbackUri;
private @Nullable String routeId;
private Set<String> statusCodes = new HashSet<>();
private boolean resumeWithoutError = false;
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public @Nullable String getRouteId() {
return routeId;
}
public @Nullable URI getFallbackUri() {
return fallbackUri;
}
public Config setFallbackUri(URI fallbackUri) {
this.fallbackUri = fallbackUri;
return this;
}
public Config setFallbackUri(String fallbackUri) {
return setFallbackUri(URI.create(fallbackUri));
}
public @Nullable String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
|
return this;
}
public @Nullable String getId() {
if (!StringUtils.hasText(name) && StringUtils.hasText(routeId)) {
return routeId;
}
return name;
}
public Set<String> getStatusCodes() {
return statusCodes;
}
public Config setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public Config addStatusCode(String statusCode) {
this.statusCodes.add(statusCode);
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError;
}
public void setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
}
}
public class CircuitBreakerStatusCodeException extends HttpStatusCodeException {
public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SpringCloudCircuitBreakerFilterFactory.java
| 1
|
请完成以下Java代码
|
public class FirstOrderHiddenMarkovModel extends HiddenMarkovModel
{
/**
* 创建空白的隐马尔可夫模型以供训练
*/
public FirstOrderHiddenMarkovModel()
{
this(null, null, null);
}
public FirstOrderHiddenMarkovModel(float[] start_probability, float[][] transition_probability, float[][] emission_probability)
{
super(start_probability, transition_probability, emission_probability);
toLog();
}
@Override
public int[][] generate(int length)
{
double[] pi = logToCdf(start_probability);
double[][] A = logToCdf(transition_probability);
double[][] B = logToCdf(emission_probability);
int xy[][] = new int[2][length];
xy[1][0] = drawFrom(pi); // 采样首个隐状态
xy[0][0] = drawFrom(B[xy[1][0]]); // 根据首个隐状态采样它的显状态
for (int t = 1; t < length; t++)
{
xy[1][t] = drawFrom(A[xy[1][t - 1]]);
xy[0][t] = drawFrom(B[xy[1][t]]);
}
return xy;
}
@Override
public float predict(int[] observation, int[] state)
{
final int time = observation.length; // 序列长度
final int max_s = start_probability.length; // 状态种数
float[] score = new float[max_s];
// link[t][s] := 第t个时刻在当前状态是s时,前1个状态是什么
int[][] link = new int[time][max_s];
// 第一个时刻,使用初始概率向量乘以发射概率矩阵
for (int cur_s = 0; cur_s < max_s; ++cur_s)
{
score[cur_s] = start_probability[cur_s] + emission_probability[cur_s][observation[0]];
}
// 第二个时刻,使用前一个时刻的概率向量乘以一阶转移矩阵乘以发射概率矩阵
float[] pre = new float[max_s];
for (int t = 1; t < observation.length; t++)
{
// swap(now, pre)
float[] buffer = pre;
pre = score;
|
score = buffer;
// end of swap
for (int s = 0; s < max_s; ++s)
{
score[s] = Integer.MIN_VALUE;
for (int f = 0; f < max_s; ++f)
{
float p = pre[f] + transition_probability[f][s] + emission_probability[s][observation[t]];
if (p > score[s])
{
score[s] = p;
link[t][s] = f;
}
}
}
}
float max_score = Integer.MIN_VALUE;
int best_s = 0;
for (int s = 0; s < max_s; s++)
{
if (score[s] > max_score)
{
max_score = score[s];
best_s = s;
}
}
for (int t = link.length - 1; t >= 0; --t)
{
state[t] = best_s;
best_s = link[t][best_s];
}
return max_score;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\FirstOrderHiddenMarkovModel.java
| 1
|
请完成以下Java代码
|
public void updateBeforeDisplaying()
{
// nothing
}
protected final AnnotatedTableModel<?> getTableModelOrNull()
{
final JTable table = getTable();
if (table == null)
{
return null;
}
final TableModel tableModel = table.getModel();
if (tableModel instanceof AnnotatedTableModel<?>)
{
return (AnnotatedTableModel<?>)tableModel;
}
|
return null;
}
protected final ListSelectionModel getSelectionModelOrNull()
{
final JTable table = getTable();
if (table == null)
{
return null;
}
final ListSelectionModel selectionModel = table.getSelectionModel();
return selectionModel;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableAction.java
| 1
|
请完成以下Java代码
|
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Notification Group.
@param AD_User_NotificationGroup_ID User Notification Group */
@Override
public void setAD_User_NotificationGroup_ID (int AD_User_NotificationGroup_ID)
{
if (AD_User_NotificationGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_NotificationGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_NotificationGroup_ID, Integer.valueOf(AD_User_NotificationGroup_ID));
}
/** Get User Notification Group.
@return User Notification Group */
@Override
public int getAD_User_NotificationGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_NotificationGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* NotificationType AD_Reference_ID=344
* Reference name: AD_User NotificationType
|
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=344;
/** EMail = E */
public static final String NOTIFICATIONTYPE_EMail = "E";
/** Notice = N */
public static final String NOTIFICATIONTYPE_Notice = "N";
/** None = X */
public static final String NOTIFICATIONTYPE_None = "X";
/** EMailPlusNotice = B */
public static final String NOTIFICATIONTYPE_EMailPlusNotice = "B";
/** NotifyUserInCharge = O */
public static final String NOTIFICATIONTYPE_NotifyUserInCharge = "O";
/** Set Benachrichtigungs-Art.
@param NotificationType
Art der Benachrichtigung
*/
@Override
public void setNotificationType (java.lang.String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
/** Get Benachrichtigungs-Art.
@return Art der Benachrichtigung
*/
@Override
public java.lang.String getNotificationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_NotificationType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_NotificationGroup.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AddQtyToProjectTaskRequest
{
@NonNull ServiceRepairProjectTaskId taskId;
@NonNull ProductId productId;
@NonNull Quantity qtyReserved;
@NonNull Quantity qtyConsumed;
@Builder(toBuilder = true)
private AddQtyToProjectTaskRequest(
@NonNull final ServiceRepairProjectTaskId taskId,
@NonNull final ProductId productId,
@Nullable final Quantity qtyReserved,
@Nullable final Quantity qtyConsumed)
{
final Quantity firstQtyNotNull = CoalesceUtil.coalesce(qtyReserved, qtyConsumed);
if (firstQtyNotNull == null)
{
throw new AdempiereException("At least one qty shall be specified");
}
Quantity.getCommonUomIdOfAll(qtyReserved, qtyConsumed); // assume same UOM
this.taskId = taskId;
|
this.productId = productId;
this.qtyReserved = qtyReserved != null ? qtyReserved : firstQtyNotNull.toZero();
this.qtyConsumed = qtyConsumed != null ? qtyConsumed : firstQtyNotNull.toZero();
}
public UomId getUomId()
{
return Quantity.getCommonUomIdOfAll(qtyReserved, qtyConsumed);
}
public AddQtyToProjectTaskRequest negate()
{
return toBuilder()
.qtyReserved(qtyReserved.negate())
.qtyConsumed(qtyConsumed.negate())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\requests\AddQtyToProjectTaskRequest.java
| 2
|
请完成以下Java代码
|
public class ReplicationException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = 8608172237424907859L;
private final String adMessage;
private final Throwable cause;
/**
* Constructs a new exception with the specified detail message.
*
* @param adMessage the detail message.
*/
public ReplicationException(final String adMessage)
{
super("@" + adMessage + "@");
this.adMessage = adMessage;
cause = null;
}
/**
* Constructs a new exception with the specified detail message and cause.
*/
public ReplicationException(final String adMessage, final Throwable cause)
{
super("@" + adMessage + "@", cause);
this.adMessage = adMessage;
this.cause = cause;
}
|
@Override
protected ITranslatableString buildMessage()
{
final TranslatableStringBuilder message = TranslatableStrings.builder();
if(Check.isNotBlank(adMessage)) // avoide NPE
{
message.appendADMessage(adMessage);
appendParameters(message);
}
if (cause != null)
{
message.append("\nCause: ").append(AdempiereException.extractMessage(cause));
}
return message.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\exceptions\ReplicationException.java
| 1
|
请完成以下Java代码
|
private ProjectAssetGenerator<byte[]> generateBuild(R request) {
return (context) -> {
byte[] content = generateBuild(context);
publishProjectGeneratedEvent(request, context);
return content;
};
}
/**
* Create a file in the same directory as the given directory using the directory name
* and extension.
* @param dir the directory used to determine the path and name of the new file
* @param extension the extension to use for the new file
* @return the newly created file
*/
public Path createDistributionFile(Path dir, String extension) {
Path download = dir.resolveSibling(dir.getFileName() + extension);
addTempFile(dir, download);
return download;
}
private void addTempFile(Path group, Path file) {
this.temporaryFiles.compute(group, (path, paths) -> {
List<Path> newPaths = (paths != null) ? paths : new ArrayList<>();
newPaths.add(file);
return newPaths;
});
}
/**
* Clean all the temporary files that are related to this root directory.
* @param dir the directory to clean
* @see #createDistributionFile
*/
public void cleanTempFiles(Path dir) {
List<Path> tempFiles = this.temporaryFiles.remove(dir);
if (!tempFiles.isEmpty()) {
tempFiles.forEach((path) -> {
try {
FileSystemUtils.deleteRecursively(path);
}
catch (IOException ex) {
// Continue
}
});
}
}
private byte[] generateBuild(ProjectGenerationContext context) throws IOException {
ProjectDescription description = context.getBean(ProjectDescription.class);
StringWriter out = new StringWriter();
BuildWriter buildWriter = context.getBeanProvider(BuildWriter.class).getIfAvailable();
if (buildWriter != null) {
|
buildWriter.writeBuild(out);
return out.toString().getBytes();
}
else {
throw new IllegalStateException("No BuildWriter implementation found for " + description.getLanguage());
}
}
private void customizeProjectGenerationContext(AnnotationConfigApplicationContext context,
InitializrMetadata metadata) {
context.setParent(this.parentApplicationContext);
context.registerBean(InitializrMetadata.class, () -> metadata);
context.registerBean(BuildItemResolver.class, () -> new MetadataBuildItemResolver(metadata,
context.getBean(ProjectDescription.class).getPlatformVersion()));
context.registerBean(MetadataProjectDescriptionCustomizer.class,
() -> new MetadataProjectDescriptionCustomizer(metadata));
}
private void publishProjectGeneratedEvent(R request, ProjectGenerationContext context) {
InitializrMetadata metadata = context.getBean(InitializrMetadata.class);
ProjectGeneratedEvent event = new ProjectGeneratedEvent(request, metadata);
this.eventPublisher.publishEvent(event);
}
private void publishProjectFailedEvent(R request, InitializrMetadata metadata, Exception cause) {
ProjectFailedEvent event = new ProjectFailedEvent(request, metadata, cause);
this.eventPublisher.publishEvent(event);
}
}
|
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectGenerationInvoker.java
| 1
|
请完成以下Java代码
|
public class NestedTestRow {
private int id;
private String[][] nestedArray;
// Constructors, getters, and setters
public NestedTestRow() {}
public NestedTestRow(int id, String[][] nestedArray) {
this.id = id;
this.nestedArray = nestedArray;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
|
public String[][] getNestedArray() {
return nestedArray;
}
public void setNestedArray(String[][] nestedArray) {
this.nestedArray = nestedArray;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NestedTestRow that = (NestedTestRow) o;
return id == that.id &&
Arrays.deepEquals(nestedArray, that.nestedArray);
}
}
|
repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\com\baeldung\resultsetarraytoarraystrings\NestedTestRow.java
| 1
|
请完成以下Java代码
|
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold max.
@param ThresholdMax
Maximum gross amount for withholding calculation (0=no limit)
*/
public void setThresholdMax (BigDecimal ThresholdMax)
{
set_Value (COLUMNNAME_ThresholdMax, ThresholdMax);
}
/** Get Threshold max.
@return Maximum gross amount for withholding calculation (0=no limit)
*/
public BigDecimal getThresholdMax ()
{
|
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Threshold min.
@param Thresholdmin
Minimum gross amount for withholding calculation
*/
public void setThresholdmin (BigDecimal Thresholdmin)
{
set_Value (COLUMNNAME_Thresholdmin, Thresholdmin);
}
/** Get Threshold min.
@return Minimum gross amount for withholding calculation
*/
public BigDecimal getThresholdmin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Withholding.java
| 1
|
请完成以下Java代码
|
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
/**
* PostingSign AD_Reference_ID=541699
* Reference name: PostingSign
*/
public static final int POSTINGSIGN_AD_Reference_ID=541699;
/** DR = D */
public static final String POSTINGSIGN_DR = "D";
/** CR = C */
public static final String POSTINGSIGN_CR = "C";
@Override
public void setPostingSign (final java.lang.String PostingSign)
{
set_Value (COLUMNNAME_PostingSign, PostingSign);
}
@Override
|
public java.lang.String getPostingSign()
{
return get_ValueAsString(COLUMNNAME_PostingSign);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_UserChange.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return ObjectUtils.toString(this);
}
/**
* @return true if there is a query that is currently running because user enabled/disabled some of the facets
*/
public final boolean isQueryRunning()
{
return queryRunning.get();
}
/**
* Filter underlying data model using the active filters,
*
* i.e.
* <ul>
* <li>gets currently active facets from {@link IFacetsPool}
* <li>filter registered {@link IFacetFilterable} using those
* </ul>
*
* @param triggeringFacet facet which triggered this query.
*/
private final void executeQuery(final IFacet<?> triggeringFacet)
{
final boolean alreadyRunning = queryRunning.getAndSet(true);
if (alreadyRunning)
{
// do nothing if query is already running
return;
}
try
{
//
// Get current active facets and filter the data source
final IFacetsPool<ModelType> facetsPool = getFacetsPool();
final Set<IFacet<ModelType>> facets = facetsPool.getActiveFacets();
final IFacetFilterable<ModelType> facetFilterable = getFacetFilterable();
facetFilterable.filter(facets);
//
// After filtering the datasource, we need to update all facet categories which are eager to refresh.
facetCollectors.collect()
.setSource(facetFilterable)
// Don't update facets from the same category as our triggering facets
.excludeFacetCategory(triggeringFacet.getFacetCategory())
// Update only those facet groups on which we also "eager refreshing"
|
.setOnlyEagerRefreshCategories()
.collectAndUpdate(facetsPool);
}
finally
{
queryRunning.set(false);
}
}
/**
* Collect all facets from registered {@link IFacetCollector}s and then set them to {@link IFacetsPool}.
*
* If this executor has already a query which is running ({@link #isQueryRunning()}), this method will do nothing.
*/
public void collectFacetsAndResetPool()
{
// Do nothing if we have query which is currently running,
// because it most of the cases this happends because some business logic
// was triggered when the underlying facet filterable was changed due to our current running query
// and which triggered this method.
// If we would not prevent this, we could run in endless recursive calls.
if (isQueryRunning())
{
return;
}
//
// Before collecting ALL facets from this data source, make sure the database source is reset to it's inital state.
final IFacetFilterable<ModelType> facetFilterable = getFacetFilterable();
facetFilterable.reset();
//
// Collect the facets from facet filterable's current selection
// and set them to facets pool
facetCollectors.collect()
.setSource(facetFilterable)
.collectAndSet(getFacetsPool());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetExecutor.java
| 1
|
请完成以下Java代码
|
public PdfCollator close()
{
if (closed)
{
return this;
}
closed = true;
if (pdfCopy == null)
{
return this;
}
pdfDocument.close();
pdfCopy = null;
pdfDocument = null;
return this;
|
}
public byte[] toByteArray()
{
if (out instanceof ByteArrayOutputStream)
{
close();
final ByteArrayOutputStream baos = (ByteArrayOutputStream)out;
return baos.toByteArray();
}
else
{
throw new RuntimeException("Output stream not supported: " + out); // NOPMD by tsa on 2/28/13 2:15 AM
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\util\PdfCollator.java
| 1
|
请完成以下Java代码
|
public Builder setDocumentType(@NonNull final WindowId windowId)
{
setDocumentType(DocumentType.Window, windowId.toDocumentId());
return this;
}
public Builder setDocumentType(@NonNull final DocumentType documentType, @NonNull final DocumentId documentTypeId)
{
this.documentType = documentType;
this.documentTypeId = documentTypeId;
return this;
}
public Builder setDocumentId(final String documentIdStr)
{
setDocumentId(DocumentId.ofStringOrEmpty(documentIdStr));
return this;
}
public Builder setDocumentId(final DocumentId documentId)
{
this.documentId = documentId;
return this;
}
public Builder allowNewDocumentId()
{
documentId_allowNew = true;
return this;
}
public Builder setDetailId(final String detailIdStr)
{
setDetailId(DetailId.fromJson(detailIdStr));
return this;
}
public Builder setDetailId(final DetailId detailId)
{
this.detailId = detailId;
return this;
}
public Builder setRowId(final String rowIdStr)
{
final DocumentId rowId = DocumentId.ofStringOrEmpty(rowIdStr);
setRowId(rowId);
return this;
}
public Builder setRowId(@Nullable final DocumentId rowId)
{
|
rowIds.clear();
if (rowId != null)
{
rowIds.add(rowId);
}
return this;
}
public Builder setRowIdsList(final String rowIdsListStr)
{
return setRowIds(DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr));
}
public Builder setRowIds(final DocumentIdsSelection rowIds)
{
this.rowIds.clear();
this.rowIds.addAll(rowIds.toSet());
return this;
}
public Builder allowNullRowId()
{
rowId_allowNull = true;
return this;
}
public Builder allowNewRowId()
{
rowId_allowNew = true;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentPath.java
| 1
|
请完成以下Java代码
|
public class X_C_Workplace_Product extends org.compiere.model.PO implements I_C_Workplace_Product, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -684761921L;
/** Standard Constructor */
public X_C_Workplace_Product (final Properties ctx, final int C_Workplace_Product_ID, @Nullable final String trxName)
{
super (ctx, C_Workplace_Product_ID, trxName);
}
/** Load Constructor */
public X_C_Workplace_Product (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
|
@Override
public void setC_Workplace_Product_ID (final int C_Workplace_Product_ID)
{
if (C_Workplace_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_Product_ID, C_Workplace_Product_ID);
}
@Override
public int getC_Workplace_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_Product_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public String getValue() {
|
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
}
|
repos\SpringBootLearning-master\springboot-config\src\main\java\com\forezp\bean\ConfigBean.java
| 2
|
请完成以下Java代码
|
public void performOperationStep(DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
JobExecutorXml jobExecutorXml = getJobExecutorXml(operationContext);
int queueSize = getQueueSize(jobExecutorXml);
int corePoolSize = getCorePoolSize(jobExecutorXml);
int maxPoolSize = getMaxPoolSize(jobExecutorXml);
long keepAliveTime = getKeepAliveTime(jobExecutorXml);
// initialize Queue & Executor services
BlockingQueue<Runnable> threadPoolQueue = new ArrayBlockingQueue<Runnable>(queueSize);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, threadPoolQueue);
threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// construct the service for the thread pool
JmxManagedThreadPool managedThreadPool = new JmxManagedThreadPool(threadPoolQueue, threadPoolExecutor);
// install the service into the container
serviceContainer.startService(ServiceTypes.BPM_PLATFORM, RuntimeContainerDelegateImpl.SERVICE_NAME_EXECUTOR, managedThreadPool);
}
private JobExecutorXml getJobExecutorXml(DeploymentOperation operationContext) {
BpmPlatformXml bpmPlatformXml = operationContext.getAttachment(Attachments.BPM_PLATFORM_XML);
JobExecutorXml jobExecutorXml = bpmPlatformXml.getJobExecutor();
return jobExecutorXml;
}
private int getQueueSize(JobExecutorXml jobExecutorXml) {
String queueSize = jobExecutorXml.getProperties().get(JobExecutorXml.QUEUE_SIZE);
if (queueSize == null) {
return DEFAULT_QUEUE_SIZE;
}
|
return Integer.parseInt(queueSize);
}
private long getKeepAliveTime(JobExecutorXml jobExecutorXml) {
String keepAliveTime = jobExecutorXml.getProperties().get(JobExecutorXml.KEEP_ALIVE_TIME);
if (keepAliveTime == null) {
return DEFAULT_KEEP_ALIVE_TIME_MS;
}
return Long.parseLong(keepAliveTime);
}
private int getMaxPoolSize(JobExecutorXml jobExecutorXml) {
String maxPoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.MAX_POOL_SIZE);
if (maxPoolSize == null) {
return DEFAULT_MAX_POOL_SIZE;
}
return Integer.parseInt(maxPoolSize);
}
private int getCorePoolSize(JobExecutorXml jobExecutorXml) {
String corePoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.CORE_POOL_SIZE);
if (corePoolSize == null) {
return DEFAULT_CORE_POOL_SIZE;
}
return Integer.parseInt(corePoolSize);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartManagedThreadPoolStep.java
| 1
|
请完成以下Java代码
|
public Builder setFilters(final Collection<DocumentFilterDescriptor> filters)
{
this.filters = filters;
return this;
}
public Builder addFilter(@NonNull final DocumentFilterDescriptor filter)
{
if (filters == null)
{
filters = new ArrayList<>();
}
filters.add(filter);
return this;
}
private DocumentQueryOrderByList getDefaultOrderBys()
{
return defaultOrderBys != null ? defaultOrderBys : DocumentQueryOrderByList.EMPTY;
}
public Builder setDefaultOrderBys(final DocumentQueryOrderByList defaultOrderBys)
{
this.defaultOrderBys = defaultOrderBys;
return this;
}
public Set<String> getFieldNames()
{
return elementBuilders
.stream()
.flatMap(element -> element.getFieldNames().stream())
.collect(GuavaCollectors.toImmutableSet());
}
public Builder setIdFieldName(final String idFieldName)
{
this.idFieldName = idFieldName;
return this;
}
private String getIdFieldName()
{
return idFieldName;
}
public Builder setHasAttributesSupport(final boolean hasAttributesSupport)
{
this.hasAttributesSupport = hasAttributesSupport;
return this;
}
public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout)
{
this.includedViewLayout = includedViewLayout;
return this;
}
public Builder clearViewCloseActions()
{
allowedViewCloseActions = new LinkedHashSet<>();
return this;
}
public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction)
{
if (allowedViewCloseActions == null)
{
allowedViewCloseActions = new LinkedHashSet<>();
|
}
allowedViewCloseActions.add(viewCloseAction);
return this;
}
private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions()
{
return allowedViewCloseActions != null
? ImmutableSet.copyOf(allowedViewCloseActions)
: DEFAULT_allowedViewCloseActions;
}
public Builder setHasTreeSupport(final boolean hasTreeSupport)
{
this.hasTreeSupport = hasTreeSupport;
return this;
}
public Builder setTreeCollapsible(final boolean treeCollapsible)
{
this.treeCollapsible = treeCollapsible;
return this;
}
public Builder setTreeExpandedDepth(final int treeExpandedDepth)
{
this.treeExpandedDepth = treeExpandedDepth;
return this;
}
public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails)
{
this.allowOpeningRowDetails = allowOpeningRowDetails;
return this;
}
public Builder setFocusOnFieldName(final String focusOnFieldName)
{
this.focusOnFieldName = focusOnFieldName;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java
| 1
|
请完成以下Java代码
|
public class DirectDebitTransactionSDD {
@XmlElement(name = "MndtRltdInf", required = true)
protected MandateRelatedInformationSDD mndtRltdInf;
@XmlElement(name = "CdtrSchmeId")
protected PartyIdentificationSEPA3 cdtrSchmeId;
/**
* Gets the value of the mndtRltdInf property.
*
* @return
* possible object is
* {@link MandateRelatedInformationSDD }
*
*/
public MandateRelatedInformationSDD getMndtRltdInf() {
return mndtRltdInf;
}
/**
* Sets the value of the mndtRltdInf property.
*
* @param value
* allowed object is
* {@link MandateRelatedInformationSDD }
*
*/
public void setMndtRltdInf(MandateRelatedInformationSDD value) {
this.mndtRltdInf = value;
}
/**
|
* Gets the value of the cdtrSchmeId property.
*
* @return
* possible object is
* {@link PartyIdentificationSEPA3 }
*
*/
public PartyIdentificationSEPA3 getCdtrSchmeId() {
return cdtrSchmeId;
}
/**
* Sets the value of the cdtrSchmeId property.
*
* @param value
* allowed object is
* {@link PartyIdentificationSEPA3 }
*
*/
public void setCdtrSchmeId(PartyIdentificationSEPA3 value) {
this.cdtrSchmeId = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\DirectDebitTransactionSDD.java
| 1
|
请完成以下Java代码
|
static boolean matchesPkceTokenRequest(HttpServletRequest request) {
return matchesAuthorizationCodeGrantRequest(request)
&& request.getParameter(PkceParameterNames.CODE_VERIFIER) != null;
}
static void validateAndAddDPoPParametersIfAvailable(HttpServletRequest request,
Map<String, Object> additionalParameters) {
final String dPoPProofHeaderName = OAuth2AccessToken.TokenType.DPOP.getValue();
String dPoPProof = request.getHeader(dPoPProofHeaderName);
if (StringUtils.hasText(dPoPProof)) {
if (Collections.list(request.getHeaders(dPoPProofHeaderName)).size() != 1) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, dPoPProofHeaderName, ACCESS_TOKEN_REQUEST_ERROR_URI);
}
else {
additionalParameters.put("dpop_proof", dPoPProof);
additionalParameters.put("dpop_method", request.getMethod());
additionalParameters.put("dpop_target_uri", request.getRequestURL().toString());
}
}
}
|
static void throwError(String errorCode, String parameterName, String errorUri) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri);
throw new OAuth2AuthenticationException(error);
}
static String normalizeUserCode(String userCode) {
Assert.hasText(userCode, "userCode cannot be empty");
StringBuilder sb = new StringBuilder(userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", ""));
Assert.isTrue(sb.length() == 8, "userCode must be exactly 8 alpha/numeric characters");
sb.insert(4, '-');
return sb.toString();
}
static boolean validateUserCode(String userCode) {
return (userCode != null && userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", "").length() == 8);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2EndpointUtils.java
| 1
|
请完成以下Java代码
|
public final class C_Order_CreatePOFromRequisition extends C_Order_CreationProcess implements IProcessPrecondition
{
private final IOrderBL orderBL = Services.get(IOrderBL.class);
@Param(parameterName = "C_DocType_ID", mandatory = true)
private DocTypeId newOrderDocTypeId;
@Param(parameterName = "DateOrdered")
private Timestamp newOrderDateOrdered;
@Param(parameterName = "POReference")
private String poReference;
@Param(parameterName = "CompleteIt")
private boolean completeIt;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull I_C_Order order)
{
final DocStatus quotationDocStatus = DocStatus.ofNullableCodeOrUnknown(order.getDocStatus());
if (!quotationDocStatus.isCompleted())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a completed quotation");
}
if (!orderBL.isRequisition(order))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("is not purchase requisition");
}
|
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final I_C_Order purchaseOrder = CreatePurchaseOrderFromRequisitionCommand.builder()
.fromRequisitionId(OrderId.ofRepoId(getRecord_ID()))
.newOrderDocTypeId(newOrderDocTypeId)
.newOrderDateOrdered(newOrderDateOrdered)
.poReference(poReference)
.completeIt(completeIt)
.build()
.execute();
openOrder(purchaseOrder, AdWindowId.ofRepoId(getProcessInfo().getAD_Window_ID()));
return purchaseOrder.getDocumentNo();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\process\C_Order_CreatePOFromRequisition.java
| 1
|
请完成以下Java代码
|
public static MIndexColumn retrieveOrCreate(final MIndexTable indexTable,
final String columnName, final int seqNo) {
final Properties ctx = indexTable.getCtx();
final String trxName = indexTable.get_TrxName();
final MTable table = (MTable) indexTable.getAD_Table();
final MColumn column = table.getColumn(columnName);
if (column == null) {
throw new IllegalArgumentException("Illegal column name '"
+ columnName + "' for table " + table);
}
final String whereClause = COLUMNNAME_AD_Index_Table_ID + "=? AND "
+ COLUMNNAME_AD_Column_ID + "=?";
|
final Object[] params = { indexTable.get_ID(), column.get_ID() };
MIndexColumn indexColumn = new Query(ctx, Table_Name,
whereClause, trxName).setParameters(params).firstOnly(MIndexColumn.class);
if (indexColumn == null) {
indexColumn = new MIndexColumn(ctx, 0, trxName);
indexColumn.setAD_Index_Table_ID(indexTable.get_ID());
indexColumn.setAD_Column_ID(column.get_ID());
}
indexColumn.setSeqNo(seqNo);
indexColumn.saveEx();
return indexColumn;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexColumn.java
| 1
|
请完成以下Java代码
|
public class Person {
private Integer personId;
private String name;
private List<Address> addresses;
public Person() {
}
public Person(Integer personId, String name) {
this.personId = personId;
this.name = name;
addresses = new ArrayList<Address>();
}
public Person(String name) {
this.name = name;
}
public Integer getPersonId() {
|
return personId;
}
public String getName() {
return name;
}
public void addAddress(Address address) {
addresses.add(address);
}
public List<Address> getAddresses() {
return addresses;
}
}
|
repos\tutorials-master\mybatis\src\main\java\com\baeldung\mybatis\model\Person.java
| 1
|
请完成以下Java代码
|
public boolean isAllowed(MethodInvocation invocation, Authentication authentication) {
Assert.notNull(invocation, "MethodInvocation required");
Assert.notNull(invocation.getMethod(), "MethodInvocation must provide a non-null getMethod()");
Collection<ConfigAttribute> attrs = this.securityInterceptor.obtainSecurityMetadataSource()
.getAttributes(invocation);
if (attrs == null) {
return !this.securityInterceptor.isRejectPublicInvocations();
}
if (authentication == null || authentication.getAuthorities().isEmpty()) {
return false;
}
try {
this.securityInterceptor.getAccessDecisionManager().decide(authentication, invocation, attrs);
return true;
}
|
catch (AccessDeniedException unauthorized) {
logger.debug(LogMessage.format("%s denied for %s", invocation, authentication), unauthorized);
return false;
}
}
public void setSecurityInterceptor(AbstractSecurityInterceptor securityInterceptor) {
Assert.notNull(securityInterceptor, "AbstractSecurityInterceptor cannot be null");
Assert.isTrue(MethodInvocation.class.equals(securityInterceptor.getSecureObjectClass()),
"AbstractSecurityInterceptor does not support MethodInvocations");
Assert.notNull(securityInterceptor.getAccessDecisionManager(),
"AbstractSecurityInterceptor must provide a non-null AccessDecisionManager");
this.securityInterceptor = securityInterceptor;
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\MethodInvocationPrivilegeEvaluator.java
| 1
|
请完成以下Java代码
|
class ZipInflaterInputStream extends InflaterInputStream {
private int available;
private boolean extraBytesWritten;
ZipInflaterInputStream(InputStream inputStream, Inflater inflater, int size) {
super(inputStream, inflater, getInflaterBufferSize(size));
this.available = size;
}
private static int getInflaterBufferSize(long size) {
size += 2; // inflater likes some space
size = (size > 65536) ? 8192 : size;
size = (size <= 0) ? 4096 : size;
return (int) size;
}
@Override
public int available() throws IOException {
return (this.available >= 0) ? this.available : super.available();
}
@Override
|
public int read(byte[] b, int off, int len) throws IOException {
int result = super.read(b, off, len);
if (result != -1) {
this.available -= result;
}
return result;
}
@Override
protected void fill() throws IOException {
try {
super.fill();
}
catch (EOFException ex) {
if (this.extraBytesWritten) {
throw ex;
}
this.len = 1;
this.buf[0] = 0x0;
this.extraBytesWritten = true;
this.inf.setInput(this.buf, 0, this.len);
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\ZipInflaterInputStream.java
| 1
|
请完成以下Java代码
|
public class M_ProductPrice_ActivationBasedOnProductDiscontinuedFlag_Process extends JavaProcess implements IProcessPrecondition
{
private static final AdMessageKey ERROR_MISSING_DISCONTINUED_FROM = AdMessageKey.of("ActivationBasedOnProductDiscontinuedFlag_Process.MissingDiscontinuedFrom");
private final IProductDAO productDAO = Services.get(IProductDAO.class);
private final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class);
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final I_M_Product product = productDAO.getById(getRecord_ID());
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryFilter<I_M_Product> productFilter = queryBL.createCompositeQueryFilter(I_M_Product.class)
.addOnlyActiveRecordsFilter()
.addCompareFilter(
I_M_Product.COLUMNNAME_M_Product_ID,
CompareQueryFilter.Operator.EQUAL,
product.getM_Product_ID());
if (product.isDiscontinued())
{
final ZoneId zoneId = orgDAO.getTimeZone(OrgId.ofRepoId(product.getAD_Org_ID()));
final Optional<LocalDate> discontinuedFrom = Optional.ofNullable(product.getDiscontinuedFrom())
.map(discontinuedFromTimestamp -> TimeUtil.asLocalDate(discontinuedFromTimestamp, zoneId));
|
if (!discontinuedFrom.isPresent())
{
throw new AdempiereException(ERROR_MISSING_DISCONTINUED_FROM)
.appendParametersToMessage()
.setParameter("ProductId", product.getM_Product_ID());
}
priceListDAO.updateProductPricesIsActive(productFilter, discontinuedFrom.get(), false);
}
else
{
priceListDAO.updateProductPricesIsActive(productFilter, null, true);
}
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\process\M_ProductPrice_ActivationBasedOnProductDiscontinuedFlag_Process.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
PasswordEncoder passwordEncoder() {
// 使用BCrypt强哈希函数加密方案(密钥迭代次数默认为10)
return new BCryptPasswordEncoder();
}
// 配置 password 授权模式
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.inMemory()
.withClient("password")
.authorizedGrantTypes("password", "refresh_token") //授权模式为password和refresh_token两种
.accessTokenValiditySeconds(1800) // 配置access_token的过期时间
.resourceIds("rid") //配置资源id
.scopes("all")
.secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq"); //123加密后的密码
}
|
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
//endpoints.tokenStore(inMemoryTokenStore) //配置令牌的存储(这里存放在内存中)
endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
// 表示支持 client_id 和 client_secret 做登录认证
security.allowFormAuthenticationForClients();
}
}
|
repos\springboot-demo-master\oatuth2\src\main\java\com\et\oauth2\config\AuthorizationServerConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static ActiveMQConnectionFactory createJmsConnectionFactory(ActiveMQProperties properties,
ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers,
ActiveMQConnectionDetails connectionDetails) {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(),
connectionDetails.getPassword(), connectionDetails.getBrokerUrl());
new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList())
.configure(connectionFactory);
return connectionFactory;
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CachingConnectionFactory.class)
@ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true)
static class CachingConnectionFactoryConfiguration {
@Bean
CachingConnectionFactory jmsConnectionFactory(JmsProperties jmsProperties, ActiveMQProperties properties,
ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers,
ActiveMQConnectionDetails connectionDetails) {
JmsProperties.Cache cacheProperties = jmsProperties.getCache();
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
createJmsConnectionFactory(properties, factoryCustomizers, connectionDetails));
connectionFactory.setCacheConsumers(cacheProperties.isConsumers());
connectionFactory.setCacheProducers(cacheProperties.isProducers());
connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize());
return connectionFactory;
}
|
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class })
static class PooledConnectionFactoryConfiguration {
@Bean(destroyMethod = "stop")
@ConditionalOnBooleanProperty("spring.activemq.pool.enabled")
JmsPoolConnectionFactory jmsConnectionFactory(ActiveMQProperties properties,
ObjectProvider<ActiveMQConnectionFactoryCustomizer> factoryCustomizers,
ActiveMQConnectionDetails connectionDetails) {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionDetails.getUser(),
connectionDetails.getPassword(), connectionDetails.getBrokerUrl());
new ActiveMQConnectionFactoryConfigurer(properties, factoryCustomizers.orderedStream().toList())
.configure(connectionFactory);
return new JmsPoolConnectionFactoryFactory(properties.getPool())
.createPooledConnectionFactory(connectionFactory);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQConnectionFactoryConfiguration.java
| 2
|
请完成以下Java代码
|
public class RotateArray {
private RotateArray() {
throw new IllegalStateException("Rotate array algorithm utility methods class");
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void bruteForce(int[] arr, int k) {
checkInvalidInput(arr, k);
k %= arr.length;
int temp;
int previous;
for (int i = 0; i < k; i++) {
previous = arr[arr.length - 1];
for (int j = 0; j < arr.length; j++) {
temp = arr[j];
arr[j] = previous;
previous = temp;
}
}
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void withExtraArray(int[] arr, int k) {
checkInvalidInput(arr, k);
int[] extraArray = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
extraArray[(i + k) % arr.length] = arr[i];
}
System.arraycopy(extraArray, 0, arr, 0, arr.length);
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void cyclicReplacement(int[] arr, int k) {
checkInvalidInput(arr, k);
k = k % arr.length;
int count = 0;
for (int start = 0; count < arr.length; start++) {
int current = start;
|
int prev = arr[start];
do {
int next = (current + k) % arr.length;
int temp = arr[next];
arr[next] = prev;
prev = temp;
current = next;
count++;
} while (start != current);
}
}
/**
*
* @param arr array to apply rotation to
* @param k number of rotations
*/
public static void reverse(int[] arr, int k) {
checkInvalidInput(arr, k);
k %= arr.length;
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}
private static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
private static void checkInvalidInput(int[] arr, int rotation) {
if (rotation < 1 || arr == null)
throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null");
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\rotatearray\RotateArray.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
shutdown: graceful
spring:
jpa:
database: POSTGRESQL
show-sql: true
generate-ddl: true
hibernate:
ddl-auto: create-drop
properties:
hibernate:
jdbc:
lob:
non_contextual_creation: true
datasource:
platform: postgres
url
|
: jdbc:postgresql://localhost:5432/postgres
username: postgres
password: secret
lifecycle:
timeout-per-shutdown-phase: 20s
|
repos\spring-examples-java-17\spring-bank\bank-server\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* PostingType AD_Reference_ID=125
* Reference name: _Posting Type
*/
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Actual Year End = Y */
public static final String POSTINGTYPE_ActualYearEnd = "Y";
/** Set Buchungsart.
@param PostingType
Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public void setPostingType (java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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();
}
/** Set SubLine ID.
@param SubLine_ID
Transaction sub line ID (internal)
*/
@Override
public void setSubLine_ID (int SubLine_ID)
{
if (SubLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_SubLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID));
}
/** Get SubLine ID.
@return Transaction sub line ID (internal)
*/
@Override
public int getSubLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest_Source_v.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static HttpResponse httpsRequest2(String requestUrl, String method, String outputStr) throws IOException {
HttpsURLConnection connection = null;
try {
SSLSocketFactory ssf = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
ssf = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
throw new IOException("实例化SSLContext失败", e);
} catch (NoSuchProviderException e) {
throw new IOException("实例化SSLContext失败", e);
} catch (KeyManagementException e) {
throw new IOException("初始化SSLContext失败", e);
}
URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
// 设置请求方式(GET/POST)
connection.setRequestMethod(method);
if ("GET".equalsIgnoreCase(method)) {
connection.connect();
}
// 当有数据需要提交时
|
if (null != outputStr) {
OutputStream outputStream = connection.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
return new HttpResponse(connection);
} catch (IOException e) {
if (connection != null) {
connection.disconnect();
}
throw e;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\https\HttpClientUtil.java
| 2
|
请完成以下Java代码
|
public class HashcodeBuilder
{
private final static int prime = 31;
private int hashcode = 0;
public HashcodeBuilder()
{
super();
}
public HashcodeBuilder append(Object value)
{
return appendHashcode(value == null ? 0 : value.hashCode());
}
/**
* Converts given {@link BigDecimal} to {@link Double} and appends the {@link Double}'s hash code.
*
* We do this, because 2 big decimals which are numerically equal but have different scales, will have 2 different hashes.
*
* @param value
*
* @see http://stackoverflow.com/questions/14311644/normalizing-bigdecimals-hash-code-howto
*/
public HashcodeBuilder append(final BigDecimal value)
{
if (value == null)
{
return appendHashcode(0);
}
final Double d = value.doubleValue();
return appendHashcode(d.hashCode());
}
public HashcodeBuilder appendHashcode(final int hashcodeToAppend)
{
hashcode = prime * hashcode + hashcodeToAppend;
return this;
}
|
public HashcodeBuilder append(Map<?, ?> map, boolean handleEmptyMapAsNull)
{
if (handleEmptyMapAsNull && (map == null || map.isEmpty()))
{
return append((Object)null);
}
return append(map);
}
public int toHashcode()
{
return hashcode;
}
/**
* Sames as {@link #toHashcode()} because:
* <ul>
* <li>we want to avoid bugs like calling this method instead of {@link #toHashcode()}
* <li>the real hash code of this object does not matter
* </ul>
*
* @deprecated Please use {@link #toHashcode()}. This method is present here, just to avoid some mistakes.
*/
@Deprecated
@Override
public int hashCode()
{
return toHashcode();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\HashcodeBuilder.java
| 1
|
请完成以下Java代码
|
public void setId(String value) {
this.id = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{urn:msv3:v2}ArtikelMenge">
* <attribute name="Bedarf" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="direkt"/>
* <enumeration value="einsAusN"/>
* <enumeration value="unspezifisch"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Artikel
extends ArtikelMenge
{
@XmlAttribute(name = "Bedarf", required = true)
protected String bedarf;
/**
* Gets the value of the bedarf property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getBedarf() {
return bedarf;
}
/**
* Sets the value of the bedarf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBedarf(String value) {
this.bedarf = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VerfuegbarkeitsanfrageEinzelne.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/
public void setOrderByClause (String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
public String getOrderByClause ()
{
return (String)get_Value(COLUMNNAME_OrderByClause);
}
|
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView.java
| 1
|
请完成以下Java代码
|
public JavaType resolveAbstractType(DeserializationConfig config, BeanDescription typeDesc) {
return findTypeMapping(config, typeDesc.getType());
}
};
resolver.addMapping(Task.class, TaskImpl.class);
resolver.addMapping(TaskCandidateUser.class, TaskCandidateUserImpl.class);
resolver.addMapping(TaskCandidateGroup.class, TaskCandidateGroupImpl.class);
module.registerSubtypes(new NamedType(TaskResult.class, TaskResult.class.getSimpleName()));
module.registerSubtypes(new NamedType(ClaimTaskPayload.class, ClaimTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(CompleteTaskPayload.class, CompleteTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(SaveTaskPayload.class, SaveTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(CreateTaskPayload.class, CreateTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(DeleteTaskPayload.class, DeleteTaskPayload.class.getSimpleName()));
|
module.registerSubtypes(new NamedType(GetTasksPayload.class, GetTasksPayload.class.getSimpleName()));
module.registerSubtypes(
new NamedType(GetTaskVariablesPayload.class, GetTaskVariablesPayload.class.getSimpleName())
);
module.registerSubtypes(new NamedType(ReleaseTaskPayload.class, ReleaseTaskPayload.class.getSimpleName()));
module.registerSubtypes(new NamedType(UpdateTaskPayload.class, UpdateTaskPayload.class.getSimpleName()));
module.setAbstractTypes(resolver);
return module;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-model-impl\src\main\java\org\activiti\api\task\conf\impl\TaskModelAutoConfiguration.java
| 1
|
请完成以下Java代码
|
public class UserDto {
private String firstName;
private String lastName;
private String displayName;
private String id;
public UserDto(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
if (firstName == null && lastName == null) {
this.displayName = id;
}else {
this.displayName = (lastName != null) ? firstName + " " + lastName : firstName;
}
}
public String getFirstName() {
return firstName;
}
public String getId() {
return id;
}
public String getLastName() {
return lastName;
}
|
public String getDisplayName() {
return displayName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDto userDto = (UserDto) o;
if (firstName != null ? !firstName.equals(userDto.firstName) : userDto.firstName != null) return false;
if (id != null ? !id.equals(userDto.id) : userDto.id != null) return false;
if (lastName != null ? !lastName.equals(userDto.lastName) : userDto.lastName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\UserDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String auditHeaders(@NonNull final Map<String, Object> headers)
{
final StringBuilder headersStringCollector = new StringBuilder(" ========================= Headers ======================== \n");
try
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.newJsonObjectMapper();
return headersStringCollector
.append(objectMapper.writeValueAsString(headers))
.append("\n")
.toString();
}
catch (final Exception e)
{
return headersStringCollector.append(getHeadersErrorMessage(e, headers)).toString();
|
}
}
@NonNull
private String getHeadersErrorMessage(@NonNull final Exception exception, @NonNull final Map<String, Object> headers)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
return "\n Got exception while parsing request headers \n"
+ ";\n ========================= blindly converting headers toString(); headers: ======================== \n"
+ headers.toString()
+ ";\n ========================= error stack trace - start ======================== \n"
+ exception.getLocalizedMessage()
+ ";\n ========================= error stack trace - end ======================== \n";
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AuditFileTrailUtil.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_M_Shipper getM_Shipper()
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
@Override
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_Shipper_RoutingCode_ID (final int M_Shipper_RoutingCode_ID)
{
if (M_Shipper_RoutingCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, null);
|
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_RoutingCode_ID, M_Shipper_RoutingCode_ID);
}
@Override
public int getM_Shipper_RoutingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_RoutingCode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @ResponseBody ResponseEntity<String> get() {
return new ResponseEntity<>("GET Response", HttpStatus.OK);
}
@GetMapping("/get/{id}")
public @ResponseBody ResponseEntity<String> getById(@PathVariable String id) {
return new ResponseEntity<>("GET Response : " + id, HttpStatus.OK);
}
@PostMapping("/post")
public @ResponseBody ResponseEntity<String> post() {
return new ResponseEntity<>("POST Response", HttpStatus.OK);
}
@PutMapping("/put")
|
public @ResponseBody ResponseEntity<String> put() {
return new ResponseEntity<>("PUT Response", HttpStatus.OK);
}
@DeleteMapping("/delete")
public @ResponseBody ResponseEntity<String> delete() {
return new ResponseEntity<>("DELETE Response", HttpStatus.OK);
}
@PatchMapping("/patch")
public @ResponseBody ResponseEntity<String> patch() {
return new ResponseEntity<>("PATCH Response", HttpStatus.OK);
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-3\src\main\java\com\baeldung\boot\controller\RequestMappingShortcutsController.java
| 2
|
请完成以下Java代码
|
public StringAttributeBuilder idAttribute() {
return (StringAttributeBuilder) super.idAttribute();
}
/**
* Create a new {@link AttributeReferenceBuilder} for the reference source element instance
*
* @param referenceTargetElement the reference target model element instance
* @return the new attribute reference builder
*/
public <V extends ModelElementInstance> AttributeReferenceBuilder<V> qNameAttributeReference(Class<V> referenceTargetElement) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build();
AttributeReferenceBuilderImpl<V> referenceBuilder = new QNameAttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
public <V extends ModelElementInstance> AttributeReferenceBuilder<V> idAttributeReference(Class<V> referenceTargetElement) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build();
AttributeReferenceBuilderImpl<V> referenceBuilder = new AttributeReferenceBuilderImpl<V>(attribute, referenceTargetElement);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
@SuppressWarnings("rawtypes")
public <V extends ModelElementInstance> AttributeReferenceCollectionBuilder<V> idAttributeReferenceCollection(Class<V> referenceTargetElement, Class<? extends AttributeReferenceCollection> attributeReferenceCollection) {
AttributeImpl<String> attribute = (AttributeImpl<String>) build();
AttributeReferenceCollectionBuilder<V> referenceBuilder = new AttributeReferenceCollectionBuilderImpl<V>(attribute, referenceTargetElement, attributeReferenceCollection);
setAttributeReference(referenceBuilder);
return referenceBuilder;
}
protected <V extends ModelElementInstance> void setAttributeReference(AttributeReferenceBuilder<V> referenceBuilder) {
if (this.referenceBuilder != null) {
|
throw new ModelException("An attribute cannot have more than one reference");
}
this.referenceBuilder = referenceBuilder;
}
@Override
public void performModelBuild(Model model) {
super.performModelBuild(model);
if (referenceBuilder != null) {
((ModelBuildOperation) referenceBuilder).performModelBuild(model);
}
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\StringAttributeBuilderImpl.java
| 1
|
请完成以下Java代码
|
public void onDeviceUpdate(Device device) {
this.profileId = device.getDeviceProfileId();
var data = device.getDeviceData();
if (data.getTransportConfiguration() != null && data.getTransportConfiguration().getType().equals(DeviceTransportType.COAP)) {
CoapDeviceTransportConfiguration configuration = (CoapDeviceTransportConfiguration) data.getTransportConfiguration();
this.powerMode = configuration.getPowerMode();
this.edrxCycle = configuration.getEdrxCycle();
this.psmActivityTimer = configuration.getPsmActivityTimer();
this.pagingTransmissionWindow = configuration.getPagingTransmissionWindow();
}
}
public void addQueuedNotification(TransportProtos.AttributeUpdateNotificationMsg msg) {
if (missedAttributeUpdates == null) {
missedAttributeUpdates = msg;
} else {
Map<String, TransportProtos.TsKvProto> updatedAttrs = new HashMap<>(missedAttributeUpdates.getSharedUpdatedCount() + msg.getSharedUpdatedCount());
Set<String> deletedKeys = new HashSet<>(missedAttributeUpdates.getSharedDeletedCount() + msg.getSharedDeletedCount());
for (TransportProtos.TsKvProto oldUpdatedAttrs : missedAttributeUpdates.getSharedUpdatedList()) {
updatedAttrs.put(oldUpdatedAttrs.getKv().getKey(), oldUpdatedAttrs);
}
deletedKeys.addAll(msg.getSharedDeletedList());
for (TransportProtos.TsKvProto newUpdatedAttrs : msg.getSharedUpdatedList()) {
|
updatedAttrs.put(newUpdatedAttrs.getKv().getKey(), newUpdatedAttrs);
}
deletedKeys.addAll(msg.getSharedDeletedList());
for (String deletedKey : msg.getSharedDeletedList()) {
updatedAttrs.remove(deletedKey);
}
missedAttributeUpdates = TransportProtos.AttributeUpdateNotificationMsg.newBuilder().addAllSharedUpdated(updatedAttrs.values()).addAllSharedDeleted(deletedKeys).build();
}
}
public TransportProtos.AttributeUpdateNotificationMsg getAndClearMissedUpdates() {
var result = this.missedAttributeUpdates;
this.missedAttributeUpdates = null;
return result;
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\client\TbCoapClientState.java
| 1
|
请完成以下Java代码
|
public void setCM_Container_ID (int CM_Container_ID)
{
if (CM_Container_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID));
}
/** Get Web Container.
@return Web Container contains content like images, text etc.
*/
public int getCM_Container_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Content HTML.
@param ContentHTML
Contains the content itself
*/
public void setContentHTML (String ContentHTML)
{
set_Value (COLUMNNAME_ContentHTML, ContentHTML);
}
/** Get Content HTML.
@return Contains the content itself
*/
public String getContentHTML ()
{
return (String)get_Value(COLUMNNAME_ContentHTML);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Valid.
@param IsValid
Element is valid
*/
public void setIsValid (boolean IsValid)
{
|
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Valid.
@return Element is valid
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_Element.java
| 1
|
请完成以下Java代码
|
public class ELExecutionContext {
protected Map<Integer, Map<String, Object>> ruleResults = new LinkedHashMap<>();
protected Map<String, Object> stackVariables;
protected DecisionExecutionAuditContainer auditContainer;
protected Map<String, List<Object>> outputValues = new LinkedHashMap<>();
protected BuiltinAggregator aggregator;
protected String instanceId;
protected String scopeType;
protected String tenantId;
protected boolean forceDMN11;
public void checkExecutionContext(String variableId) {
if (StringUtils.isEmpty(variableId)) {
throw new IllegalArgumentException("Variable id cannot be empty");
}
}
public void addRuleResult(int ruleNumber, String outputName, Object outputValue) {
Map<String, Object> ruleResult;
if (ruleResults.containsKey(ruleNumber)) {
ruleResult = ruleResults.get(ruleNumber);
} else {
ruleResult = new HashMap<>();
ruleResults.put(ruleNumber, ruleResult);
}
ruleResult.put(outputName, outputValue);
}
public void setStackVariables(Map<String, Object> variables) {
this.stackVariables = variables;
}
public Map<String, Object> getStackVariables() {
return stackVariables;
}
public Map<String, Object> getRuleResult(int ruleNumber) {
return ruleResults.get(ruleNumber);
}
public Map<Integer, Map<String, Object>> getRuleResults() {
return ruleResults;
}
public DecisionExecutionAuditContainer getAuditContainer() {
return auditContainer;
}
public void setAuditContainer(DecisionExecutionAuditContainer auditContainer) {
this.auditContainer = auditContainer;
}
|
public Map<String, List<Object>> getOutputValues() {
return outputValues;
}
public void addOutputValues(String outputName, List<Object> outputValues) {
this.outputValues.put(outputName, outputValues);
}
public BuiltinAggregator getAggregator() {
return aggregator;
}
public void setAggregator(BuiltinAggregator aggregator) {
this.aggregator = aggregator;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java
| 1
|
请完成以下Java代码
|
public class RequiredFactorError {
private final RequiredFactor requiredFactor;
private final Reason reason;
RequiredFactorError(RequiredFactor requiredFactor, Reason reason) {
Assert.notNull(requiredFactor, "RequiredFactor must not be null");
Assert.notNull(reason, "Reason must not be null");
if (reason == Reason.EXPIRED && requiredFactor.getValidDuration() == null) {
throw new IllegalArgumentException(
"If expired, RequiredFactor.getValidDuration() must not be null. Got " + requiredFactor);
}
this.requiredFactor = requiredFactor;
this.reason = reason;
}
public RequiredFactor getRequiredFactor() {
return this.requiredFactor;
}
/**
* True if not {@link #isMissing()} but was older than the
* {@link RequiredFactor#getValidDuration()}.
* @return true if expired, else false
*/
public boolean isExpired() {
return this.reason == Reason.EXPIRED;
}
/**
* True if no {@link FactorGrantedAuthority#getAuthority()} on the
* {@link org.springframework.security.core.Authentication} matched
* {@link RequiredFactor#getAuthority()}.
* @return true if missing, else false.
*/
public boolean isMissing() {
return this.reason == Reason.MISSING;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
RequiredFactorError that = (RequiredFactorError) o;
return Objects.equals(this.requiredFactor, that.requiredFactor) && this.reason == that.reason;
}
@Override
|
public int hashCode() {
return Objects.hash(this.requiredFactor, this.reason);
}
@Override
public String toString() {
return "RequiredFactorError{" + "requiredFactor=" + this.requiredFactor + ", reason=" + this.reason + '}';
}
public static RequiredFactorError createMissing(RequiredFactor requiredFactor) {
return new RequiredFactorError(requiredFactor, Reason.MISSING);
}
public static RequiredFactorError createExpired(RequiredFactor requiredFactor) {
return new RequiredFactorError(requiredFactor, Reason.EXPIRED);
}
/**
* The reason that the error occurred.
*
* @author Rob Winch
* @since 7.0
*/
private enum Reason {
/**
* The authority was missing.
* @see #isMissing()
*/
MISSING,
/**
* The authority was considered expired.
* @see #isExpired()
*/
EXPIRED
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\RequiredFactorError.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PathVariablesController {
private List<Item> items = new ArrayList<Item>();
public PathVariablesController() {
Item item1 = new Item(1, "First Item");
List<Detail> item1Details = new ArrayList<>();
item1Details.add(new Detail(1, "Green"));
item1Details.add(new Detail(2, "Large"));
item1.setDetails(item1Details);
items.add(item1);
Item item2 = new Item(2, "Second Item");
List<Detail> item2Details = new ArrayList<>();
item2Details.add(new Detail(1, "Red"));
item2Details.add(new Detail(2, "Medium"));
item2.setDetails(item2Details);
items.add(item2);
}
@GetMapping("/pathvars")
public String start(Model model) {
model.addAttribute("items", items);
return "pathvariables/index";
}
@GetMapping("/pathvars/single/{id}")
public String singlePathVariable(@PathVariable("id") int id, Model model) {
if (id == 1) {
model.addAttribute("item", new Item(1, "First Item"));
} else {
|
model.addAttribute("item", new Item(2, "Second Item"));
}
return "pathvariables/view";
}
@GetMapping("/pathvars/item/{itemId}/detail/{detailId}")
public String multiplePathVariable(@PathVariable("itemId") int itemId, @PathVariable("detailId") int detailId, Model model) {
for (Item item : items) {
if (item.getId() == itemId) {
model.addAttribute("item", item);
for (Detail detail : item.getDetails()) {
if (detail.getId() == detailId) {
model.addAttribute("detail", detail);
}
}
}
}
return "pathvariables/view";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\pathvariables\PathVariablesController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setup() throws NoSuchAlgorithmException {
refreshSecrets();
}
public SigningKeyResolver getSigningKeyResolver() {
return signingKeyResolver;
}
public Map<String, String> getSecrets() {
return secrets;
}
public void setSecrets(Map<String, String> secrets) {
Assert.notNull(secrets);
Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
this.secrets = secrets;
}
public byte[] getHS256SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getJcaName()));
|
}
public byte[] getHS384SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getJcaName()));
}
public byte[] getHS512SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getJcaName()));
}
public Map<String, String> refreshSecrets() throws NoSuchAlgorithmException {
SecretKey key = KeyGenerator.getInstance(SignatureAlgorithm.HS256.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS256.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS384.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS384.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
key = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName()).generateKey();
secrets.put(SignatureAlgorithm.HS512.getJcaName(), TextCodec.BASE64.encode(key.getEncoded()));
return secrets;
}
}
|
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\service\SecretService.java
| 2
|
请完成以下Java代码
|
public void linkToFlatrateDataEntryIfExists(final I_C_Invoice_Clearing_Alloc ica)
{
final I_C_Flatrate_DataEntry dataEntry = retrieveDataEntry(ica.getC_Invoice_Cand_ToClear(), ica.getC_Flatrate_Term());
if (dataEntry != null)
{
ica.setC_Flatrate_DataEntry(dataEntry);
}
}
private I_C_Flatrate_DataEntry retrieveDataEntry(final I_C_Invoice_Candidate invoiceCand, final I_C_Flatrate_Term term)
{
final List<I_C_Flatrate_DataEntry> entries =
Services.get(IFlatrateDAO.class).retrieveEntries(null, // I_C_Flatrate_Conditions
term,
invoiceCand.getDateOrdered(),
X_C_Flatrate_DataEntry.TYPE_Invoicing_PeriodBased,
|
UomId.ofRepoIdOrNull(term.getC_UOM_ID()),
true); // onlyNonSim
final I_C_Flatrate_DataEntry dataEntry;
if (entries.isEmpty())
{
dataEntry = null;
}
else
{
dataEntry = entries.get(0);
Check.assume(entries.size() == 1, "There is only one non-sim entry");
}
return dataEntry;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Invoice_Clearing_Alloc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UnitConversionType {
@XmlElement(name = "BaseUnit", required = true)
protected UnitType baseUnit;
@XmlElement(name = "TargetUnit", required = true)
protected UnitType targetUnit;
@XmlElement(name = "Factor", required = true)
protected BigDecimal factor;
@XmlElement(name = "BaseUnitArticleNumber")
protected List<ArticleNumberExtType> baseUnitArticleNumber;
/**
* Gets the value of the baseUnit property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getBaseUnit() {
return baseUnit;
}
/**
* Sets the value of the baseUnit property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setBaseUnit(UnitType value) {
this.baseUnit = value;
}
/**
* Gets the value of the targetUnit property.
*
* @return
* possible object is
* {@link UnitType }
*
*/
public UnitType getTargetUnit() {
return targetUnit;
}
/**
* Sets the value of the targetUnit property.
*
* @param value
* allowed object is
* {@link UnitType }
*
*/
public void setTargetUnit(UnitType value) {
this.targetUnit = value;
}
/**
* Gets the value of the factor property.
*
* @return
* possible object is
* {@link BigDecimal }
|
*
*/
public BigDecimal getFactor() {
return factor;
}
/**
* Sets the value of the factor property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setFactor(BigDecimal value) {
this.factor = value;
}
/**
* Gets the value of the baseUnitArticleNumber property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the baseUnitArticleNumber property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBaseUnitArticleNumber().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ArticleNumberExtType }
*
*
*/
public List<ArticleNumberExtType> getBaseUnitArticleNumber() {
if (baseUnitArticleNumber == null) {
baseUnitArticleNumber = new ArrayList<ArticleNumberExtType>();
}
return this.baseUnitArticleNumber;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\UnitConversionType.java
| 2
|
请完成以下Java代码
|
public class NotificationData {
private long id;
private String name;
private String email;
private String mobile;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactor\src\main\java\com\baeldung\reactorbus\domain\NotificationData.java
| 1
|
请完成以下Java代码
|
public static boolean isOverlapping(
@Nullable final Timestamp start1,
@Nullable final Timestamp end1,
@Nullable final Timestamp start2,
@Nullable final Timestamp end2)
{
return isOverlapping(toInstantsRange(start1, end1), toInstantsRange(start2, end2));
}
public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2)
{
if (!range1.isConnected(range2))
{
return false;
}
return !range1.intersection(range2).isEmpty();
}
/**
* Compute the days between two dates as if each year is 360 days long.
* More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360}
*/
public static long getDaysBetween360(@NonNull final ZonedDateTime from, @NonNull final ZonedDateTime to)
{
if (from.isEqual(to))
{
return 0;
}
if (to.isBefore(from))
{
return getDaysBetween360(to, from) * -1;
}
ZonedDateTime dayFrom = from;
ZonedDateTime dayTo = to;
|
if (dayFrom.getDayOfMonth() == 31)
{
dayFrom = dayFrom.withDayOfMonth(30);
}
if (dayTo.getDayOfMonth() == 31)
{
dayTo = dayTo.withDayOfMonth(30);
}
final long months = ChronoUnit.MONTHS.between(
YearMonth.from(dayFrom), YearMonth.from(dayTo));
final int daysLeft = dayTo.getDayOfMonth() - dayFrom.getDayOfMonth();
return 30 * months + daysLeft;
}
/**
* Compute the days between two dates as if each year is 360 days long.
* More details and an implementation for Excel can be found in {@link org.apache.poi.ss.formula.functions.Days360}
*/
public static long getDaysBetween360(@NonNull final Instant from, @NonNull final Instant to)
{
return getDaysBetween360(asZonedDateTime(from), asZonedDateTime(to));
}
public static Instant addDays(@NonNull final Instant baseInstant, final long daysToAdd)
{
return baseInstant.plus(daysToAdd, ChronoUnit.DAYS);
}
} // TimeUtil
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\TimeUtil.java
| 1
|
请完成以下Java代码
|
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTablePrefix() {
return tablePrefix;
}
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
public static List<String> getSchemaUpdateValues() {
return SCHEMA_UPDATE_VALUES;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public boolean isJdbcBatchProcessing() {
return jdbcBatchProcessing;
|
}
public void setJdbcBatchProcessing(boolean jdbcBatchProcessing) {
this.jdbcBatchProcessing = jdbcBatchProcessing;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("type=" + type)
.add("schemaUpdate=" + schemaUpdate)
.add("schemaName=" + schemaName)
.add("tablePrefix=" + tablePrefix)
.add("jdbcBatchProcessing=" + jdbcBatchProcessing)
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\DatabaseProperty.java
| 1
|
请完成以下Java代码
|
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
|
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\pricing\model\X_C_PricingRule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTaxableAmount() {
return taxableAmount;
}
/**
* Sets the value of the taxableAmount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxableAmount(String value) {
this.taxableAmount = value;
}
/**
* Gets the value of the taxAmount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTaxAmount() {
return taxAmount;
}
/**
* Sets the value of the taxAmount property.
*
* @param value
* allowed object is
* {@link String }
|
*
*/
public void setTaxAmount(String value) {
this.taxAmount = value;
}
/**
* Gets the value of the adjustmentAmount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAdjustmentAmount() {
return adjustmentAmount;
}
/**
* Sets the value of the adjustmentAmount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAdjustmentAmount(String value) {
this.adjustmentAmount = value;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\REMADVExtensionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Saml2Error implements Serializable {
private static final long serialVersionUID = 620L;
private final String errorCode;
private final String description;
/**
* Constructs a {@code Saml2Error} using the provided parameters.
* @param errorCode the error code
* @param description the error description
*/
public Saml2Error(String errorCode, String description) {
Assert.hasText(errorCode, "errorCode cannot be empty");
this.errorCode = errorCode;
this.description = description;
}
/**
* Construct an {@link Saml2ErrorCodes#INVALID_RESPONSE} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error invalidResponse(String description) {
return new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, description);
}
/**
* Construct an {@link Saml2ErrorCodes#INTERNAL_VALIDATION_ERROR} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error internalValidationError(String description) {
return new Saml2Error(Saml2ErrorCodes.INTERNAL_VALIDATION_ERROR, description);
}
/**
* Construct an {@link Saml2ErrorCodes#MALFORMED_RESPONSE_DATA} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error malformedResponseData(String description) {
return new Saml2Error(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, description);
}
/**
* Construct an {@link Saml2ErrorCodes#DECRYPTION_ERROR} error
|
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error decryptionError(String description) {
return new Saml2Error(Saml2ErrorCodes.DECRYPTION_ERROR, description);
}
/**
* Construct an {@link Saml2ErrorCodes#RELYING_PARTY_REGISTRATION_NOT_FOUND} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error relyingPartyRegistrationNotFound(String description) {
return new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, description);
}
/**
* Construct an {@link Saml2ErrorCodes#SUBJECT_NOT_FOUND} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error subjectNotFound(String description) {
return new Saml2Error(Saml2ErrorCodes.SUBJECT_NOT_FOUND, description);
}
/**
* Returns the error code.
* @return the error code
*/
public final String getErrorCode() {
return this.errorCode;
}
/**
* Returns the error description.
* @return the error description
*/
public final String getDescription() {
return this.description;
}
@Override
public String toString() {
return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : "");
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2Error.java
| 2
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_LotCtlExclude[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Exclude Lot.
@param M_LotCtlExclude_ID
Exclude the ability to create Lots in Attribute Sets
*/
public void setM_LotCtlExclude_ID (int M_LotCtlExclude_ID)
{
if (M_LotCtlExclude_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_LotCtlExclude_ID, Integer.valueOf(M_LotCtlExclude_ID));
}
/** Get Exclude Lot.
@return Exclude the ability to create Lots in Attribute Sets
*/
public int getM_LotCtlExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtlExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_LotCtl getM_LotCtl() throws RuntimeException
{
return (I_M_LotCtl)MTable.get(getCtx(), I_M_LotCtl.Table_Name)
.getPO(getM_LotCtl_ID(), get_TrxName()); }
/** Set Lot Control.
@param M_LotCtl_ID
Product Lot Control
*/
public void setM_LotCtl_ID (int M_LotCtl_ID)
{
if (M_LotCtl_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID));
}
/** Get Lot Control.
@return Product Lot Control
*/
public int getM_LotCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtlExclude.java
| 1
|
请完成以下Java代码
|
public class TenantIdProviderProcessInstanceContext {
protected ProcessDefinition processDefinition;
protected VariableMap variables;
protected DelegateExecution superExecution;
protected DelegateCaseExecution superCaseExecution;
public TenantIdProviderProcessInstanceContext(ProcessDefinition processDefinition, VariableMap variables) {
this.processDefinition = processDefinition;
this.variables = variables;
}
public TenantIdProviderProcessInstanceContext(ProcessDefinition processDefinition, VariableMap variables, DelegateExecution superExecution) {
this(processDefinition, variables);
this.superExecution = superExecution;
}
public TenantIdProviderProcessInstanceContext(ProcessDefinition processDefinition, VariableMap variables, DelegateCaseExecution superCaseExecution) {
this(processDefinition, variables);
this.superCaseExecution = superCaseExecution;
}
/**
* @return the process definition of the process instance which is being started
*/
public ProcessDefinition getProcessDefinition() {
return processDefinition;
}
/**
* @return the variables which were passed to the starting process instance
*/
|
public VariableMap getVariables() {
return variables;
}
/**
* @return the super execution. Null if the starting process instance is a root process instance and not started using a call activity.
* If the process instance is started using a call activity, this method returns the execution in the super process
* instance executing the call activity.
*/
public DelegateExecution getSuperExecution() {
return superExecution;
}
/**
* @return the super case execution. Null if the starting process instance is not a sub process instance started using a CMMN case task.
*/
public DelegateCaseExecution getSuperCaseExecution() {
return superCaseExecution;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantIdProviderProcessInstanceContext.java
| 1
|
请完成以下Java代码
|
public UnProcessPickingCandidatesResult execute()
{
final List<PickingCandidate> pickingCandidates = pickingCandidateRepository.getByIds(pickingCandidateIds);
pickingCandidates.forEach(this::assertEligibleForProcessing);
trxManager.runInThreadInheritedTrx(() -> pickingCandidates.forEach(this::processInTrx));
return UnProcessPickingCandidatesResult.builder()
.pickingCandidates(pickingCandidates)
.build();
}
private void assertEligibleForProcessing(final PickingCandidate pickingCandidate)
{
pickingCandidate.assertProcessed();
}
private void processInTrx(@NonNull final PickingCandidate pickingCandidate)
{
if (pickingCandidate.isRejectedToPick())
{
// TODO: impl
throw new AdempiereException("Unprocessing not supported");
}
else if (pickingCandidate.getPickFrom().isPickFromHU())
{
processInTrx_unpackHU(pickingCandidate);
}
else if (pickingCandidate.getPickFrom().isPickFromPickingOrder())
{
// TODO: impl
throw new AdempiereException("Unprocessing not supported");
}
else
{
throw new AdempiereException("Unknown " + pickingCandidate.getPickFrom());
}
}
private void processInTrx_unpackHU(@NonNull final PickingCandidate pickingCandidate)
{
final HuId packedToHUId = pickingCandidate.getPackedToHuId();
|
if (packedToHUId == null)
{
return;
}
final I_M_HU packedToHU = handlingUnitsBL.getById(packedToHUId);
if (handlingUnitsBL.isDestroyed(packedToHU))
{
// shall not happen
return;
}
if (X_M_HU.HUSTATUS_Picked.equals(packedToHU.getHUStatus()))
{
handlingUnitsBL.setHUStatus(packedToHU, PlainContextAware.newWithThreadInheritedTrx(), X_M_HU.HUSTATUS_Active);
}
pickingCandidate.changeStatusToDraft();
pickingCandidateRepository.save(pickingCandidate);
huShipmentScheduleBL.deleteByTopLevelHUAndShipmentScheduleId(packedToHUId, pickingCandidate.getShipmentScheduleId());
}
@NonNull
private ProductId getProductId(final PickingCandidate pickingCandidate)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(pickingCandidate.getShipmentScheduleId());
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
}
private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return shipmentSchedulesCache.computeIfAbsent(shipmentScheduleId, huShipmentScheduleBL::getById);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\UnProcessPickingCandidatesCommand.java
| 1
|
请完成以下Java代码
|
public class MultiValuePart {
protected final String name;
protected final Object body;
protected final String filename;
protected final String mimeType;
protected MultiValuePart(String name, Object body, String filename) {
this.name = name;
this.body = body;
this.filename = filename;
this.mimeType = null;
}
protected MultiValuePart(String name, Object body, String filename, String mimeType) {
this.name = name;
this.body = body;
this.filename = filename;
this.mimeType = mimeType;
}
public String getName() {
return name;
}
public Object getBody() {
return body;
}
public String getFilename() {
return filename;
|
}
public String getMimeType() {
return mimeType;
}
public static MultiValuePart fromText(String name, String value) {
return new MultiValuePart(name, value, null);
}
public static MultiValuePart fromFile(String name, byte[] value, String filename) {
return new MultiValuePart(name, value, filename);
}
public static MultiValuePart fromFile(String name, byte[] value, String filename, String mimeType) {
return new MultiValuePart(name, value, filename, mimeType);
}
}
|
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\MultiValuePart.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void init() {
LOG.info("init ...");
printService.print("init ...");
printServiceErr.print("init ....");
printService.print(dataService.getData());
printServiceOut.print("init .....");
}
@Override
public String printDefault(String message) {
return printService.print(message);
}
@Override
public String printStdErr(String message) {
return printServiceErr.print(message);
}
@Override
public String printStdOut(String message) {
return printServiceOut.print(message);
}
|
@Override
public String getData() {
return dataService.getData();
}
@Override
public String getDataPrototype() {
return dataServicePrototype.getData();
}
@PreDestroy
public void shutdown() {
LOG.info("##destroy.");
}
}
|
repos\spring-examples-java-17\spring-di\src\main\java\itx\examples\springboot\di\services\ClientServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
@Override
public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public Object getCachedValue() {
return cachedValue;
}
@Override
public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue;
}
// misc methods ///////////////////////////////////////////////////////////////
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("VariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(type != null ? type.getTypeName() : "null");
if (executionId != null) {
sb.append(", executionId=").append(executionId);
}
if (processInstanceId != null) {
|
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
}
if (scopeId != null) {
sb.append(", scopeId=").append(scopeId);
}
if (subScopeId != null) {
sb.append(", subScopeId=").append(subScopeId);
}
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (scopeDefinitionId != null) {
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\VariableInstanceEntityImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public POJOLookupMap getDB()
{
return db;
}
@Override
public I_C_InvoiceLine createInvoiceLine(org.compiere.model.I_C_Invoice invoice)
{
throw new UnsupportedOperationException();
}
@Override
public List<I_C_LandedCost> retrieveLandedCosts(I_C_InvoiceLine invoiceLine, String whereClause, String trxName)
{
throw new UnsupportedOperationException();
}
@Override
public I_C_LandedCost createLandedCost(String trxName)
{
throw new UnsupportedOperationException();
}
@Override
public I_C_InvoiceLine createInvoiceLine(String trxName)
{
throw new UnsupportedOperationException();
}
private List<I_C_AllocationLine> retrieveAllocationLines(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return db.getRecords(I_C_AllocationLine.class, pojo -> {
if (pojo == null)
{
return false;
}
if (pojo.getC_Invoice_ID() != invoice.getC_Invoice_ID())
{
return false;
}
return true;
});
}
private BigDecimal retrieveAllocatedAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
Adempiere.assertUnitTestMode();
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
|
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice))
{
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineAmt = amountAccessor.getValue(line);
if ((null != ah) && (ah.getC_Currency_ID() != invoice.getC_Currency_ID()))
{
final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert(
lineAmt, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
ah.getDateTrx().toInstant(), // ConvDate
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineAmtConv);
}
else
{
sum = sum.add(lineAmt);
}
}
return sum;
}
public BigDecimal retrieveWriteOffAmt(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return retrieveAllocatedAmt(invoice, o -> {
final I_C_AllocationLine line = (I_C_AllocationLine)o;
return line.getWriteOffAmt();
});
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\PlainInvoiceDAO.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static void copyToDbRecord(
@NonNull final HUTraceEvent huTraceRecord,
@NonNull final I_M_HU_Trace dbRecord)
{
if (huTraceRecord.getDocTypeId().isPresent())
{
dbRecord.setC_DocType_ID(huTraceRecord.getDocTypeId().get().getRepoId()); // note that zero means "new", and not "nothing" or null
}
// HU_TraceEvent_ID is not copied to the dbRecord! because the dbRecord is where it always comes from
dbRecord.setAD_Org_ID(OrgId.toRepoIdOrAny(huTraceRecord.getOrgId()));
dbRecord.setDocStatus(huTraceRecord.getDocStatus());
dbRecord.setEventTime(TimeUtil.asTimestamp(huTraceRecord.getEventTime()));
dbRecord.setHUTraceType(huTraceRecord.getType().toString());
dbRecord.setVHU_ID(huTraceRecord.getVhuId().getRepoId());
dbRecord.setM_Product_ID(huTraceRecord.getProductId().getRepoId());
|
dbRecord.setQty(huTraceRecord.getQty().toBigDecimal());
dbRecord.setC_UOM_ID(UomId.toRepoId(huTraceRecord.getQty().getUomId()));
dbRecord.setVHUStatus(huTraceRecord.getVhuStatus());
dbRecord.setM_HU_Trx_Line_ID(huTraceRecord.getHuTrxLineId());
dbRecord.setM_HU_ID(huTraceRecord.getTopLevelHuId().getRepoId());
dbRecord.setVHU_Source_ID(HuId.toRepoId(huTraceRecord.getVhuSourceId()));
dbRecord.setM_InOut_ID(huTraceRecord.getInOutId());
dbRecord.setM_Movement_ID(huTraceRecord.getMovementId());
dbRecord.setM_Inventory_ID(InventoryId.toRepoId(huTraceRecord.getInventoryId()));
dbRecord.setM_ShipmentSchedule_ID(ShipmentScheduleId.toRepoId(huTraceRecord.getShipmentScheduleId()));
dbRecord.setPP_Cost_Collector_ID(huTraceRecord.getPpCostCollectorId());
dbRecord.setPP_Order_ID(huTraceRecord.getPpOrderId());
dbRecord.setLotNumber(huTraceRecord.getLotNumber());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\repository\HuTraceEventToDbRecordUtil.java
| 2
|
请完成以下Java代码
|
public void addDefinition(T definition) {
cache.put(definition.getId(), definition);
}
public T getDefinition(String id) {
return cache.get(id);
}
public void removeDefinitionFromCache(String id) {
cache.remove(id);
}
public void clear() {
cache.clear();
}
public Cache<String, T> getCache() {
return cache;
}
protected abstract AbstractResourceDefinitionManager<T> getManager();
|
protected abstract void checkInvalidDefinitionId(String definitionId);
protected abstract void checkDefinitionFound(String definitionId, T definition);
protected abstract void checkInvalidDefinitionByKey(String definitionKey, T definition);
protected abstract void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, T definition);
protected abstract void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, T definition);
protected abstract void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, T definition);
protected abstract void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, T definition);
protected abstract void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, T definition);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\ResourceDefinitionCache.java
| 1
|
请完成以下Java代码
|
public String getIconName()
{
return iconName;
}
public static PPOrderLineType cast(final IViewRowType type)
{
return (PPOrderLineType)type;
}
public boolean canReceive()
{
return canReceive;
}
public boolean canIssue()
{
return canIssue;
}
public boolean isBOMLine()
{
return this == BOMLine_Component
|| this == BOMLine_Component_Service
|| this == BOMLine_ByCoProduct;
}
public boolean isMainProduct()
{
return this == MainProduct;
}
public boolean isHUOrHUStorage()
{
return this == HU_LU
|| this == HU_TU
|
|| this == HU_VHU
|| this == HU_Storage;
}
public static PPOrderLineType ofHUEditorRowType(final HUEditorRowType huType)
{
final PPOrderLineType type = huType2type.get(huType);
if (type == null)
{
throw new IllegalArgumentException("No type found for " + huType);
}
return type;
}
private static final ImmutableMap<HUEditorRowType, PPOrderLineType> huType2type = Stream.of(values())
.filter(type -> type.huType != null)
.collect(GuavaCollectors.toImmutableMapByKey(type -> type.huType));
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLineType.java
| 1
|
请完成以下Java代码
|
private int getQueueSize(JobExecutorXml jobExecutorXml) {
String queueSize = jobExecutorXml.getProperties().get(JobExecutorXml.QUEUE_SIZE);
if (queueSize == null) {
return DEFAULT_QUEUE_SIZE;
}
return Integer.parseInt(queueSize);
}
private long getKeepAliveTime(JobExecutorXml jobExecutorXml) {
String keepAliveTime = jobExecutorXml.getProperties().get(JobExecutorXml.KEEP_ALIVE_TIME);
if (keepAliveTime == null) {
return DEFAULT_KEEP_ALIVE_TIME_MS;
}
return Long.parseLong(keepAliveTime);
}
|
private int getMaxPoolSize(JobExecutorXml jobExecutorXml) {
String maxPoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.MAX_POOL_SIZE);
if (maxPoolSize == null) {
return DEFAULT_MAX_POOL_SIZE;
}
return Integer.parseInt(maxPoolSize);
}
private int getCorePoolSize(JobExecutorXml jobExecutorXml) {
String corePoolSize = jobExecutorXml.getProperties().get(JobExecutorXml.CORE_POOL_SIZE);
if (corePoolSize == null) {
return DEFAULT_CORE_POOL_SIZE;
}
return Integer.parseInt(corePoolSize);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\jobexecutor\StartManagedThreadPoolStep.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getLicencePic() {
return licencePic;
}
public void setLicencePic(String licencePic) {
this.licencePic = licencePic;
}
public Integer getUserType() {
return userType;
}
|
public void setUserType(Integer userType) {
this.userType = userType;
}
@Override
public String toString() {
return "RegisterReq{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", licencePic='" + licencePic + '\'' +
", userType=" + userType +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\RegisterReq.java
| 2
|
请完成以下Java代码
|
public String showVetList(@RequestParam(defaultValue = "1") int page, Model model) {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for Object-Xml mapping
Vets vets = new Vets();
Page<Vet> paginated = findPaginated(page);
vets.getVetList().addAll(paginated.toList());
return addPaginationModel(page, paginated, model);
}
private String addPaginationModel(int page, Page<Vet> paginated, Model model) {
List<Vet> listVets = paginated.getContent();
model.addAttribute("currentPage", page);
model.addAttribute("totalPages", paginated.getTotalPages());
model.addAttribute("totalItems", paginated.getTotalElements());
model.addAttribute("listVets", listVets);
return "vets/vetList";
}
|
private Page<Vet> findPaginated(int page) {
int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
return vetRepository.findAll(pageable);
}
@GetMapping({ "/vets" })
public @ResponseBody Vets showResourcesVetList() {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for JSon/Object mapping
Vets vets = new Vets();
vets.getVetList().addAll(this.vetRepository.findAll());
return vets;
}
}
|
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\vet\VetController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MscManagedProcessEngine implements Service<ProcessEngine> {
private final static Logger LOGG = Logger.getLogger(MscManagedProcessEngine.class.getName());
protected Supplier<MscRuntimeContainerDelegate> runtimeContainerDelegateSupplier;
/** the process engine managed by this service */
protected ProcessEngine processEngine;
private ServiceController<ManagedReferenceFactory> bindingService;
// for subclasses only
protected MscManagedProcessEngine() {
}
public MscManagedProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
}
@Override
public ProcessEngine getValue() throws IllegalStateException, IllegalArgumentException {
return processEngine;
}
@Override
public void start(StartContext context) throws StartException {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateSupplier.get();
runtimeContainerDelegate.processEngineStarted(processEngine);
createProcessEngineJndiBinding(context);
}
protected void createProcessEngineJndiBinding(StartContext context) {
final ProcessEngineManagedReferenceFactory managedReferenceFactory = new ProcessEngineManagedReferenceFactory(processEngine);
final ServiceName processEngineServiceBindingServiceName = ContextNames.GLOBAL_CONTEXT_SERVICE_NAME
.append(BpmPlatform.APP_JNDI_NAME)
.append(BpmPlatform.MODULE_JNDI_NAME)
.append(processEngine.getName());
final String jndiName = BpmPlatform.JNDI_NAME_PREFIX
+ "/" + BpmPlatform.APP_JNDI_NAME
+ "/" + BpmPlatform.MODULE_JNDI_NAME
+ "/" +processEngine.getName();
// bind process engine service
|
bindingService = BindingUtil.createJndiBindings(context.getChildTarget(), processEngineServiceBindingServiceName, jndiName, managedReferenceFactory);
// log info message
LOGG.info("jndi binding for process engine " + processEngine.getName() + " is " + jndiName);
}
protected void removeProcessEngineJndiBinding() {
bindingService.setMode(Mode.REMOVE);
}
@Override
public void stop(StopContext context) {
MscRuntimeContainerDelegate runtimeContainerDelegate = runtimeContainerDelegateSupplier.get();
runtimeContainerDelegate.processEngineStopped(processEngine);
}
public Supplier<MscRuntimeContainerDelegate> getRuntimeContainerDelegateSupplier() {
return runtimeContainerDelegateSupplier;
}
}
|
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngine.java
| 2
|
请完成以下Java代码
|
private void validateQtyEntered(@NonNull final I_PP_Order_Candidate ppOrderCandidateRecord)
{
final BigDecimal qtyEntered = ppOrderCandidateRecord.getQtyEntered();
final BigDecimal qtyProcessed = ppOrderCandidateRecord.getQtyProcessed();
final String adLanguage = Env.getAD_Language();
if (qtyEntered.compareTo(qtyProcessed) < 0)
{
final String qtyEnteredColumnTrl = msgBL.translatable(I_PP_Order_Candidate.COLUMNNAME_QtyEntered).translate(adLanguage);
final String qtyProcessedColumnTrl = msgBL.translatable(I_PP_Order_Candidate.COLUMNNAME_QtyProcessed).translate(adLanguage);
throw new AdempiereException(MSG_QTY_ENTERED_LOWER_THAN_QTY_PROCESSED,
qtyEnteredColumnTrl,
qtyProcessedColumnTrl)
.appendParametersToMessage()
.setParameter("PP_Order_Candidate_ID", ppOrderCandidateRecord.getPP_Order_Candidate_ID())
.setParameter("QtyProcessed", ppOrderCandidateRecord.getQtyProcessed())
.setParameter("QtyEntered", ppOrderCandidateRecord.getQtyEntered())
.markAsUserValidationError();
}
}
private void validateQtyToProcess(@NonNull final I_PP_Order_Candidate ppOrderCandidateRecord)
{
final BigDecimal qtyEntered = ppOrderCandidateRecord.getQtyEntered();
final BigDecimal qtyProcessed = ppOrderCandidateRecord.getQtyProcessed();
final BigDecimal actualQtyLeftToBeProcessed = qtyEntered.subtract(qtyProcessed);
|
final String adLanguage = Env.getAD_Language();
if (ppOrderCandidateRecord.getQtyToProcess().compareTo(actualQtyLeftToBeProcessed) > 0)
{
final String qtyToProcessColumnTrl = msgBL.translatable(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess).translate(adLanguage);
throw new AdempiereException(MSG_QTY_TO_PROCESS_GREATER_THAN_QTY_LEFT, qtyToProcessColumnTrl)
.appendParametersToMessage()
.setParameter("PP_Order_Candidate_ID", ppOrderCandidateRecord.getPP_Order_Candidate_ID())
.setParameter("PP_Order_Candidate.QtyToProcess", ppOrderCandidateRecord.getQtyToProcess())
.setParameter("PP_Order_Candidate.QtyEntered", ppOrderCandidateRecord.getQtyEntered())
.setParameter("PP_Order_Candidate.QtyProcessed", ppOrderCandidateRecord.getQtyProcessed())
.markAsUserValidationError();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\model\interceptor\PP_Order_Candidate.java
| 1
|
请完成以下Java代码
|
public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutColumnDescriptor.Builder.class);
private String internalName;
private final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupsBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("elementGroups-count", elementGroupsBuilders.size())
.toString();
}
public DocumentLayoutColumnDescriptor build()
{
final DocumentLayoutColumnDescriptor result = new DocumentLayoutColumnDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result;
}
private List<DocumentLayoutElementGroupDescriptor> buildElementGroups()
{
return elementGroupsBuilders
.stream()
.map(DocumentLayoutElementGroupDescriptor.Builder::build)
.filter(this::checkValid)
.collect(GuavaCollectors.toImmutableList());
}
private boolean checkValid(final DocumentLayoutElementGroupDescriptor elementGroup)
{
if(!elementGroup.hasElementLines())
|
{
logger.trace("Skip adding {} to {} because it does not have element line", elementGroup, this);
return false;
}
return true;
}
public Builder setInternalName(String internalName)
{
this.internalName = internalName;
return this;
}
public Builder addElementGroups(@NonNull final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupBuilders)
{
elementGroupsBuilders.addAll(elementGroupBuilders);
return this;
}
public Builder addElementGroup(@NonNull final DocumentLayoutElementGroupDescriptor.Builder elementGroupBuilder)
{
elementGroupsBuilders.add(elementGroupBuilder);
return this;
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementGroupsBuilders.stream().flatMap(DocumentLayoutElementGroupDescriptor.Builder::streamElementBuilders);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutColumnDescriptor.java
| 1
|
请完成以下Java代码
|
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
HashMap<String, Long> longHeaders = new HashMap<>();
for (Map.Entry<String, List<String>> headerEntry : headers.headerSet()) {
long headerSizeInBytes = 0L;
headerSizeInBytes += headerEntry.getKey().getBytes().length;
List<String> values = headerEntry.getValue();
for (String value : values) {
headerSizeInBytes += value.getBytes().length;
}
if (headerSizeInBytes > config.getMaxSize().toBytes()) {
longHeaders.put(headerEntry.getKey(), headerSizeInBytes);
}
}
if (!longHeaders.isEmpty()) {
exchange.getResponse().setStatusCode(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE);
exchange.getResponse()
.getHeaders()
.add(errorHeaderName, getErrorMessage(longHeaders, config.getMaxSize()));
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public String toString() {
return filterToStringCreator(RequestHeaderSizeGatewayFilterFactory.this)
.append("maxSize", config.getMaxSize())
.toString();
}
};
}
private static String getErrorMessage(HashMap<String, Long> longHeaders, DataSize maxSize) {
StringBuilder msg = new StringBuilder(String.format(ERROR_PREFIX, maxSize));
longHeaders
.forEach((header, size) -> msg.append(String.format(ERROR, header, DataSize.of(size, DataUnit.BYTES))));
return msg.toString();
}
|
public static class Config {
private DataSize maxSize = DataSize.ofBytes(16000L);
private @Nullable String errorHeaderName;
public DataSize getMaxSize() {
return maxSize;
}
public void setMaxSize(DataSize maxSize) {
this.maxSize = maxSize;
}
public @Nullable String getErrorHeaderName() {
return errorHeaderName;
}
public void setErrorHeaderName(String errorHeaderName) {
this.errorHeaderName = errorHeaderName;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestHeaderSizeGatewayFilterFactory.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.