instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static IPricingResult calculatePricingResult(@NonNull final org.compiere.model.I_M_InOutLine fromInOutLine) { final IInOutBL inOutBL = Services.get(IInOutBL.class); return inOutBL.getProductPrice(fromInOutLine); } @Nullable public static PriceAndTax calculatePriceAndTaxAndUpdate( @NonNull final I_C_Invoice_Candidate icRecord, final org.compiere.model.I_M_InOutLine fromInOutLine) { try { final PriceAndTax priceAndTax = calculatePriceAndTax(icRecord, fromInOutLine); IInvoiceCandInvalidUpdater.updatePriceAndTax(icRecord, priceAndTax); return priceAndTax; } catch (final Exception e) { if (icRecord.getC_Tax_ID() <= 0) {
icRecord.setC_Tax_ID(Tax.C_TAX_ID_NO_TAX_FOUND); // make sure that we will be able to save the icRecord } setError(icRecord, e); return null; } } private static void setError( @NonNull final I_C_Invoice_Candidate ic, @NonNull final Exception ex) { logger.debug("Set IsInDispute=true, because an error occured"); ic.setIsInDispute(true); // 07193 - Mark's request final boolean askForDeleteRegeneration = false; // default; don't ask for re-generation final I_AD_Note note = null; // we don't have a note Services.get(IInvoiceCandBL.class).setError(ic, ex.getLocalizedMessage(), note, askForDeleteRegeneration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOutLine_Handler.java
1
请完成以下Java代码
public void deleteAll() { getDbEntityManager().delete(MeterLogEntity.class, DELETE_ALL_METER, null); } public void deleteByTimestampAndReporter(Date timestamp, String reporter) { Map<String, Object> parameters = new HashMap<>(); if (timestamp != null) { parameters.put("milliseconds", timestamp.getTime()); } parameters.put("reporter", reporter); getDbEntityManager().delete(MeterLogEntity.class, DELETE_ALL_METER_BY_TIMESTAMP_AND_REPORTER, parameters); } // TASK METER LOG public long findUniqueTaskWorkerCount(Date startTime, Date endTime) { Map<String, Object> parameters = new HashMap<>(); parameters.put("startTime", startTime); parameters.put("endTime", endTime); return (Long) getDbEntityManager().selectOne(SELECT_UNIQUE_TASK_WORKER, parameters); } public void deleteTaskMetricsByTimestamp(Date timestamp) { Map<String, Object> parameters = Collections.singletonMap("timestamp", timestamp); getDbEntityManager().delete(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_TIMESTAMP, parameters); } public void deleteTaskMetricsById(List<String> taskMetricIds) { getDbEntityManager().deletePreserveOrder(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_IDS, taskMetricIds); } public DbOperation deleteTaskMetricsByRemovalTime(Date currentTimestamp, Integer timeToLive, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); // data inserted prior to now minus timeToLive-days can be removed Date removalTime = Date.from(currentTimestamp.toInstant().minus(timeToLive, ChronoUnit.DAYS)); parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(TaskMeterLogEntity.class, DELETE_TASK_METER_BY_REMOVAL_TIME, new ListQueryParameterObject(parameters, 0, batchSize)); } @SuppressWarnings("unchecked") public List<String> findTaskMetricsForCleanup(int batchSize, Integer timeToLive, int minuteFrom, int minuteTo) { Map<String, Object> queryParameters = new HashMap<>(); queryParameters.put("currentTimestamp", ClockUtil.getCurrentTime()); queryParameters.put("timeToLive", timeToLive); if (minuteTo - minuteFrom + 1 < 60) { queryParameters.put("minuteFrom", minuteFrom); queryParameters.put("minuteTo", minuteTo); } ListQueryParameterObject parameterObject = new ListQueryParameterObject(queryParameters, 0, batchSize); parameterObject.getOrderingProperties().add(new QueryOrderingProperty(new QueryPropertyImpl("TIMESTAMP_"), Direction.ASCENDING)); return (List<String>) getDbEntityManager().selectList(SELECT_TASK_METER_FOR_CLEANUP, parameterObject); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogManager.java
1
请完成以下Java代码
public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the models */ public List<CarModel> getModels() { return models; } /** * @param models the models to set */ public void setModels(List<CarModel> models) { this.models = models; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((models == null) ? 0 : models.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) {
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CarMaker other = (CarMaker) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (models == null) { if (other.models != null) return false; } else if (!models.equals(other.models)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarMaker.java
1
请完成以下Java代码
Mono<Void> delete(String sessionId) { String sessionIndexesKey = getSessionIndexesKey(sessionId); return this.sessionRedisOperations.opsForSet() .members(sessionIndexesKey) .flatMap((indexKey) -> removeSessionFromIndex((String) indexKey, sessionId)) .then(this.sessionRedisOperations.delete(sessionIndexesKey)) .then(); } private Mono<Void> removeSessionFromIndex(String indexKey, String sessionId) { return this.sessionRedisOperations.opsForSet().remove(indexKey, sessionId).then(); } Mono<Map<String, String>> getIndexes(String sessionId) { String sessionIndexesKey = getSessionIndexesKey(sessionId); return this.sessionRedisOperations.opsForSet() .members(sessionIndexesKey) .cast(String.class) .collectMap((indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[0], (indexKey) -> indexKey.substring(this.indexKeyPrefix.length()).split(":")[1]); } Flux<String> getSessionIds(String indexName, String indexValue) { String indexKey = getIndexKey(indexName, indexValue); return this.sessionRedisOperations.opsForSet().members(indexKey).cast(String.class); }
private void updateIndexKeyPrefix() { this.indexKeyPrefix = this.namespace + "sessions:index:"; } private String getSessionIndexesKey(String sessionId) { return this.namespace + "sessions:" + sessionId + ":idx"; } private String getIndexKey(String indexName, String indexValue) { return this.indexKeyPrefix + indexName + ":" + indexValue; } void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be empty"); this.namespace = namespace; updateIndexKeyPrefix(); } void setIndexResolver(IndexResolver<Session> indexResolver) { Assert.notNull(indexResolver, "indexResolver cannot be null"); this.indexResolver = indexResolver; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionIndexer.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class SlicePagingRepositoryImplementation<T> { public static final String NULL_ENTITY = "Entity cannot be null"; public static final String NULL_PAGEABLE = "Pageable cannot be null"; @Autowired private EntityManager entityManager; private final Class<T> entityClass; public SlicePagingRepositoryImplementation(Class<T> entityClass) { Objects.requireNonNull(entityClass, NULL_ENTITY); this.entityClass = entityClass; } public Slice<T> findAll(Pageable pageable) { Objects.requireNonNull(pageable, NULL_PAGEABLE); return findAll(pageable, entityClass); }
private Slice<T> findAll(Pageable pageable, Class<T> entityClass) { final String sql = "SELECT e FROM " + entityClass.getSimpleName() + " e"; TypedQuery<T> query = entityManager.createQuery(sql, entityClass); return this.readSlice(query, pageable); } private Slice<T> readSlice(final TypedQuery<T> query, final Pageable pageable) { query.setFirstResult((int) pageable.getOffset()); query.setMaxResults(pageable.getPageSize() + 1); final List<T> content = query.getResultList(); boolean hasNext = content.size() == (pageable.getPageSize() + 1); if (hasNext) { content.remove(content.size() - 1); } return new SliceImpl<>(content, pageable, hasNext); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSliceAllSimpleSql\src\main\java\com\bookstore\repository\impl\SlicePagingRepositoryImplementation.java
2
请完成以下Java代码
public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) public void setSuspended(Boolean suspended) { this.suspended = suspended; } @CamundaQueryParam(value="createdBy") public void setCreateUserId(String userId) { this.userId = userId; } @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } @CamundaQueryParam(value = "withFailures", converter = BooleanConverter.class) public void setWithFailures(final Boolean withFailures) { this.withFailures = withFailures; } @CamundaQueryParam(value = "withoutFailures", converter = BooleanConverter.class) public void setWithoutFailures(final Boolean withoutFailures) { this.withoutFailures = withoutFailures; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected BatchStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchStatisticsQuery(); } protected void applyFilters(BatchStatisticsQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(suspended)) {
query.suspended(); } if (FALSE.equals(suspended)) { query.active(); } if (userId != null) { query.createdBy(userId); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (TRUE.equals(withFailures)) { query.withFailures(); } if (TRUE.equals(withoutFailures)) { query.withoutFailures(); } } protected void applySortBy(BatchStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } else if (sortBy.equals(SORT_BY_START_TIME_VALUE)) { query.orderByStartTime(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchStatisticsQueryDto.java
1
请完成以下Java代码
public void beforeSave(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateWorkDates(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkStart, skipIfCopying = true) public void onDateWorkStart(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkStart(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DateWorkComplete, skipIfCopying = true) public void onDateWorkComplete(final I_C_RfQ rfq) { final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDateWorkComplete(workDatesAware); } @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_DeliveryDays, skipIfCopying = true) public void onDeliveryDays(final I_C_RfQ rfq) { if (InterfaceWrapperHelper.isNull(rfq, I_C_RfQ.COLUMNNAME_DeliveryDays)) { return; } final IRfQWorkDatesAware workDatesAware = InterfaceWrapperHelper.create(rfq, IRfQWorkDatesAware.class); RfQWorkDatesUtil.updateFromDeliveryDays(workDatesAware);
} @CalloutMethod(columnNames = I_C_RfQ.COLUMNNAME_C_RfQ_Topic_ID, skipIfCopying = true) public void onC_RfQTopic(final I_C_RfQ rfq) { final I_C_RfQ_Topic rfqTopic = rfq.getC_RfQ_Topic(); if (rfqTopic == null) { return; } final String rfqTypeDefault = rfqTopic.getRfQType(); if (rfqTypeDefault != null) { rfq.setRfQType(rfqTypeDefault); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQ.java
1
请完成以下Java代码
public Integer getHelpCount() { return helpCount; } public void setHelpCount(Integer helpCount) { this.helpCount = helpCount; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", icon=").append(icon); sb.append(", helpCount=").append(helpCount); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsHelpCategory.java
1
请完成以下Java代码
public boolean isGenerateComments() { return true; } @Override public I_AD_Migration getMigration(String key) { final Properties ctx = Env.getCtx(); final Integer migrationId = migrationsMap.get(key); if (migrationId == null || migrationId <= 0) { return null; } I_AD_Migration migration = migrationsCache.get(migrationId); if (migration != null) { return migration; } // We have the ID in out map, but cache expired, which means that maybe somebody deleted this record
// Trying to reload migration = Services.get(IMigrationDAO.class).retrieveMigrationOrNull(ctx, migrationId); if (migration != null) { putMigration(key, migration); return migration; } return migration; } @Override public void putMigration(String key, I_AD_Migration migration) { migrationsMap.put(key, migration.getAD_Migration_ID()); migrationsCache.put(migration.getAD_Migration_ID(), migration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\SessionMigrationLoggerContext.java
1
请在Spring Boot框架中完成以下Java代码
class ReflectionWrapper { private final Class<?> type; private final Object instance; ReflectionWrapper(String type, Object instance) { this.type = findClass(instance.getClass().getClassLoader(), type); this.instance = this.type.cast(instance); } protected final Object getInstance() { return this.instance; } @Override public String toString() { return this.instance.toString(); } protected Class<?> findClass(String name) { return findClass(getInstance().getClass().getClassLoader(), name); } protected Method findMethod(String name, Class<?>... parameterTypes) { return findMethod(this.type, name, parameterTypes); }
protected static Class<?> findClass(ClassLoader classLoader, String name) { try { return Class.forName(name, false, classLoader); } catch (ClassNotFoundException ex) { throw new IllegalStateException(ex); } } protected static Method findMethod(Class<?> type, String name, Class<?>... parameterTypes) { try { return type.getMethod(name, parameterTypes); } catch (Exception ex) { throw new IllegalStateException(ex); } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\ReflectionWrapper.java
2
请完成以下Java代码
public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * Role AD_Reference_ID=541254 * Reference name: Role */ public static final int ROLE_AD_Reference_ID=541254;
/** Main Producer = MP */ public static final String ROLE_MainProducer = "MP"; /** Hostpital = HO */ public static final String ROLE_Hostpital = "HO"; /** Physician Doctor = PD */ public static final String ROLE_PhysicianDoctor = "PD"; /** General Practitioner = GP */ public static final String ROLE_GeneralPractitioner = "GP"; /** Health Insurance = HI */ public static final String ROLE_HealthInsurance = "HI"; /** Nursing Home = NH */ public static final String ROLE_NursingHome = "NH"; /** Caregiver = CG */ public static final String ROLE_Caregiver = "CG"; /** Preferred Pharmacy = PP */ public static final String ROLE_PreferredPharmacy = "PP"; /** Nursing Service = NS */ public static final String ROLE_NursingService = "NS"; /** Payer = PA */ public static final String ROLE_Payer = "PA"; /** Payer = PA */ public static final String ROLE_Pharmacy = "PH"; @Override public void setRole (final @Nullable java.lang.String Role) { set_Value (COLUMNNAME_Role, Role); } @Override public java.lang.String getRole() { return get_ValueAsString(COLUMNNAME_Role); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java
1
请在Spring Boot框架中完成以下Java代码
private I_AD_User getConfiguredESUser() { final UserId configuredUserId = UserId.ofRepoId(resolveAuthRelatedSysConfig(SYS_CONFIG_EXTERNAL_SYSTEM_AD_USER_ID)); return userDAO.getById(configuredUserId); } @NonNull private Integer resolveAuthRelatedSysConfig(@NonNull final String sysConfig) { final String sysConfigValueAsString = sysConfigBL.getValue(sysConfig); if (Check.isNotBlank(sysConfigValueAsString)) { return Integer.parseInt(sysConfigValueAsString); } throw ESMissingConfigurationException.builder() .adMessageKey(EXTERNAL_SYSTEM_AUTH_NOTIFICATION_CONTENT_SYSCONFIG_NOT_FOUND) .params(ImmutableList.of(sysConfig)) .build();
} @NonNull private static JsonExternalSystemMessage buildJsonExternalSystemMessage(@NonNull final String authToken) throws JsonProcessingException { final JsonExternalSystemMessagePayload payload = JsonExternalSystemMessagePayload.builder() .authToken(authToken) .build(); return JsonExternalSystemMessage.builder() .type(JsonExternalSystemMessageType.AUTHORIZATION_REPLY) .payload(JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(payload)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\authorization\ExternalSystemAuthorizationService.java
2
请完成以下Java代码
public void setCustomer_Group_ID (final int Customer_Group_ID) { if (Customer_Group_ID < 1) set_Value (COLUMNNAME_Customer_Group_ID, null); else set_Value (COLUMNNAME_Customer_Group_ID, Customer_Group_ID); } @Override public int getCustomer_Group_ID() { return get_ValueAsInt(COLUMNNAME_Customer_Group_ID); } @Override public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup) { set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup); } @Override public boolean isExcludeBPGroup() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup); } @Override public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory) { set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory); } @Override public boolean isExcludeProductCategory() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
} @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); } @Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
1
请完成以下Java代码
protected void writeHeaders() { if (isDisableOnResponseCommitted()) { return; } HeaderWriterFilter.this.writeHeaders(this.request, getHttpResponse()); } private HttpServletResponse getHttpResponse() { return (HttpServletResponse) getResponse(); } } static class HeaderWriterRequest extends HttpServletRequestWrapper { private final HeaderWriterResponse response; HeaderWriterRequest(HttpServletRequest request, HeaderWriterResponse response) { super(request); this.response = response; } @Override public RequestDispatcher getRequestDispatcher(String path) { return new HeaderWriterRequestDispatcher(super.getRequestDispatcher(path), this.response); } } static class HeaderWriterRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate;
private final HeaderWriterResponse response; HeaderWriterRequestDispatcher(RequestDispatcher delegate, HeaderWriterResponse response) { this.delegate = delegate; this.response = response; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.response.onResponseCommitted(); this.delegate.include(request, response); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\HeaderWriterFilter.java
1
请完成以下Java代码
public Signal newInstance(ModelTypeInstanceContext instanceContext) { return new SignalImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF) .qNameAttributeReference(ItemDefinition.class) .build(); typeBuilder.build(); } public SignalImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this);
} public void setName(String name) { nameAttribute.setValue(this, name); } public ItemDefinition getStructure() { return structureRefAttribute.getReferenceTargetElement(this); } public void setStructure(ItemDefinition structure) { structureRefAttribute.setReferenceTargetElement(this, structure); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SignalImpl.java
1
请完成以下Java代码
public class TaskImpl extends ActivityImpl implements Task { /** camunda extensions */ protected static Attribute<Boolean> camundaAsyncAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Task.class, BPMN_ELEMENT_TASK) .namespaceUri(BPMN20_NS) .extendsType(Activity.class) .instanceProvider(new ModelTypeInstanceProvider<Task>() { public Task newInstance(ModelTypeInstanceContext instanceContext) { return new TaskImpl(instanceContext); } }); /** camunda extensions */ camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC) .namespace(CAMUNDA_NS) .defaultValue(false) .build(); typeBuilder.build(); } public TaskImpl(ModelTypeInstanceContext context) { super(context); } @SuppressWarnings("rawtypes") public AbstractTaskBuilder builder() { throw new ModelTypeException("No builder implemented."); } /** camunda extensions */ /** * @deprecated use isCamundaAsyncBefore() instead.
*/ @Deprecated public boolean isCamundaAsync() { return camundaAsyncAttribute.getValue(this); } /** * @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead. */ @Deprecated public void setCamundaAsync(boolean isCamundaAsync) { camundaAsyncAttribute.setValue(this, isCamundaAsync); } public BpmnShape getDiagramElement() { return (BpmnShape) super.getDiagramElement(); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TaskImpl.java
1
请完成以下Java代码
private String forwarded(URI uri, @Nullable String hostHeader) { if (StringUtils.hasText(hostHeader)) { return "host=" + hostHeader; } if ("http".equals(uri.getScheme())) { return "host=" + uri.getHost(); } return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme()); } private @Nullable Publisher<?> body() { Publisher<?> body = this.body; if (body != null) { return body; } body = getRequestBody(); hasBody = true; // even if it's null return body; } /** * Search for the request body if it was already deserialized using * <code>@RequestBody</code>. If it is not found then deserialize it in the same way * that it would have been for a <code>@RequestBody</code>. * @return the request body */ private @Nullable Mono<Object> getRequestBody() { for (String key : bindingContext.getModel().asMap().keySet()) { if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key); Object target = result.getTarget(); if (target != null) { return Mono.just(target); } } } return null; } protected static class BodyGrabber { public Publisher<Object> body(@RequestBody Publisher<Object> body) { return body; } } protected static class BodySender { @ResponseBody public @Nullable Publisher<Object> body() { return null; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java
1
请完成以下Java代码
private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(simpleReader) .writer(fileItemWriter()) .build(); } private FlatFileItemWriter<TestData> fileItemWriter() throws Exception { FlatFileItemWriter<TestData> writer = new FlatFileItemWriter<>(); FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file"); Path path = Paths.get(file.getPath()); if (!Files.exists(path)) { Files.createFile(path); } writer.setResource(file); // 设置目标文件路径 // 把读到的每个TestData对象转换为JSON字符串
LineAggregator<TestData> aggregator = item -> { try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(item); } catch (JsonProcessingException e) { e.printStackTrace(); } return ""; }; writer.setLineAggregator(aggregator); writer.afterPropertiesSet(); return writer; } }
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\FileItemWriterDemo.java
1
请在Spring Boot框架中完成以下Java代码
public final class SupplierClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private final Supplier<? extends ClientRegistrationRepository> repositorySupplier; /** * Constructs an {@code SupplierClientRegistrationRepository} using the provided * parameters. * @param repositorySupplier the client registration repository supplier */ public <T extends ClientRegistrationRepository & Iterable<ClientRegistration>> SupplierClientRegistrationRepository( Supplier<T> repositorySupplier) { Assert.notNull(repositorySupplier, "repositorySupplier cannot be null"); this.repositorySupplier = SingletonSupplier.of(repositorySupplier); } @Override
public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return this.repositorySupplier.get().findByRegistrationId(registrationId); } /** * Returns an {@code Iterator} of {@link ClientRegistration}. * @return an {@code Iterator<ClientRegistration>} */ @Override public Iterator<ClientRegistration> iterator() { return ((Iterable<ClientRegistration>) this.repositorySupplier.get()).iterator(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\SupplierClientRegistrationRepository.java
2
请在Spring Boot框架中完成以下Java代码
private ProductionDetail createProductionDetailForPPOrder( @NonNull final PPOrderCreatedEvent ppOrderEvent) { final PPOrder ppOrder = ppOrderEvent.getPpOrder(); return ProductionDetail.builder() .advised(Flag.FALSE_DONT_UPDATE) .pickDirectlyIfFeasible(Flag.of(ppOrderEvent.isDirectlyPickIfFeasible())) .qty(ppOrder.getPpOrderData().getQtyRequired()) .plantId(ppOrder.getPpOrderData().getPlantId()) .workstationId(ppOrder.getPpOrderData().getWorkstationId()) .productPlanningId(ppOrder.getPpOrderData().getProductPlanningId()) .ppOrderRef(PPOrderRef.ofPPOrderId(ppOrder.getPpOrderId())) .ppOrderDocStatus(ppOrder.getDocStatus()) .build(); } @NonNull private Optional<DemandDetail> retrieveDemandDetail(@NonNull final PPOrderData ppOrderData) { if (ppOrderData.getShipmentScheduleId() <= 0) { return Optional.empty();
} final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery. ofShipmentScheduleId(ppOrderData.getShipmentScheduleId()); final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.builder() .productId(ppOrderData.getProductDescriptor().getProductId()) .warehouseId(ppOrderData.getWarehouseId()) .build(); final CandidatesQuery candidatesQuery = CandidatesQuery.builder() .type(CandidateType.DEMAND) .materialDescriptorQuery(materialDescriptorQuery) .demandDetailsQuery(demandDetailsQuery) .build(); return candidateRepositoryRetrieval.retrieveLatestMatch(candidatesQuery) .map(Candidate::getDemandDetail); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderCreatedHandler.java
2
请在Spring Boot框架中完成以下Java代码
private static class ForecastHeaderKey { public static final String IMPORT_ORDER_BY = I_I_Forecast.COLUMNNAME_Name + ',' + I_I_Forecast.COLUMNNAME_DatePromised + ',' + I_I_Forecast.COLUMNNAME_BPValue + ',' + I_I_Forecast.COLUMNNAME_WarehouseValue + ',' + I_I_Forecast.COLUMNNAME_PriceList + ',' + I_I_Forecast.COLUMNNAME_ProductValue; @NonNull String name; @NonNull WarehouseId warehouseId; @Nullable PriceListId priceListId; @Nullable BPartnerId bpartnerId; @Nullable String externalId; @NonNull LocalDate datePromisedDay; public static ForecastHeaderKey of(final I_I_Forecast importRecord)
{ return ForecastHeaderKey.builder() .name(StringUtils.trimBlankToOptional(importRecord.getName()).orElseThrow(() -> new FillMandatoryException("Name"))) .warehouseId(WarehouseId.ofRepoId(importRecord.getM_Warehouse_ID())) .priceListId(PriceListId.ofRepoIdOrNull(importRecord.getM_PriceList_ID())) .bpartnerId(BPartnerId.ofRepoIdOrNull(importRecord.getC_BPartner_ID())) .externalId(StringUtils.trimBlankToNull(importRecord.getExternalId())) .datePromisedDay(importRecord.getDatePromised().toLocalDateTime().toLocalDate()) .build(); } } public static final class ForecastImportContext { @Nullable ForecastId forecastId; @Nullable ForecastImportProcess.ForecastHeaderKey forecastHeaderKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impexp\ForecastImportProcess.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(_id, firstName, lastName, email, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Users {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Users.java
2
请在Spring Boot框架中完成以下Java代码
public class CompositeItemProcessorDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private ListItemReader<TestData> simpleReader; @Autowired private TestDataFilterItemProcessor testDataFilterItemProcessor; @Autowired private TestDataTransformItemPorcessor testDataTransformItemPorcessor; @Bean public Job compositeItemProcessorJob() { return jobBuilderFactory.get("compositeItemProcessorJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2)
.reader(simpleReader) .processor(compositeItemProcessor()) .writer(list -> list.forEach(System.out::println)) .build(); } // CompositeItemProcessor组合多种中间处理器 private CompositeItemProcessor<TestData, TestData> compositeItemProcessor() { CompositeItemProcessor<TestData, TestData> processor = new CompositeItemProcessor<>(); List<ItemProcessor<TestData, TestData>> processors = Arrays.asList(testDataFilterItemProcessor, testDataTransformItemPorcessor); // 代理两个processor processor.setDelegates(processors); return processor; } }
repos\SpringAll-master\70.spring-batch-itemprocessor\src\main\java\cc\mrbird\batch\entity\job\CompositeItemProcessorDemo.java
2
请完成以下Java代码
public org.compiere.model.I_M_InventoryLine getM_InventoryLine() { return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class); } @Override public void setM_InventoryLine(org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } /** Set Inventur-Position. @param M_InventoryLine_ID Unique line in an Inventory document */ @Override public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Inventur-Position. @return Unique line in an Inventory document */ @Override public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_InventoryLineMA. @param M_InventoryLineMA_ID M_InventoryLineMA */ @Override public void setM_InventoryLineMA_ID (int M_InventoryLineMA_ID) { if (M_InventoryLineMA_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, Integer.valueOf(M_InventoryLineMA_ID)); } /** Get M_InventoryLineMA. @return M_InventoryLineMA */ @Override public int getM_InventoryLineMA_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLineMA_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bewegungs-Menge. @param MovementQty Quantity of a product moved. */ @Override public void setMovementQty (java.math.BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Bewegungs-Menge. @return Quantity of a product moved. */ @Override public java.math.BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLineMA.java
1
请完成以下Java代码
public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); } /** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID)
{ if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
1
请完成以下Java代码
private WarehouseId findPickingWarehouseId(@NonNull final I_C_Order order) { if (!order.isSOTrx()) { return null; } final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(order.getC_BPartner_ID()); if (bpartnerId == null) { return null; } final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class); final I_C_BPartner bp = bpartnersRepo.getById(bpartnerId); if (!bp.isCustomer()) { return null; }
final WarehouseId customerWarehouseId = WarehouseId.ofRepoIdOrNull(bp.getM_Warehouse_ID()); if (customerWarehouseId != null && isPickingWarehouse(customerWarehouseId)) { return customerWarehouseId; } // if order is a purchase order, return null return null; } private boolean isPickingWarehouse(final WarehouseId warehouseId) { final IWarehouseDAO warehousesRepo = Services.get(IWarehouseDAO.class); final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId); return warehouse.isPickingWarehouse(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\warehouse\spi\impl\WarehouseAdvisor.java
1
请完成以下Java代码
public class DictionaryUtil { /** * 给某个字典排序 * @param path * @return */ public static boolean sortDictionary(String path) { try { BufferedReader br = new BufferedReader(new InputStreamReader(IOUtil.newInputStream(path), "UTF-8")); TreeMap<String, String> map = new TreeMap<String, String>(); String line; while ((line = br.readLine()) != null) { String[] param = line.split("\\s"); map.put(param[0], line);
} br.close(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8")); for (Map.Entry<String, String> entry : map.entrySet()) { bw.write(entry.getValue()); bw.newLine(); } bw.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\util\DictionaryUtil.java
1
请完成以下Java代码
public void doStop() { // nothing } class DispatchStartMessageDeployedEvents implements Command<Void> { private final List<StartMessageDeployedEvent> messageDeployedEvents; public DispatchStartMessageDeployedEvents(List<StartMessageDeployedEvent> messageDeployedEvents) { this.messageDeployedEvents = messageDeployedEvents; } public Void execute(CommandContext commandContext) { for (ProcessRuntimeEventListener<StartMessageDeployedEvent> listener : listeners) { messageDeployedEvents.stream().forEach(listener::onEvent); } return null; } } static class FindStartMessageEventSubscriptions implements Command<List<MessageEventSubscriptionEntity>> { private static final String MESSAGE = "message"; private final String processDefinitionId; public FindStartMessageEventSubscriptions(String processDefinitionId) {
this.processDefinitionId = processDefinitionId; } public List<MessageEventSubscriptionEntity> execute(CommandContext commandContext) { return new EventSubscriptionQueryImpl(commandContext) .eventType(MESSAGE) .configuration(processDefinitionId) .list() .stream() .map(MessageEventSubscriptionEntity.class::cast) .filter(it -> it.getProcessInstanceId() == null) .collect(Collectors.toList()); } } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\StartMessageDeployedEventProducer.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getProtocolHeader() { return this.protocolHeader; } public void setProtocolHeader(@Nullable String protocolHeader) { this.protocolHeader = protocolHeader; } public String getProtocolHeaderHttpsValue() { return this.protocolHeaderHttpsValue; } public String getHostHeader() { return this.hostHeader; } public void setHostHeader(String hostHeader) { this.hostHeader = hostHeader; } public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } public String getPortHeader() { return this.portHeader; } public void setPortHeader(String portHeader) { this.portHeader = portHeader; } public @Nullable String getRemoteIpHeader() { return this.remoteIpHeader; } public void setRemoteIpHeader(@Nullable String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } public @Nullable String getTrustedProxies() { return this.trustedProxies; } public void setTrustedProxies(@Nullable String trustedProxies) { this.trustedProxies = trustedProxies; }
} /** * When to use APR. */ public enum UseApr { /** * Always use APR and fail if it's not available. */ ALWAYS, /** * Use APR if it is available. */ WHEN_AVAILABLE, /** * Never use APR. */ NEVER } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
2
请完成以下Java代码
private static String unsignedDivide(String a, String b) { validateUnsignedBinaryString(a); validateUnsignedBinaryString(b); if (compareBinaryStrings(b, a) > 0) { return "0"; } // Remove leading zeros a = a.replaceFirst("^0+(?!$)", ""); b = b.replaceFirst("^0+(?!$)", ""); if (b.equals("0")) { throw new ArithmeticException("Division by zero is not allowed"); } StringBuilder result = new StringBuilder(a.length()); String remainder = ""; // Iterate through each bit of the dividend "a" from MSB to LSB for (int i = 0; i < a.length(); i++) { if (result.length() == 0) { // Initialize result and remainder if not yet done if (compareBinaryStrings(a.substring(0, i + 1), b) >= 0) { result.append('1'); remainder = unsignedSubtract(a.substring(0, i + 1), b); } } else { // Concatenate the current bit of "a" to the remainder remainder += a.charAt(i); // Compare the current remainder with the divisor "b" if (compareBinaryStrings(remainder, b) >= 0) { // If remainder is greater than or equal to divisor, append '1' to result result.append('1'); // Subtract divisor "b" from remainder remainder = unsignedSubtract(remainder, b); } else { // If remainder is less than divisor, append '0' to result result.append('0'); } } } return result.toString(); } private static String removePlusMinus(String s) { if (s == null || s.isEmpty()) { throw new IllegalArgumentException("The string cannot be null or empty"); }
if (s.startsWith("+") || s.startsWith("-")) { return s.substring(1); } return s; } private static boolean isPositive(String s) { if (s == null || s.isEmpty()) { throw new IllegalArgumentException("String cannot be null or empty"); } char firstChar = s.charAt(0); if (firstChar == '+' || firstChar == '0' || firstChar == '1') { return true; } else if (firstChar == '-') { return false; } else { throw new IllegalArgumentException("String does not start with a valid character"); } } }
repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\arbitrarylengthbinaryintegers\BinaryStringOperations.java
1
请完成以下Java代码
public java.lang.String getHostKey() { return (java.lang.String)get_Value(COLUMNNAME_HostKey); } /** * Status AD_Reference_ID=540384 * Reference name: C_Print_Job_Instructions_Status */ public static final int STATUS_AD_Reference_ID=540384; /** Pending = P */ public static final String STATUS_Pending = "P"; /** Send = S */ public static final String STATUS_Send = "S"; /** Done = D */ public static final String STATUS_Done = "D";
/** Error = E */ public static final String STATUS_Error = "E"; @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions.java
1
请完成以下Java代码
public boolean isEmpty() {return selectionId == null && (ids == null || ids.isEmpty());} public boolean isDatabaseSelection() { return selectionId != null; } public interface CaseMapper { void empty(); void fixedSet(@NonNull ImmutableSet<InvoiceCandidateId> ids); void selectionId(@NonNull PInstanceId selectionId); }
public void apply(@NonNull final CaseMapper mapper) { if (selectionId != null) { mapper.selectionId(selectionId); } else if (ids != null && !ids.isEmpty()) { mapper.fixedSet(ids); } else { mapper.empty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\InvoiceCandidateIdsSelection.java
1
请完成以下Java代码
public int getAD_Column_ID() { return AD_Column_ID; } /** * Get AD_Image_ID * @return image */ public int getAD_Image_ID() { return AD_Image_ID; } /** * Get AD_Color_ID * @return color */ public int getAD_Color_ID() { return AD_Color_ID; } /** * Get PA_Goal_ID * @return goal */ public int getPA_Goal_ID() { return PA_Goal_ID; } /*************************************************************************/ /** * Init Workbench Windows * @return true if initilized */ private boolean initDesktopWorkbenches() { String sql = "SELECT AD_Workbench_ID " + "FROM AD_DesktopWorkbench " + "WHERE AD_Desktop_ID=? AND IsActive='Y' " + "ORDER BY SeqNo"; try { PreparedStatement pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, AD_Desktop_ID); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int AD_Workbench_ID = rs.getInt(1); m_workbenches.add (new Integer(AD_Workbench_ID)); }
rs.close(); pstmt.close(); } catch (SQLException e) { log.error("MWorkbench.initDesktopWorkbenches", e); return false; } return true; } // initDesktopWorkbenches /** * Get Window Count * @return no of windows */ public int getWindowCount() { return m_workbenches.size(); } // getWindowCount /** * Get AD_Workbench_ID of index * @param index index * @return -1 if not valid */ public int getAD_Workbench_ID (int index) { if (index < 0 || index > m_workbenches.size()) return -1; Integer id = (Integer)m_workbenches.get(index); return id.intValue(); } // getAD_Workbench_ID } // MDesktop
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDesktop.java
1
请在Spring Boot框架中完成以下Java代码
public void run() { deferredResult.setErrorResult( ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred.")); } }); ForkJoinPool.commonPool().submit(() -> { LOG.info("Processing in separate thread"); try { Thread.sleep(600l); deferredResult.setResult(ResponseEntity.ok("ok")); } catch (InterruptedException e) { LOG.info("Request processing interrupted"); deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("INTERNAL_SERVER_ERROR occurred.")); } }); LOG.info("servlet thread freed"); return deferredResult; }
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) { DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(); ForkJoinPool.commonPool().submit(() -> { try { // Exception occurred in processing throw new Exception(); } catch (Exception e) { LOG.info("Request processing failed"); deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("INTERNAL_SERVER_ERROR occurred.")); } }); return deferredResult; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\deffered\controllers\DeferredResultController.java
2
请在Spring Boot框架中完成以下Java代码
public class MonthsUntilExpiryAttributeStorageListener implements IAttributeStorageListener { @PostConstruct public void postConstruct() { Services.get(IAttributeStorageFactoryService.class).addAttributeStorageListener(this); } @Override public void onAttributeValueChanged( @NonNull final IAttributeValueContext attributeValueContext, @NonNull final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld_NOTUSED) { final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage); final boolean storageIsAboutHUs = huAttributeStorage != null; if (!storageIsAboutHUs) { return; } final boolean relevantAttributesArePresent = storage.hasAttribute(AttributeConstants.ATTR_MonthsUntilExpiry) && storage.hasAttribute(AttributeConstants.ATTR_BestBeforeDate); if (!relevantAttributesArePresent) { return; }
final AttributeCode attributeCode = attributeValue.getAttributeCode(); final boolean relevantAttributeHasChanged = AttributeConstants.ATTR_BestBeforeDate.equals(attributeCode); if (!relevantAttributeHasChanged) { return; } final LocalDate today = SystemTime.asLocalDate(); final OptionalInt monthsUntilExpiry = UpdateMonthsUntilExpiryCommand.computeMonthsUntilExpiry(storage, today); if (monthsUntilExpiry.isPresent()) { storage.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, monthsUntilExpiry.getAsInt()); } else { storage.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\MonthsUntilExpiryAttributeStorageListener.java
2
请完成以下Java代码
public LookupValuesList getParameterLookupValues(final String parameterName) { return parametersDocument.getFieldLookupValues(parameterName); } @Override public LookupValuesPage getParameterLookupValuesForQuery(final String parameterName, final String query) { return parametersDocument.getFieldLookupValuesForQuery(parameterName, query); } @Override public void processParameterValueChanges(final List<JSONDocumentChangedEvent> events, final ReasonSupplier reason) { parametersDocument.processValueChanges(events, reason); } @Override public ProcessInstanceResult getExecutionResult() { Check.assumeNotNull(result, "action was already executed"); return result; } @Override public ProcessInstanceResult startProcess(@NonNull final ProcessExecutionContext context) { assertNotExecuted(); // // Validate parameters, if any if (parametersDocument != null) { parametersDocument.checkAndGetValidStatus().throwIfInvalid(); } // // Execute view action's method final IView view = getView(); final Method viewActionMethod = viewActionDescriptor.getViewActionMethod(); final Object[] viewActionParams = viewActionDescriptor.extractMethodArguments(view, parametersDocument, selectedDocumentIds); try { final Object targetObject = Modifier.isStatic(viewActionMethod.getModifiers()) ? null : view; final Object resultActionObj = viewActionMethod.invoke(targetObject, viewActionParams); final ResultAction resultAction = viewActionDescriptor.convertReturnType(resultActionObj); final ResultAction resultActionProcessed = processResultAction(resultAction, context.getViewsRepo()); final ProcessInstanceResult result = ProcessInstanceResult.builder(pinstanceId) .action(resultActionProcessed) .build(); this.result = result; return result; }
catch (final Throwable ex) { throw AdempiereException.wrapIfNeeded(ex); } } private ResultAction processResultAction(final ResultAction resultAction, final IViewsRepository viewRepos) { if (resultAction == null) { return null; } if (resultAction instanceof CreateAndOpenIncludedViewAction) { final IView view = viewRepos.createView(((CreateAndOpenIncludedViewAction)resultAction).getCreateViewRequest()); return OpenIncludedViewAction.builder().viewId(view.getViewId()).build(); } return resultAction; } /* package */ void assertNotExecuted() { Check.assumeNull(result, "view action instance not already executed"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionInstance.java
1
请完成以下Java代码
public class IdmEngineFactoryBean implements FactoryBean<IdmEngine>, DisposableBean, ApplicationContextAware { protected IdmEngineConfiguration idmEngineConfiguration; protected ApplicationContext applicationContext; protected IdmEngine idmEngine; @Override public void destroy() throws Exception { if (idmEngine != null) { idmEngine.close(); } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public IdmEngine getObject() throws Exception { configureExternallyManagedTransactions(); if (idmEngineConfiguration.getBeans() == null) { idmEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext)); } this.idmEngine = idmEngineConfiguration.buildIdmEngine(); return this.idmEngine; } protected void configureExternallyManagedTransactions() { if (idmEngineConfiguration instanceof SpringIdmEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringIdmEngineConfiguration engineConfiguration = (SpringIdmEngineConfiguration) idmEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { idmEngineConfiguration.setTransactionsExternallyManaged(true); } } }
@Override public Class<IdmEngine> getObjectType() { return IdmEngine.class; } @Override public boolean isSingleton() { return true; } public IdmEngineConfiguration getIdmEngineConfiguration() { return idmEngineConfiguration; } public void setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) { this.idmEngineConfiguration = idmEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-idm-spring\src\main\java\org\flowable\idm\spring\IdmEngineFactoryBean.java
1
请完成以下Java代码
public SoftwareType getPackage() { return _package; } /** * Sets the value of the package property. * * @param value * allowed object is * {@link SoftwareType } * */ public void setPackage(SoftwareType value) { this._package = value; } /** * Gets the value of the generator property. * * @return * possible object is * {@link SoftwareType } * */
public SoftwareType getGenerator() { return generator; } /** * Sets the value of the generator property. * * @param value * allowed object is * {@link SoftwareType } * */ public void setGenerator(SoftwareType value) { this.generator = 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\PrologType.java
1
请在Spring Boot框架中完成以下Java代码
static class StandaloneEngineConfiguration extends BaseEngineConfigurationWithConfigurers<SpringCmmnEngineConfiguration> { @Bean public CmmnEngineFactoryBean cmmnEngine(SpringCmmnEngineConfiguration cmmnEngineConfiguration) { CmmnEngineFactoryBean factory = new CmmnEngineFactoryBean(); factory.setCmmnEngineConfiguration(cmmnEngineConfiguration); invokeConfigurers(cmmnEngineConfiguration); return factory; } } @Bean public CmmnRuntimeService cmmnRuntimeService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnRuntimeService(); } @Bean public DynamicCmmnService dynamicCmmnService(CmmnEngine cmmnEngine) { return cmmnEngine.getDynamicCmmnService(); } @Bean public CmmnTaskService cmmnTaskService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnTaskService(); }
@Bean public CmmnManagementService cmmnManagementService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnManagementService(); } @Bean public CmmnRepositoryService cmmnRepositoryService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnRepositoryService(); } @Bean public CmmnHistoryService cmmnHistoryService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnHistoryService(); } @Bean public CmmnMigrationService cmmnMigrationService(CmmnEngine cmmnEngine) { return cmmnEngine.getCmmnMigrationService(); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\CmmnEngineServicesAutoConfiguration.java
2
请完成以下Java代码
private int getWindowNo() { return getAPanel().getWindowNo(); } public Builder setIncludedTab(boolean includedTab) { this.includedTab = includedTab; return this; } private boolean isIncludedTab() { return includedTab; } private boolean isGridModeOnly() { return getGridTab().isGridModeOnly(); } private GridWindow getGridWindow() { return getGridTab().getGridWindow(); } public Builder setAPanel(final APanel aPanel) { this.aPanel = aPanel; return this; } private APanel getAPanel() { Check.assumeNotNull(aPanel, "aPanel not null"); return aPanel;
} private MFColor getBackgroundColor() { // use Window level background color return getGridWindow().getColor(); } private AppsAction getIgnoreAction() { return getAPanel().getIgnoreAction(); } private int getTabIndex() { return getGridTab().getTabNo(); } private boolean isLazyInitialization() { // lazy if not first tab return getTabIndex() != 0; } public Builder setGoSingleRowLayout(final boolean goSingleRowLayout) { this.goSingleRowLayout = goSingleRowLayout; return this; } private boolean isGoSingleRowLayout() { return goSingleRowLayout; } } } // GridController
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\GridController.java
1
请完成以下Java代码
public GraphFrame getGraphFrameUserRelationship() throws IOException { Path temp = Files.createTempDirectory("sparkGraphFrames"); SparkSession session = SparkSession.builder() .appName("SparkGraphFrameSample") .config("spark.sql.warehouse.dir", temp.toString()) .sparkContext(getSparkContext().sc()) .master("local[*]") .getOrCreate(); List<User> users = loadUsers(); Dataset<Row> userDataset = session.createDataFrame(users, User.class); List<Relationship> relationshipsList = getRelations(); Dataset<Row> relationshipDataset = session.createDataFrame(relationshipsList, Relationship.class); GraphFrame graphFrame = new GraphFrame(userDataset, relationshipDataset); return graphFrame; } public List<Relationship> getRelations() { List<Relationship> relationships = new ArrayList<>(); relationships.add(new Relationship("Friend", "1", "2")); relationships.add(new Relationship("Following", "1", "4")); relationships.add(new Relationship("Friend", "2", "4")); relationships.add(new Relationship("Relative", "3", "1")); relationships.add(new Relationship("Relative", "3", "4"));
return relationships; } private List<User> loadUsers() { User john = new User(1L, "John"); User martin = new User(2L, "Martin"); User peter = new User(3L, "Peter"); User alicia = new User(4L, "Alicia"); List<User> users = new ArrayList<>(); users.add(new User(1L, "John")); users.add(new User(2L, "Martin")); users.add(new User(3L, "Peter")); users.add(new User(4L, "Alicia")); return users; } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\graphframes\GraphLoader.java
1
请完成以下Java代码
public String toString() { return "NOT " + filter; } @Override public boolean accept(T model) { return !filter.accept(model); } @Override public String getSql() { final ISqlQueryFilter sqlFilter = ISqlQueryFilter.cast(filter); return "NOT (" + sqlFilter.getSql() + ")";
} @Override public List<Object> getSqlParams(final Properties ctx) { final ISqlQueryFilter sqlFilter = ISqlQueryFilter.cast(filter); return sqlFilter.getSqlParams(ctx); } @VisibleForTesting public IQueryFilter<T> getFilter() { return filter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\NotQueryFilter.java
1
请完成以下Java代码
public void report(TenantId tenantId, CustomerId customerId, ApiUsageRecordKey key) { report(tenantId, customerId, key, 1); } private void report(ApiUsageRecordKey key, long value, ReportLevel... levels) { ConcurrentMap<ReportLevel, AtomicLong> statsForKey = stats.get(key); for (ReportLevel level : levels) { if (level == null) continue; AtomicLong n = statsForKey.computeIfAbsent(level, k -> new AtomicLong()); if (key.isCounter()) { n.addAndGet(value); } else { n.set(value); } } } @Data private static class ReportLevel { private final TenantId tenantId; private final CustomerId customerId; public static ReportLevel of(TenantId tenantId) { return new ReportLevel(tenantId, null); } public static ReportLevel of(TenantId tenantId, CustomerId customerId) {
return new ReportLevel(tenantId, customerId); } public ParentEntity getParentEntity() { return new ParentEntity(tenantId, customerId); } } @Data private static class ParentEntity { private final TenantId tenantId; private final CustomerId customerId; public EntityId getId() { return customerId != null ? customerId : tenantId; } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\usagestats\DefaultTbApiUsageReportClient.java
1
请完成以下Java代码
public String getDirection () { return (String)get_Value(COLUMNNAME_Direction); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name)
{ set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_ConnectorType.java
1
请完成以下Java代码
public class SessionMigrationLoggerContext implements IMigrationLoggerContext { public static final String SYSCONFIG_Enabled = "org.adempiere.ad.migration.logger.MigrationLogger.Enabled"; public static final boolean SYSCONFIG_Enabled_Default = false; private final Map<String, Integer> migrationsMap = new HashMap<String, Integer>(3); private final CCache<Integer, I_AD_Migration> migrationsCache = new CCache<Integer, I_AD_Migration>(I_AD_Migration.Table_Name, 3, 2); public SessionMigrationLoggerContext() { } @Override public boolean isEnabled() { if (!MigrationScriptFileLoggerHolder.isEnabled()) { return false; } if (!Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_Enabled, SYSCONFIG_Enabled_Default)) { return false; } return true; } @Override public boolean isGenerateComments() { return true; } @Override public I_AD_Migration getMigration(String key) { final Properties ctx = Env.getCtx(); final Integer migrationId = migrationsMap.get(key); if (migrationId == null || migrationId <= 0) { return null; } I_AD_Migration migration = migrationsCache.get(migrationId); if (migration != null) { return migration;
} // We have the ID in out map, but cache expired, which means that maybe somebody deleted this record // Trying to reload migration = Services.get(IMigrationDAO.class).retrieveMigrationOrNull(ctx, migrationId); if (migration != null) { putMigration(key, migration); return migration; } return migration; } @Override public void putMigration(String key, I_AD_Migration migration) { migrationsMap.put(key, migration.getAD_Migration_ID()); migrationsCache.put(migration.getAD_Migration_ID(), migration); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\SessionMigrationLoggerContext.java
1
请完成以下Java代码
private void destroyEmptyHU(final I_M_HU emptyHU) { try { final boolean destroyed = handlingUnitsBL.destroyIfEmptyStorage(emptyHU); if (destroyed) { countDestroyed++; } else { countNotDestroyed++; } } catch (Exception e) { addLog("Failed destroying " + handlingUnitsBL.getDisplayName(emptyHU) + ": " + e.getLocalizedMessage()); countNotDestroyed++; } } private Iterator<I_M_HU> retrieveEmptyHUs() { // Services final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); if (p_M_Warehouse_ID <= 0) { throw new FillMandatoryException(PARAM_M_Warehouse_ID); }
final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder() .setContext(getCtx(), ITrx.TRXNAME_None) .addOnlyInWarehouseId(WarehouseId.ofRepoId(p_M_Warehouse_ID)) // we don't want to deal with e.g. Shipped HUs .addHUStatusToInclude(X_M_HU.HUSTATUS_Active) .addHUStatusToInclude(X_M_HU.HUSTATUS_Planning) .setEmptyStorageOnly() .setOnlyTopLevelHUs(); return huQueryBuilder .createQuery() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .iterate(I_M_HU.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_DestroyEmptyHUs.java
1
请完成以下Java代码
public void addInsertsIntoTargetTable(final int count) { countInsertsIntoTargetTable.add(count); } public void addUpdatesIntoTargetTable(final int count) { countUpdatesIntoTargetTable.add(count); } public void actualImportError(@NonNull final ActualImportRecordsResult.Error error) { actualImportErrors.add(error); } } @EqualsAndHashCode private static final class Counter { private boolean unknownValue; private int value = 0; @Override public String toString() { return unknownValue ? "N/A" : String.valueOf(value); }
public void set(final int value) { if (value < 0) { throw new AdempiereException("value shall NOT be negative: " + value); } this.value = value; this.unknownValue = false; } public void add(final int valueToAdd) { Check.assumeGreaterOrEqualToZero(valueToAdd, "valueToAdd"); set(this.value + valueToAdd); } public OptionalInt toOptionalInt() {return unknownValue ? OptionalInt.empty() : OptionalInt.of(value);} public int toIntOr(final int defaultValue) {return unknownValue ? defaultValue : value;} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportProcessResult.java
1
请完成以下Java代码
public static MTree_NodeCMS[] getTree (Properties ctx, int AD_Tree_ID, String trxName) { ArrayList<MTree_NodeCMS> list = new ArrayList<MTree_NodeCMS>(); String sql = "SELECT * FROM AD_TreeNodeCMS WHERE AD_Tree_ID=? ORDER BY Node_ID"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, trxName); pstmt.setInt (1, AD_Tree_ID); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) { list.add (new MTree_NodeCMS (ctx, rs, trxName)); } rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { s_log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } MTree_NodeCMS[] retValue = new MTree_NodeCMS[list.size ()]; list.toArray (retValue); return retValue; } // getTree /** * Get Tree Node * @param tree tree * @param Node_ID node * @return node or null */ public static MTree_NodeCMS get (MTree_Base tree, int Node_ID) { MTree_NodeCMS retValue = null; String sql = "SELECT * FROM AD_TreeNodeCMS WHERE AD_Tree_ID=? AND Node_ID=?"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, tree.get_TrxName()); pstmt.setInt (1, tree.getAD_Tree_ID()); pstmt.setInt (2, Node_ID); ResultSet rs = pstmt.executeQuery (); if (rs.next ()) retValue = new MTree_NodeCMS (tree.getCtx(), rs, tree.get_TrxName()); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { s_log.error("get", e); } try
{ if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } return retValue; } // get /** Static Logger */ private static Logger s_log = LogManager.getLogger(MTree_NodeCMS.class); /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MTree_NodeCMS (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MTree_NodeCMS /** * Full Constructor * @param tree tree * @param Node_ID node */ public MTree_NodeCMS (MTree_Base tree, int Node_ID) { super (tree.getCtx(), 0, tree.get_TrxName()); setClientOrg(tree); setAD_Tree_ID (tree.getAD_Tree_ID()); setNode_ID(Node_ID); // Add to root setParent_ID(0); setSeqNo (0); } // MTree_NodeCMS } // MTree_NodeCMS
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree_NodeCMS.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final ReviewRepository reviewRepository; private final BookRepository bookRepository; private final ArticleRepository articleRepository; private final MagazineRepository magazineRepository; public BookstoreService(ReviewRepository reviewRepository, BookRepository bookRepository, ArticleRepository articleRepository, MagazineRepository magazineRepository) { this.reviewRepository = reviewRepository; this.bookRepository = bookRepository; this.articleRepository = articleRepository; this.magazineRepository = magazineRepository; } @Transactional public void persistReviewOk() { Review review = new Review(); review.setContent("This is a book review ..."); review.setBook(bookRepository.findById(1L).get());
reviewRepository.save(review); } // Calling this method will cause a javax.validation.ConstraintViolationException // 'A review can be associated with either a book, a magazine or an article' @Transactional public void persistReviewWrong() { Review review = new Review(); review.setContent("This is an article and magazine review ..."); review.setArticle(articleRepository.findById(1L).get()); review.setMagazine(magazineRepository.findById(1L).get()); reviewRepository.save(review); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootChooseOnlyOneAssociation\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public class JarModeLibrary extends Library { /** * {@link JarModeLibrary} for layer tools. */ public static final JarModeLibrary TOOLS = new JarModeLibrary("spring-boot-jarmode-tools"); JarModeLibrary(String artifactId) { this(createCoordinates(artifactId)); } public JarModeLibrary(LibraryCoordinates coordinates) { super(getJarName(coordinates), null, LibraryScope.RUNTIME, coordinates, false, false, true); } private static LibraryCoordinates createCoordinates(String artifactId) { String version = JarModeLibrary.class.getPackage().getImplementationVersion(); return LibraryCoordinates.of("org.springframework.boot", artifactId, version); } private static String getJarName(LibraryCoordinates coordinates) { String version = coordinates.getVersion(); StringBuilder jarName = new StringBuilder(coordinates.getArtifactId()); if (StringUtils.hasText(version)) { jarName.append('-'); jarName.append(version); }
jarName.append(".jar"); return jarName.toString(); } @Override public InputStream openStream() throws IOException { LibraryCoordinates coordinates = getCoordinates(); Assert.state(coordinates != null, "'coordinates' must not be null"); String path = "META-INF/jarmode/" + coordinates.getArtifactId() + ".jar"; URL resource = getClass().getClassLoader().getResource(path); Assert.state(resource != null, () -> "Unable to find resource " + path); return resource.openStream(); } @Override long getLastModified() { return 0L; } @Override public File getFile() { throw new UnsupportedOperationException("Unable to access jar mode library file"); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\JarModeLibrary.java
1
请完成以下Java代码
private void insertBPartnerExternalReferenceIfMissing( @NonNull final JsonSingleExternalReferenceCreateReq externalReferenceCreateReq, @NonNull final BPartnerComposite bpartnerComposite, @Nullable final String orgCode) { final BPartnerId bPartnerId = bpartnerComposite.getBpartner() != null && bpartnerComposite.getBpartner().getId() != null ? bpartnerComposite.getBpartner().getId() : null; if (bPartnerId == null) { throw new AdempiereException("bPartnerComposite.getBpartner().getId() should never be null at this stage!") .appendParametersToMessage() .setParameter("BPartnerComposite", bpartnerComposite); } final JsonSingleExternalReferenceCreateReq createRequest = buildExternalRefWithMetasfreshId(externalReferenceCreateReq, JsonMetasfreshId.of(bPartnerId.getRepoId())); externalReferenceRestControllerService.performInsertIfMissing(createRequest, orgCode); } private void insertBPLocationExternalRefIfMissing( @NonNull final List<JsonRequestLocationUpsertItem> requestItems, @NonNull final Map<ExternalId, JsonMetasfreshId> externalLocationId2MetasfreshId, @Nullable final String orgCode) { requestItems.stream() .map(JsonRequestLocationUpsertItem::getLocationExternalRef) .filter(Objects::nonNull) .map(locationExternalRef -> { final ExternalId locationExternalId = ExternalId.of(locationExternalRef.getExternalReferenceItem().getLookupItem().getId()); return Optional.ofNullable(externalLocationId2MetasfreshId.get(locationExternalId)) .map(locationMFId -> buildExternalRefWithMetasfreshId(locationExternalRef, locationMFId)) .orElseGet(() -> {
logger.warn("*** WARN in insertBPLocationExternalRefIfMissing: no metasfreshId was found for the externalId: {}! " + "If this happened, something went wrong while upserting the bPartnerLocations", locationExternalId); return null; }); }) .filter(Objects::nonNull) .forEach(createExternalRefReq -> externalReferenceRestControllerService.performInsertIfMissing(createExternalRefReq, orgCode)); } @NonNull private JsonSingleExternalReferenceCreateReq buildExternalRefWithMetasfreshId( @NonNull final JsonSingleExternalReferenceCreateReq externalReferenceCreateReq, @NonNull final JsonMetasfreshId metasfreshId) { final JsonExternalReferenceItem referenceItemWithMFId = JsonExternalReferenceItem .builder() .metasfreshId(metasfreshId) .version(externalReferenceCreateReq.getExternalReferenceItem().getVersion()) .lookupItem(externalReferenceCreateReq.getExternalReferenceItem().getLookupItem()) .build(); return JsonSingleExternalReferenceCreateReq.builder() .systemName(externalReferenceCreateReq.getSystemName()) .externalReferenceItem(referenceItemWithMFId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\JsonPersisterService.java
1
请在Spring Boot框架中完成以下Java代码
public class MessageController { private final MessageService messageService; @Autowired public MessageController(MessageService messageService) { this.messageService = messageService; } @GetMapping("/messages") public ResponseEntity<Collection<MessageData>> getMessages() { return ResponseEntity.ok(messageService.getAll()); } @GetMapping("/messages/{id}") public ResponseEntity<MessageData> getMessageById(@PathVariable("id") String id) {
return ResponseEntity.of(messageService.get(id)); } @PostMapping("/messages/{message}") public ResponseEntity<MessageData> save(@PathVariable("message") String message) { MessageData msg = new MessageData(UUID.randomUUID().toString(), message); messageService.save(msg); return ResponseEntity.ok(msg); } @DeleteMapping("/messages/{id}") public ResponseEntity<MessageData> delete(@PathVariable("id") String id) { return ResponseEntity.of(messageService.delete(id)); } }
repos\spring-examples-java-17\spring-redis\src\main\java\itx\examples\springboot\redis\controller\MessageController.java
2
请完成以下Java代码
public String toGlobalQRCodeJsonString() {return ResourceQRCodeJsonConverter.toGlobalQRCodeJsonString(this);} public static ResourceQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return ResourceQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);} public static ResourceQRCode ofGlobalQRCodeJsonString(final String qrCodeString) { return ResourceQRCodeJsonConverter.fromGlobalQRCodeJsonString(qrCodeString); } public static ResourceQRCode ofResource(@NonNull final I_S_Resource record) { return ResourceQRCode.builder() .resourceId(ResourceId.ofRepoId(record.getS_Resource_ID())) .resourceType(record.getManufacturingResourceType()) .caption(record.getName())
.build(); } public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .qrCode(toGlobalQRCodeJsonString()) .bottomText(caption) .build(); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return ResourceQRCodeJsonConverter.isTypeMatching(globalQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\qrcode\ResourceQRCode.java
1
请完成以下Spring Boot application配置
spring: application: name: listener-demo # Kafka 配置项,对应 KafkaProperties 配置类 kafka: bootstrap-servers: 127.0.0.1:9092 # 指定 Kafka Broker 地址,可以设置多个,以逗号分隔 server: port: 18080 # 随机端口,方便启动多个消费者 management: endpoints: # Actuator HTTP 配置项,对应 WebEndpoi
ntProperties 配置类 web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
repos\SpringBoot-Labs-master\labx-19\labx-19-sc-bus-kafka-demo-listener-actuator\src\main\resources\application.yml
2
请完成以下Java代码
public ApiUsageState findTenantApiUsageState(TenantId tenantId) { log.trace("Executing findTenantUsageRecord, tenantId [{}]", tenantId); validateId(tenantId, id -> INCORRECT_TENANT_ID + id); return apiUsageStateDao.findTenantApiUsageState(tenantId.getId()); } @Override public ApiUsageState findApiUsageStateByEntityId(EntityId entityId) { validateId(entityId.getId(), id -> "Invalid entity id " + id); return apiUsageStateDao.findApiUsageStateByEntityId(entityId); } @Override public ApiUsageState findApiUsageStateById(TenantId tenantId, ApiUsageStateId id) { log.trace("Executing findApiUsageStateById, tenantId [{}], apiUsageStateId [{}]", tenantId, id); validateId(tenantId, t -> INCORRECT_TENANT_ID + t); validateId(id, u -> "Incorrect apiUsageStateId " + u); return apiUsageStateDao.findById(tenantId, id.getId()); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findApiUsageStateById(tenantId, new ApiUsageStateId(entityId.getId())));
} @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(apiUsageStateDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Transactional @Override public void deleteByTenantId(TenantId tenantId) { deleteApiUsageStateByEntityId(tenantId); } @Override public EntityType getEntityType() { return EntityType.API_USAGE_STATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\usagerecord\ApiUsageStateServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderPayResultVo implements Serializable { /** 状态 **/ private String status = TradeStatusEnum.WAITING_PAYMENT.name(); /** 金额 **/ private BigDecimal orderPrice; /** 商户页面通知结果地址 **/ private String returnUrl; /** 产品名称 **/ private String productName; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public BigDecimal getOrderPrice() { return orderPrice; } public void setOrderPrice(BigDecimal orderPrice) { this.orderPrice = orderPrice; } public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", status=").append(status); sb.append(", orderPrice=").append(orderPrice); sb.append(", returnUrl=").append(returnUrl); sb.append(", productName=").append(productName); sb.append("]"); return sb.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\OrderPayResultVo.java
2
请完成以下Java代码
protected RuleNodeException getInactiveException() { return new RuleNodeException("Rule Node is not active! Failed to initialize.", ruleChainName, ruleNode); } private boolean isMyNodePartition() { return isMyNodePartition(this.ruleNode); } private boolean isMyNodePartition(RuleNode ruleNode) { boolean result = ruleNode == null || !ruleNode.isSingletonMode() || systemContext.getDiscoveryService().isMonolith() || defaultCtx.isLocalEntity(ruleNode.getId()); if (!result) { log.trace("[{}][{}] Is not my node partition", tenantId, entityId); } return result; } //Message will return after processing. See RuleChainActorMessageProcessor.pushToTarget.
private void putToNodePartition(TbMsg source) { TbMsg tbMsg = TbMsg.newMsg(source, source.getQueueName(), source.getRuleChainId(), entityId); TopicPartitionInfo tpi = systemContext.resolve(ServiceType.TB_RULE_ENGINE, tbMsg.getQueueName(), tenantId, ruleNode.getId()); TransportProtos.ToRuleEngineMsg toQueueMsg = TransportProtos.ToRuleEngineMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setTbMsgProto(TbMsg.toProto(tbMsg)) .build(); systemContext.getClusterService().pushMsgToRuleEngine(tpi, tbMsg.getId(), toQueueMsg, null); defaultCtx.ack(source); } private void persistDebugInputIfAllowed(TbMsg msg, String fromNodeConnectionType) { if (DebugModeUtil.isDebugAllAvailable(ruleNode)) { systemContext.persistDebugInput(tenantId, entityId, msg, fromNodeConnectionType); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleNodeActorMessageProcessor.java
1
请完成以下Java代码
public final Supplier<ScriptExecutor> createExecutorSupplier(final I_AD_Rule rule) { Check.assumeNotNull(rule, "Parameter rule is not null"); final String scriptEngineType = rule.getRuleType(); final String scriptEngineName = extractEngineNameFromRuleValue(rule.getValue()); return () -> createExecutor(scriptEngineType, scriptEngineName); } public final void assertScriptEngineExists(final I_AD_Rule rule) { try { final ScriptExecutor executor = createExecutor(rule); Check.assumeNotNull(executor, "executor is not null"); // shall not happen } catch (final Throwable e) { throw new AdempiereException("@WrongScriptValue@", e); } } public static final String extractEngineNameFromRuleValue(final String ruleValue) { if (ruleValue == null) { return null; } final int colonPosition = ruleValue.indexOf(":"); if (colonPosition < 0) { return null; } return ruleValue.substring(0, colonPosition); } public static final Optional<String> extractRuleValueFromClassname(final String classname) {
if (classname == null || classname.isEmpty()) { return Optional.empty(); } if (!classname.toLowerCase().startsWith(SCRIPT_PREFIX)) { return Optional.empty(); } final String ruleValue = classname.substring(SCRIPT_PREFIX.length()).trim(); return Optional.of(ruleValue); } private final ScriptEngine createScriptEngine_JSR223(final String engineName) { Check.assumeNotEmpty(engineName, "engineName is not empty"); final ScriptEngineManager factory = getScriptEngineManager(); final ScriptEngine engine = factory.getEngineByName(engineName); if (engine == null) { throw new AdempiereException("Script engine was not found for engine name: '" + engineName + "'"); } return engine; } private final ScriptEngineManager getScriptEngineManager() { return scriptEngineManager.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptEngineFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getOrderIp() { return orderIp; } public void setOrderIp(String orderIp) { this.orderIp = orderIp; } public String getOrderDate() { return orderDate; } public void setOrderDate(String orderDate) { this.orderDate = orderDate; } public String getOrderTime() { return orderTime; } public void setOrderTime(String orderTime) { this.orderTime = orderTime; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getPayType() {
return payType; } public void setPayType(String payType) { this.payType = payType; } public String getAuthCode() { return authCode; } public void setAuthCode(String authCode) { this.authCode = authCode; } @Override public String toString() { return "F2FPayRequestBo{" + "payKey='" + payKey + '\'' + ", authCode='" + authCode + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\F2FPayRequestBo.java
2
请完成以下Java代码
public void setInsertObjectIdentitySql(String insertObjectIdentity) { this.insertObjectIdentity = insertObjectIdentity; } public void setInsertSidSql(String insertSid) { this.insertSid = insertSid; } public void setClassPrimaryKeyQuery(String selectClassPrimaryKey) { this.selectClassPrimaryKey = selectClassPrimaryKey; } public void setObjectIdentityPrimaryKeyQuery(String selectObjectIdentityPrimaryKey) { this.selectObjectIdentityPrimaryKey = selectObjectIdentityPrimaryKey; } public void setSidPrimaryKeyQuery(String selectSidPrimaryKey) { this.selectSidPrimaryKey = selectSidPrimaryKey; } public void setUpdateObjectIdentity(String updateObjectIdentity) { this.updateObjectIdentity = updateObjectIdentity; } /** * @param foreignKeysInDatabase if false this class will perform additional FK * constrain checking, which may cause deadlocks (the default is true, so deadlocks * are avoided but the database is expected to enforce FKs) */ public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) { this.foreignKeysInDatabase = foreignKeysInDatabase; }
@Override public void setAclClassIdSupported(boolean aclClassIdSupported) { super.setAclClassIdSupported(aclClassIdSupported); if (aclClassIdSupported) { // Change the default insert if it hasn't been overridden if (this.insertClass.equals(DEFAULT_INSERT_INTO_ACL_CLASS)) { this.insertClass = DEFAULT_INSERT_INTO_ACL_CLASS_WITH_ID; } else { log.debug("Insert class statement has already been overridden, so not overridding the default"); } } } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\JdbcMutableAclService.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Duration getTimeToLive() { return this.timeToLive; } public void setTimeToLive(@Nullable Duration timeToLive) { this.timeToLive = timeToLive; } public boolean determineQosEnabled() { if (this.qosEnabled != null) { return this.qosEnabled; } return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null); } public @Nullable Boolean getQosEnabled() { return this.qosEnabled; } public void setQosEnabled(@Nullable Boolean qosEnabled) { this.qosEnabled = qosEnabled; } public @Nullable Duration getReceiveTimeout() { return this.receiveTimeout; } public void setReceiveTimeout(@Nullable Duration receiveTimeout) { this.receiveTimeout = receiveTimeout; } public Session getSession() { return this.session; } public static class Session { /** * Acknowledge mode used when creating sessions. */ private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO; /** * Whether to use transacted sessions. */ private boolean transacted; public AcknowledgeMode getAcknowledgeMode() { return this.acknowledgeMode; } public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) { this.acknowledgeMode = acknowledgeMode; }
public boolean isTransacted() { return this.transacted; } public void setTransacted(boolean transacted) { this.transacted = transacted; } } } public enum DeliveryMode { /** * Does not require that the message be logged to stable storage. This is the * lowest-overhead delivery mode but can lead to lost of message if the broker * goes down. */ NON_PERSISTENT(1), /* * Instructs the JMS provider to log the message to stable storage as part of the * client's send operation. */ PERSISTENT(2); private final int value; DeliveryMode(int value) { this.value = value; } public int getValue() { return this.value; } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java
2
请完成以下Java代码
public List<DocumentLayoutElementDescriptor> getElements() { return elements; } public static final class Builder { private ProcessId processId; private PanelLayoutType layoutType = PanelLayoutType.Panel; private ITranslatableString caption; private ITranslatableString description; private final List<DocumentLayoutElementDescriptor> elements = new ArrayList<>(); private Builder() { super(); } public ProcessLayout build() { return new ProcessLayout(this); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("processId", processId) .add("caption", caption) .add("elements-count", elements.size()) .toString(); } public Builder setProcessId(final ProcessId processId) { this.processId = processId; return this; } public Builder setLayoutType(final PanelLayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = caption; return this; } public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public ITranslatableString getDescription() { return description; } public Builder addElement(final DocumentLayoutElementDescriptor element) { Check.assumeNotNull(element, "Parameter element is not null"); elements.add(element); return this; }
public Builder addElement(final DocumentFieldDescriptor processParaDescriptor) { Check.assumeNotNull(processParaDescriptor, "Parameter processParaDescriptor is not null"); final DocumentLayoutElementDescriptor element = DocumentLayoutElementDescriptor.builder() .setCaption(processParaDescriptor.getCaption()) .setDescription(processParaDescriptor.getDescription()) .setWidgetType(processParaDescriptor.getWidgetType()) .setAllowShowPassword(processParaDescriptor.isAllowShowPassword()) .barcodeScannerType(processParaDescriptor.getBarcodeScannerType()) .addField(DocumentLayoutElementFieldDescriptor.builder(processParaDescriptor.getFieldName()) .setLookupInfos(processParaDescriptor.getLookupDescriptor().orElse(null)) .setPublicField(true) .setSupportZoomInto(processParaDescriptor.isSupportZoomInto())) .build(); addElement(element); return this; } public Builder addElements(@Nullable final DocumentEntityDescriptor parametersDescriptor) { if (parametersDescriptor != null) { parametersDescriptor.getFields().forEach(this::addElement); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\ProcessLayout.java
1
请在Spring Boot框架中完成以下Java代码
public void removeFromFavorite(@RequestBody @NonNull final JsonRemoveProductsFromFavoriteRequest request) { final User user = loginService.getLoggedInUser(); for (final String productIdStr : request.getProductIds()) { final Product product = productSuppliesService.getProductById(Long.parseLong(productIdStr)); productSuppliesService.removeUserFavoriteProduct(user, product); } } @GetMapping("/notFavorite") public JsonProductToAddResponse getProductsNotFavorite() { final User user = loginService.getLoggedInUser(); final List<Product> productsContracted = contractsService.getContracts(user.getBpartner()).getProducts(); final List<Product> productsFavorite = productSuppliesService.getUserFavoriteProducts(user); final List<Product> productsShared = productSuppliesService.getAllSharedProducts(); final ArrayList<Product> productsNotSelected = new ArrayList<>(productsContracted); productsNotSelected.removeAll(productsFavorite); final ArrayList<Product> productsNotContracted = new ArrayList<>(productsShared); productsNotContracted.removeAll(productsFavorite); productsNotContracted.removeAll(productsContracted); final Locale locale = loginService.getLocale();
return JsonProductToAddResponse.builder() .products(toJsonProductOrderedList(productsNotSelected, locale)) .moreProducts(toJsonProductOrderedList(productsNotContracted, locale)) .build(); } private static ArrayList<JsonProduct> toJsonProductOrderedList(@NonNull final List<Product> products, @NonNull final Locale locale) { return products.stream() .map(product -> toJsonProduct(product, locale)) .sorted(Comparator.comparing(JsonProduct::getProductName)) .collect(Collectors.toCollection(ArrayList::new)); } private static JsonProduct toJsonProduct(@NonNull final Product product, @NonNull final Locale locale) { return JsonProduct.builder() .productId(product.getIdAsString()) .productName(product.getName(locale)) .packingInfo(product.getPackingInfo(locale)) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\products\ProductsRestController.java
2
请完成以下Java代码
public ResponseEntity<byte[]> getImageById( @PathVariable("imageId") final int imageIdInt, @RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth, @RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight, @NonNull final WebRequest request) { final AdImageId adImageId = AdImageId.ofRepoId(imageIdInt); final AdImage adImage = adImageRepository.getById(adImageId); final String etag = computeETag(adImage.getLastModified(), maxWidth, maxHeight); if (request.checkNotModified(etag)) { // Response: 304 Not Modified return newResponse(HttpStatus.NOT_MODIFIED, etag).build(); } return newResponse(HttpStatus.OK, etag) .contentType(MediaType.parseMediaType(adImage.getContentType())) .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + adImage.getFilename() + "\"")
.body(adImage.getScaledImageData(maxWidth, maxHeight)); } private static String computeETag(@NonNull final Instant lastModified, int maxWidth, int maxHeight) { return lastModified + "_" + Math.max(maxWidth, 0) + "_" + Math.max(maxHeight, 0); } private ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag) { return ResponseEntity.status(status) .eTag(etag) .cacheControl(CacheControl.maxAge(Duration.ofSeconds(10))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\image\ImageRestController.java
1
请完成以下Spring Boot application配置
server: port: 9090 security: oauth2: # OAuth2 Client 配置,对应 OAuth2ClientProperties 类 client: client-id: clientapp client-secret: 112233 # OAuth2 Resource 配置,对应 ResourceServerProperties 类 resource: token-info-uri: http://127.0.0.1:80
80/oauth/check_token # 获得 Token 信息的 URL # 访问令牌获取 URL,自定义的 access-token-uri: http://127.0.0.1:8080/oauth/token
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo02-resource-server\src\main\resources\application.yml
2
请完成以下Java代码
public Optional<IDocumentLocationAdapter> getDocumentLocationAdapterIfHandled(final Object record) { return toDunningDoc(record).map(DunningDocDocumentLocationAdapterFactory::locationAdapter); } @Override public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { return Optional.empty(); } @Override public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { return Optional.empty(); }
@Override public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { return Optional.empty(); } private static Optional<I_C_DunningDoc> toDunningDoc(final Object record) { return InterfaceWrapperHelper.isInstanceOf(record, I_C_DunningDoc.class) ? Optional.of(InterfaceWrapperHelper.create(record, I_C_DunningDoc.class)) : Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDocDocumentLocationAdapterFactory.java
1
请完成以下Java代码
public HttpStatus getStatusCode() throws IOException { return status; } @Override public int getRawStatusCode() throws IOException { return status.value(); } @Override public String getStatusText() throws IOException { return status.getReasonPhrase(); } @Override public void close() { } @Override public InputStream getBody() throws IOException { return new ByteArrayInputStream(message.getBytes()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return headers; } public HttpStatus getStatus() { return status;
} public void setStatus(HttpStatus status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul-fallback\spring-cloud-zuul-fallback-api-gateway\src\main\java\com\baeldung\spring\cloud\apigateway\fallback\GatewayClientResponse.java
1
请完成以下Java代码
public LogicExpressionResult getReadonly() { return documentField.getReadonly(); } @Override public LogicExpressionResult getMandatory() { return documentField.getMandatory(); } @Override public LogicExpressionResult getDisplayed() { return documentField.getDisplayed(); }
@Override public DocumentValidStatus getValidStatus() { return documentField.getValidStatus(); } @Override public DeviceDescriptorsList getDevices() { return documentField.getDescriptor() .getDeviceDescriptorsProvider() .getDeviceDescriptors(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\DocumentFieldAsProcessInstanceParameter.java
1
请在Spring Boot框架中完成以下Java代码
public static ServiceName forProcessApplicationStartService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("START"); } /** * <p>Returns the name for a {@link ProcessApplicationDeploymentService} given * the name of the deployment unit and the name of the deployment.</p> * * @param processApplicationName * @param deploymentId */ public static ServiceName forProcessApplicationDeploymentService(String moduleName, String deploymentName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("DEPLOY").append(deploymentName); } public static ServiceName forNoViewProcessApplicationStartService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("NO_VIEW"); } /** * @return the {@link ServiceName} of the {@link MscExecutorService}. */ public static ServiceName forMscExecutorService() { return BPM_PLATFORM.append("executor-service"); } /** * @return the {@link ServiceName} of the {@link MscRuntimeContainerJobExecutor} */ public static ServiceName forMscRuntimeContainerJobExecutorService(String jobExecutorName) { return JOB_EXECUTOR.append(jobExecutorName); } /** * @return the {@link ServiceName} of the {@link MscBpmPlatformPlugins} */
public static ServiceName forBpmPlatformPlugins() { return BPM_PLATFORM_PLUGINS; } /** * @return the {@link ServiceName} of the {@link ProcessApplicationStopService} */ public static ServiceName forProcessApplicationStopService(String moduleName) { return PROCESS_APPLICATION_MODULE.append(moduleName).append("STOP"); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.BoundedQueueThreadPoolService} */ public static ServiceName forManagedThreadPool(String threadPoolName) { return JOB_EXECUTOR.append(threadPoolName); } /** * @return the {@link ServiceName} of the {@link org.jboss.as.threads.ThreadFactoryService} */ public static ServiceName forThreadFactoryService(String threadFactoryName) { return ThreadsServices.threadFactoryName(threadFactoryName); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ServiceNames.java
2
请完成以下Java代码
public int getM_BannedManufacturer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_BannedManufacturer_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner getManufacturer() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setManufacturer(org.compiere.model.I_C_BPartner Manufacturer) { set_ValueFromPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class, Manufacturer); } /** Set Hersteller. @param Manufacturer_ID Hersteller des Produktes
*/ @Override public void setManufacturer_ID (int Manufacturer_ID) { if (Manufacturer_ID < 1) set_Value (COLUMNNAME_Manufacturer_ID, null); else set_Value (COLUMNNAME_Manufacturer_ID, Integer.valueOf(Manufacturer_ID)); } /** Get Hersteller. @return Hersteller des Produktes */ @Override public int getManufacturer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Manufacturer_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_BannedManufacturer.java
1
请完成以下Java代码
public String getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(String lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
repos\Activiti-develop\activiti-core-common\activiti-project-model\src\main\java\org\activiti\core\common\project\model\ProjectManifest.java
1
请完成以下Java代码
protected boolean upgradeEncodingNonNull(String encodedPassword) { Matcher matcher = this.BCRYPT_PATTERN.matcher(encodedPassword); if (!matcher.matches()) { throw new IllegalArgumentException("Encoded password does not look like BCrypt: " + encodedPassword); } int strength = Integer.parseInt(matcher.group(2)); return strength < this.strength; } /** * Stores the default bcrypt version for use in configuration. * * @author Lin Feng */ public enum BCryptVersion { $2A("$2a"), $2Y("$2y"),
$2B("$2b"); private final String version; BCryptVersion(String version) { this.version = version; } public String getVersion() { return this.version; } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\bcrypt\BCryptPasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
public class LocalResponseCacheAutoConfiguration { private static final Log LOGGER = LogFactory.getLog(LocalResponseCacheAutoConfiguration.class); private static final String RESPONSE_CACHE_NAME = "response-cache"; /* for testing */ static final String RESPONSE_CACHE_MANAGER_NAME = "gatewayCacheManager"; @Bean @Conditional(LocalResponseCacheAutoConfiguration.OnGlobalLocalResponseCacheCondition.class) public GlobalLocalResponseCacheGatewayFilter globalLocalResponseCacheGatewayFilter( ResponseCacheManagerFactory responseCacheManagerFactory, @Qualifier(RESPONSE_CACHE_MANAGER_NAME) CacheManager cacheManager, LocalResponseCacheProperties properties) { return new GlobalLocalResponseCacheGatewayFilter(responseCacheManagerFactory, responseCache(cacheManager), properties.getTimeToLive(), properties.getRequest()); } @Bean(name = RESPONSE_CACHE_MANAGER_NAME) @Conditional(LocalResponseCacheAutoConfiguration.OnGlobalLocalResponseCacheCondition.class) public CacheManager gatewayCacheManager(LocalResponseCacheProperties cacheProperties) { return LocalResponseCacheUtils.createGatewayCacheManager(cacheProperties); } @Bean public LocalResponseCacheGatewayFilterFactory localResponseCacheGatewayFilterFactory( ResponseCacheManagerFactory responseCacheManagerFactory, LocalResponseCacheProperties properties) { return new LocalResponseCacheGatewayFilterFactory(responseCacheManagerFactory, properties.getTimeToLive(), properties.getSize(), properties.getRequest()); } @Bean public ResponseCacheManagerFactory responseCacheManagerFactory(CacheKeyGenerator cacheKeyGenerator) { return new ResponseCacheManagerFactory(cacheKeyGenerator); } @Bean public CacheKeyGenerator cacheKeyGenerator() { return new CacheKeyGenerator(); } Cache responseCache(CacheManager cacheManager) { return cacheManager.getCache(RESPONSE_CACHE_NAME); } public static class OnGlobalLocalResponseCacheCondition extends AllNestedConditions { OnGlobalLocalResponseCacheCondition() { super(ConfigurationPhase.REGISTER_BEAN);
} @ConditionalOnProperty(value = GatewayProperties.PREFIX + ".enabled", havingValue = "true", matchIfMissing = true) static class OnGatewayPropertyEnabled { } @ConditionalOnProperty(value = GatewayProperties.PREFIX + ".filter.local-response-cache.enabled", havingValue = "true") static class OnLocalResponseCachePropertyEnabled { } @ConditionalOnProperty(name = GatewayProperties.PREFIX + ".global-filter.local-response-cache.enabled", havingValue = "true", matchIfMissing = true) static class OnGlobalLocalResponseCachePropertyEnabled { } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\LocalResponseCacheAutoConfiguration.java
2
请完成以下Java代码
public void setRemittanceAmt_Currency_ID (final int RemittanceAmt_Currency_ID) { if (RemittanceAmt_Currency_ID < 1) set_Value (COLUMNNAME_RemittanceAmt_Currency_ID, null); else set_Value (COLUMNNAME_RemittanceAmt_Currency_ID, RemittanceAmt_Currency_ID); } @Override public int getRemittanceAmt_Currency_ID() { return get_ValueAsInt(COLUMNNAME_RemittanceAmt_Currency_ID); } @Override public void setSendAt (final @Nullable java.sql.Timestamp SendAt) { set_Value (COLUMNNAME_SendAt, SendAt); } @Override public java.sql.Timestamp getSendAt() { return get_ValueAsTimestamp(COLUMNNAME_SendAt); } @Override public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount) { set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount); } @Override public BigDecimal getServiceFeeAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setServiceFeeAmount_Currency_ID (final int ServiceFeeAmount_Currency_ID) { if (ServiceFeeAmount_Currency_ID < 1) set_Value (COLUMNNAME_ServiceFeeAmount_Currency_ID, null); else set_Value (COLUMNNAME_ServiceFeeAmount_Currency_ID, ServiceFeeAmount_Currency_ID); } @Override public int getServiceFeeAmount_Currency_ID() { return get_ValueAsInt(COLUMNNAME_ServiceFeeAmount_Currency_ID); } @Override public void setServiceFeeExternalInvoiceDocumentNo (final @Nullable java.lang.String ServiceFeeExternalInvoiceDocumentNo) { set_Value (COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo, ServiceFeeExternalInvoiceDocumentNo); } @Override public java.lang.String getServiceFeeExternalInvoiceDocumentNo() { return get_ValueAsString(COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo);
} @Override public void setServiceFeeInvoicedDate (final @Nullable java.sql.Timestamp ServiceFeeInvoicedDate) { set_Value (COLUMNNAME_ServiceFeeInvoicedDate, ServiceFeeInvoicedDate); } @Override public java.sql.Timestamp getServiceFeeInvoicedDate() { return get_ValueAsTimestamp(COLUMNNAME_ServiceFeeInvoicedDate); } @Override public void setSource_BP_BankAccount_ID (final int Source_BP_BankAccount_ID) { if (Source_BP_BankAccount_ID < 1) set_Value (COLUMNNAME_Source_BP_BankAccount_ID, null); else set_Value (COLUMNNAME_Source_BP_BankAccount_ID, Source_BP_BankAccount_ID); } @Override public int getSource_BP_BankAccount_ID() { return get_ValueAsInt(COLUMNNAME_Source_BP_BankAccount_ID); } @Override public void setSource_BPartner_ID (final int Source_BPartner_ID) { if (Source_BPartner_ID < 1) set_Value (COLUMNNAME_Source_BPartner_ID, null); else set_Value (COLUMNNAME_Source_BPartner_ID, Source_BPartner_ID); } @Override public int getSource_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Source_BPartner_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice.java
1
请完成以下Java代码
public Integer getStoreId() { return (Integer) get(4); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BookRecord */ public BookRecord() {
super(Book.BOOK); } /** * Create a detached, initialised BookRecord */ public BookRecord(Integer id, Integer authorId, String title, String description, Integer storeId) { super(Book.BOOK); setId(id); setAuthorId(authorId); setTitle(title); setDescription(description); setStoreId(storeId); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookRecord.java
1
请完成以下Java代码
public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostProcessor { private static final Log logger = DevToolsLogFactory.getLog(DevToolsPropertyDefaultsPostProcessor.class); private static final String ENABLED = "spring.devtools.add-properties"; private static final String WEB_LOGGING = "logging.level.web"; private static final String[] WEB_ENVIRONMENT_CLASSES = { "org.springframework.web.context.ConfigurableWebEnvironment", "org.springframework.boot.web.reactive.context.ConfigurableReactiveWebEnvironment" }; private static final Map<String, Object> PROPERTIES; static { if (NativeDetector.inNativeImage()) { PROPERTIES = Collections.emptyMap(); } else { PROPERTIES = DevToolsSettings.get().getPropertyDefaults(); } } @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (DevToolsEnablementDeducer.shouldEnable(Thread.currentThread()) && isLocalApplication(environment)) { if (canAddProperties(environment)) { logger.info(LogMessage.format("Devtools property defaults active! Set '%s' to 'false' to disable", ENABLED)); environment.getPropertySources().addLast(new MapPropertySource("devtools", PROPERTIES)); } if (isWebApplication(environment) && !environment.containsProperty(WEB_LOGGING)) { logger.info(LogMessage.format( "For additional web related logging consider setting the '%s' property to 'DEBUG'", WEB_LOGGING)); } } } private boolean isLocalApplication(ConfigurableEnvironment environment) { return environment.getPropertySources().get("remoteUrl") == null; } private boolean canAddProperties(Environment environment) { if (environment.getProperty(ENABLED, Boolean.class, true)) { return isRestarterInitialized() || isRemoteRestartEnabled(environment); } return false; }
private boolean isRestarterInitialized() { try { Restarter restarter = Restarter.getInstance(); return (restarter != null && restarter.getInitialUrls() != null); } catch (Exception ex) { return false; } } private boolean isRemoteRestartEnabled(Environment environment) { return environment.containsProperty("spring.devtools.remote.secret"); } private boolean isWebApplication(Environment environment) { for (String candidate : WEB_ENVIRONMENT_CLASSES) { Class<?> environmentClass = resolveClassName(candidate, environment.getClass().getClassLoader()); if (environmentClass != null && environmentClass.isInstance(environment)) { return true; } } return false; } private @Nullable Class<?> resolveClassName(String candidate, ClassLoader classLoader) { try { return ClassUtils.resolveClassName(candidate, classLoader); } catch (IllegalArgumentException ex) { return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\env\DevToolsPropertyDefaultsPostProcessor.java
1
请完成以下Java代码
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 Import Processor Type. @param IMP_Processor_Type_ID Import Processor Type */ public void setIMP_Processor_Type_ID (int IMP_Processor_Type_ID) { if (IMP_Processor_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_IMP_Processor_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_IMP_Processor_Type_ID, Integer.valueOf(IMP_Processor_Type_ID)); } /** Get Import Processor Type. @return Import Processor Type */ public int getIMP_Processor_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_Processor_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java Class.
@param JavaClass Java Class */ public void setJavaClass (String JavaClass) { set_Value (COLUMNNAME_JavaClass, JavaClass); } /** Get Java Class. @return Java Class */ public String getJavaClass () { return (String)get_Value(COLUMNNAME_JavaClass); } /** 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); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor_Type.java
1
请完成以下Java代码
public static String join(Iterator<String> iterator) { StringBuilder builder = new StringBuilder(); while (iterator.hasNext()) { builder.append(iterator.next()); if (iterator.hasNext()) { builder.append(", "); } } return builder.toString(); } public abstract static class StringIterator<T> implements Iterator<String> { protected Iterator<? extends T> iterator;
public StringIterator(Iterator<? extends T> iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public void remove() { iterator.remove(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\StringUtil.java
1
请完成以下Java代码
public boolean supports(Class<?> targetType) { return Map.class.isAssignableFrom(targetType); } @SuppressWarnings("unchecked") @Override public String toCursor(Map<String, Object> keys) { return ((Encoder<Map<String, Object>>) this.encoder).encodeValue( keys, DefaultDataBufferFactory.sharedInstance, MAP_TYPE, MimeTypeUtils.APPLICATION_JSON, null).toString(StandardCharsets.UTF_8); } @SuppressWarnings("unchecked") @Override public Map<String, Object> fromCursor(String cursor) { DataBuffer buffer = this.bufferFactory.wrap(cursor.getBytes(StandardCharsets.UTF_8)); Map<String, Object> map = ((Decoder<Map<String, Object>>) this.decoder).decode(buffer, MAP_TYPE, null, null); return (map != null) ? map : Collections.emptyMap(); } /** * Customizes the {@link ObjectMapper} to use default typing that supports * {@link Date}, {@link Calendar}, {@link UUID} and classes in {@code java.time}. */ private static final class JacksonObjectMapperCustomizer { static void customize(CodecConfigurer configurer) { PolymorphicTypeValidator validator = BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Map.class) .allowIfSubType("java.time.") .allowIfSubType(Calendar.class) .allowIfSubType(Date.class) .allowIfSubType(UUID.class) .build(); JsonMapper mapper = JsonMapper.builder() .activateDefaultTyping(validator, DefaultTyping.NON_FINAL) .enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS) .build(); configurer.defaultCodecs().jacksonJsonDecoder(new JacksonJsonDecoder(mapper)); configurer.defaultCodecs().jacksonJsonEncoder(new JacksonJsonEncoder(mapper)); } } /** * Customizes the {@link ObjectMapper} to use default typing that supports * {@link Date}, {@link Calendar}, {@link UUID} and classes in {@code java.time}. */
@SuppressWarnings("removal") private static final class Jackson2ObjectMapperCustomizer { static void customize(CodecConfigurer configurer) { com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator validator = com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Map.class) .allowIfSubType("java.time.") .allowIfSubType(Calendar.class) .allowIfSubType(Date.class) .allowIfSubType(UUID.class) .build(); com.fasterxml.jackson.databind.ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build(); mapper.activateDefaultTyping(validator, com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping.NON_FINAL); mapper.enable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); configurer.defaultCodecs().jacksonJsonDecoder(new Jackson2JsonDecoder(mapper)); configurer.defaultCodecs().jacksonJsonEncoder(new Jackson2JsonEncoder(mapper)); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\query\JsonKeysetCursorStrategy.java
1
请完成以下Java代码
public String getCustomPropertiesResolverImplementation() { return customPropertiesResolverImplementation; } public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) { this.customPropertiesResolverImplementation = customPropertiesResolverImplementation; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } /** * Return the script info, if present. * <p> * ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when * implementationType is 'script'. * </p> */ @Override public ScriptInfo getScriptInfo() { return scriptInfo; } /** * Sets the script info * * @see #getScriptInfo() */
@Override public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo; } @Override public FlowableListener clone() { FlowableListener clone = new FlowableListener(); clone.setValues(this); return clone; } public void setValues(FlowableListener otherListener) { super.setValues(otherListener); setEvent(otherListener.getEvent()); setImplementation(otherListener.getImplementation()); setImplementationType(otherListener.getImplementationType()); if (otherListener.getScriptInfo() != null) { setScriptInfo(otherListener.getScriptInfo().clone()); } fieldExtensions = new ArrayList<>(); if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherListener.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } setOnTransaction(otherListener.getOnTransaction()); setCustomPropertiesResolverImplementationType(otherListener.getCustomPropertiesResolverImplementationType()); setCustomPropertiesResolverImplementation(otherListener.getCustomPropertiesResolverImplementation()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowableListener.java
1
请完成以下Java代码
private void expungeStaleEntries() { lock.lock(); try { expungeStaleEntriesAssumeSync(); } finally { lock.unlock(); } } /** * Called by {@link #expungeStaleEntries()}. This method should only be called from inside a lock. * */ @SuppressWarnings("unchecked") private final void expungeStaleEntriesAssumeSync() { ListWeakReference r; while ((r = (ListWeakReference)queue.poll()) != null) { final ListEntry le = r.getListEntry(); final int i = list.indexOf(le); if (i != -1) { list.remove(i); } } } private class ListWeakReference extends WeakReference<T> { private final ListEntry parent; public ListWeakReference(final T value, final ListEntry parent) { super(value, queue); this.parent = parent; } public ListEntry getListEntry() { return this.parent; } } private class ListEntry { final T value; final ListWeakReference weakValue; final boolean isWeak; /** * String representation of "value" (only if isWeak). * * NOTE: this variable is filled only if {@link WeakList#DEBUG} flag is set. */ final String valueStr; public ListEntry(final T value, final boolean isWeak) { if (isWeak) { this.value = null; this.weakValue = new ListWeakReference(value, this); this.isWeak = true; this.valueStr = DEBUG ? String.valueOf(value) : null; } else { this.value = value; this.weakValue = null; this.isWeak = false; this.valueStr = null; } } private boolean isAvailable() { if (isWeak) { return weakValue.get() != null; } else { return true; } } public T get() { if (isWeak) { return weakValue.get();
} else { return value; } } /** * Always compare by identity. * * @return true if it's the same instance. */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } return false; } @Override public int hashCode() { // NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning" return super.hashCode(); } @Override public String toString() { if (!isAvailable()) { return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>"; } else { return String.valueOf(this.get()); } } } /** * Gets internal lock used by this weak list. * * NOTE: use it only if you know what are you doing. * * @return internal lock used by this weak list. */ public final ReentrantLock getReentrantLock() { return lock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getType() { return type; } public void setType(String type) { this.type = type; }
public String getFullMessage() { return fullMessage; } public void setFullMessage(String fullMessage) { this.fullMessage = fullMessage; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void onSuccess(@Nullable ValidationResult result) { Futures.addCallback(attributesService.findAll(tenantId, entityId, AttributeScope.valueOf(scope)), callback, MoreExecutors.directExecutor()); } @Override public void onFailure(Throwable t) { callback.onFailure(t); } }; } private FutureCallback<ValidationResult> on(Consumer<Void> success, Consumer<Throwable> failure) { return new FutureCallback<ValidationResult>() { @Override public void onSuccess(@Nullable ValidationResult result) { ValidationResultCode resultCode = result.getResultCode(); if (resultCode == ValidationResultCode.OK) { success.accept(null); } else { onFailure(ValidationCallback.getException(result)); } } @Override public void onFailure(Throwable t) { failure.accept(t); } }; }
public static Aggregation getAggregation(String agg) { return StringUtils.isEmpty(agg) ? DEFAULT_AGGREGATION : Aggregation.valueOf(agg); } private int getLimit(int limit) { return limit == 0 ? DEFAULT_LIMIT : limit; } private DefaultTenantProfileConfiguration getTenantProfileConfiguration(WebSocketSessionRef sessionRef) { return Optional.ofNullable(tenantProfileCache.get(sessionRef.getSecurityCtx().getTenantId())) .map(TenantProfile::getDefaultProfileConfiguration).orElse(null); } public static <C extends WsCmd> WsCmdHandler<C> newCmdHandler(BiConsumer<WebSocketSessionRef, C> handler) { return new WsCmdHandler<>(handler); } @RequiredArgsConstructor @Getter @SuppressWarnings("unchecked") public static class WsCmdHandler<C extends WsCmd> { protected final BiConsumer<WebSocketSessionRef, C> handler; public void handle(WebSocketSessionRef sessionRef, WsCmd cmd) { handler.accept(sessionRef, (C) cmd); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\DefaultWebSocketService.java
2
请完成以下Java代码
public Builder setAttemptCounter(MeterProvider<Counter> counter) { this.attemptCounter = counter; return this; } public Builder setSentMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.sentMessageSizeDistribution = distribution; return this; } public Builder setReceivedMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.receivedMessageSizeDistribution = distribution; return this; }
public Builder setClientAttemptDuration(MeterProvider<Timer> timer) { this.clientAttemptDuration = timer; return this; } public Builder setClientCallDuration(MeterProvider<Timer> timer) { this.clientCallDuration = timer; return this; } public MetricsClientMeters build() { return new MetricsClientMeters(this); } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientMeters.java
1
请完成以下Java代码
public void setGrpId(String value) { this.grpId = value; } /** * Gets the value of the cpblties property. * * @return * possible object is * {@link PointOfInteractionCapabilities1 } * */ public PointOfInteractionCapabilities1 getCpblties() { return cpblties; } /** * Sets the value of the cpblties property. * * @param value * allowed object is * {@link PointOfInteractionCapabilities1 } * */ public void setCpblties(PointOfInteractionCapabilities1 value) { this.cpblties = value; } /**
* Gets the value of the cmpnt 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 cmpnt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCmpnt().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PointOfInteractionComponent1 } * * */ public List<PointOfInteractionComponent1> getCmpnt() { if (cmpnt == null) { cmpnt = new ArrayList<PointOfInteractionComponent1>(); } return this.cmpnt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteraction1.java
1
请完成以下Java代码
public class GroupImpl extends ArtifactImpl implements Group { protected static AttributeReference<CategoryValue> categoryValueRefAttribute; public GroupImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public static void registerType(ModelBuilder modelBuilder) { final ModelElementTypeBuilder typeBuilder = modelBuilder .defineType(Group.class, BPMN_ELEMENT_GROUP) .namespaceUri(BPMN20_NS) .extendsType(Artifact.class) .instanceProvider( new ModelTypeInstanceProvider<Group>() { @Override public Group newInstance(ModelTypeInstanceContext instanceContext) { return new GroupImpl(instanceContext); } }); categoryValueRefAttribute = typeBuilder .stringAttribute(BPMN_ATTRIBUTE_CATEGORY_VALUE_REF) .qNameAttributeReference(CategoryValue.class) .build(); typeBuilder.build();
} @Override public CategoryValue getCategory() { return categoryValueRefAttribute.getReferenceTargetElement(this); } @Override public void setCategory(CategoryValue categoryValue) { categoryValueRefAttribute.setReferenceTargetElement(this, categoryValue); } @Override public BpmnEdge getDiagramElement() { return (BpmnEdge) super.getDiagramElement(); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\GroupImpl.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * IsAllowIssuingAnyHU AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISALLOWISSUINGANYHU_AD_Reference_ID=319; /** Yes = Y */ public static final String ISALLOWISSUINGANYHU_Yes = "Y"; /** No = N */ public static final String ISALLOWISSUINGANYHU_No = "N"; @Override public void setIsAllowIssuingAnyHU (final @Nullable java.lang.String IsAllowIssuingAnyHU) { set_Value (COLUMNNAME_IsAllowIssuingAnyHU, IsAllowIssuingAnyHU); } @Override public java.lang.String getIsAllowIssuingAnyHU() { return get_ValueAsString(COLUMNNAME_IsAllowIssuingAnyHU); } /** * IsScanResourceRequired AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSCANRESOURCEREQUIRED_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSCANRESOURCEREQUIRED_Yes = "Y"; /** No = N */ public static final String ISSCANRESOURCEREQUIRED_No = "N"; @Override public void setIsScanResourceRequired (final @Nullable java.lang.String IsScanResourceRequired) { set_Value (COLUMNNAME_IsScanResourceRequired, IsScanResourceRequired);
} @Override public java.lang.String getIsScanResourceRequired() { return get_ValueAsString(COLUMNNAME_IsScanResourceRequired); } @Override public void setMobileUI_UserProfile_MFG_ID (final int MobileUI_UserProfile_MFG_ID) { if (MobileUI_UserProfile_MFG_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_MFG_ID, MobileUI_UserProfile_MFG_ID); } @Override public int getMobileUI_UserProfile_MFG_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_MFG_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_MFG.java
1
请完成以下Java代码
public class EmployeeCriteriaQueries { public List<Employee> getAllEmployees() { final Session session = HibernateUtil.getHibernateSession(); final CriteriaBuilder cb = session.getCriteriaBuilder(); final CriteriaQuery<Employee> cr = cb.createQuery(Employee.class); final Root<Employee> root = cr.from(Employee.class); cr.select(root); Query<Employee> query = session.createQuery(cr); List<Employee> results = query.getResultList(); session.close(); return results; } // To get items having salary more than 50000 public String[] greaterThanCriteria() { final Session session = HibernateUtil.getHibernateSession(); final CriteriaBuilder cb = session.getCriteriaBuilder();
final CriteriaQuery<Employee> cr = cb.createQuery(Employee.class); final Root<Employee> root = cr.from(Employee.class); cr.select(root) .where(cb.gt(root.get("salary"), 50000)); Query<Employee> query = session.createQuery(cr); final List<Employee> greaterThanEmployeeList = query.getResultList(); final String employeeWithGreaterSalary[] = new String[greaterThanEmployeeList.size()]; for (int i = 0; i < greaterThanEmployeeList.size(); i++) { employeeWithGreaterSalary[i] = greaterThanEmployeeList.get(i) .getName(); } session.close(); return employeeWithGreaterSalary; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\view\EmployeeCriteriaQueries.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { ActivityExecution activityExecution = (ActivityExecution) execution; readFields(activityExecution); List<String> argList = new ArrayList<>(); argList.add(commandStr); if (arg1Str != null) argList.add(arg1Str); if (arg2Str != null) argList.add(arg2Str); if (arg3Str != null) argList.add(arg3Str); if (arg4Str != null) argList.add(arg4Str); if (arg5Str != null) argList.add(arg5Str); ProcessBuilder processBuilder = new ProcessBuilder(argList); try { processBuilder.redirectErrorStream(redirectErrorFlag); if (cleanEnvBoolan) { Map<String, String> env = processBuilder.environment(); env.clear(); } if (directoryStr != null && directoryStr.length() > 0) processBuilder.directory(new File(directoryStr)); Process process = processBuilder.start(); if (waitFlag) { int errorCode = process.waitFor(); if (resultVariableStr != null) { String result = convertStreamToStr(process.getInputStream()); execution.setVariable(resultVariableStr, result); } if (errorCodeVariableStr != null) { execution.setVariable(errorCodeVariableStr, Integer.toString(errorCode)); } } } catch (Exception e) { throw new ActivitiException("Could not execute shell command ", e); } leave(activityExecution); } public static String convertStreamToStr(InputStream is) throws IOException { if (is != null) {
Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } } protected String getStringFromField(Expression expression, DelegateExecution execution) { if (expression != null) { Object value = expression.getValue(execution); if (value != null) { return value.toString(); } } return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ShellActivityBehavior.java
1
请完成以下Java代码
public static List<EngineInfo> getIdmEngineInfos() { return idmEngineInfos; } /** * Get initialization results. Only info will we available for form engines which were added in the {@link IdmEngines#init()}. No {@link EngineInfo} is available for engines which were registered * programmatically. */ public static EngineInfo getIdmEngineInfo(String idmEngineName) { return idmEngineInfosByName.get(idmEngineName); } public static IdmEngine getDefaultIdmEngine() { return getIdmEngine(NAME_DEFAULT); } /** * obtain a idm engine by name. * * @param idmEngineName is the name of the idm engine or null for the default idm engine. */ public static IdmEngine getIdmEngine(String idmEngineName) { if (!isInitialized()) { init(); } return idmEngines.get(idmEngineName); } /** * retries to initialize a idm engine that previously failed. */ public static EngineInfo retry(String resourceUrl) { LOGGER.debug("retying initializing of resource {}", resourceUrl); try { return initIdmEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new FlowableException("invalid url: " + resourceUrl, e); } } /** * provides access to idm engine to application clients in a managed server environment. */ public static Map<String, IdmEngine> getIdmEngines() { return idmEngines; } /** * closes all idm engines. This method should be called when the server shuts down. */ public static synchronized void destroy() { if (isInitialized()) { Map<String, IdmEngine> engines = new HashMap<>(idmEngines); idmEngines = new HashMap<>();
for (String idmEngineName : engines.keySet()) { IdmEngine idmEngine = engines.get(idmEngineName); try { idmEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (idmEngineName == null ? "the default idm engine" : "idm engine " + idmEngineName), e); } } idmEngineInfosByName.clear(); idmEngineInfosByResourceUrl.clear(); idmEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { IdmEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngines.java
1
请完成以下Java代码
protected ClassPathBeanDefinitionScanner newClassBeanDefinitionScanner(BeanDefinitionRegistry registry) { return new ClassPathBeanDefinitionScanner(registry, isUsingDefaultFilters(), getEnvironment()); } /** * Re-registers Singleton beans registered with the previous {@link ConfigurableListableBeanFactory BeanFactory} * (prior to refresh) with this {@link ApplicationContext}, iff this context was previously active * and subsequently refreshed. * * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#copyConfigurationFrom(ConfigurableBeanFactory) * @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerSingleton(String, Object) * @see #getBeanFactory() */ @Override protected void onRefresh() { super.onRefresh(); ConfigurableListableBeanFactory currentBeanFactory = getBeanFactory(); if (this.beanFactory != null) { Arrays.stream(ArrayUtils.nullSafeArray(this.beanFactory.getSingletonNames(), String.class)) .filter(singletonBeanName -> !currentBeanFactory.containsSingleton(singletonBeanName)) .forEach(singletonBeanName -> currentBeanFactory .registerSingleton(singletonBeanName, this.beanFactory.getSingleton(singletonBeanName))); if (isCopyConfigurationEnabled()) { currentBeanFactory.copyConfigurationFrom(this.beanFactory); } } } /** * Stores a reference to the previous {@link ConfigurableListableBeanFactory} in order to copy its configuration * and state on {@link ApplicationContext} refresh invocations. * * @see #getBeanFactory() */
@Override protected void prepareRefresh() { this.beanFactory = (DefaultListableBeanFactory) SpringExtensions.safeGetValue(this::getBeanFactory); super.prepareRefresh(); } /** * @inheritDoc */ @Override public void register(Class<?>... componentClasses) { Arrays.stream(ArrayUtils.nullSafeArray(componentClasses, Class.class)) .filter(Objects::nonNull) .forEach(this.componentClasses::add); } /** * @inheritDoc */ @Override public void scan(String... basePackages) { Arrays.stream(ArrayUtils.nullSafeArray(basePackages, String.class)) .filter(StringUtils::hasText) .forEach(this.basePackages::add); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\annotation\RefreshableAnnotationConfigApplicationContext.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> {
// For MySQL5Dialect (MyISAM) stoare engine): row-level locking not supported // For MySQL5InnoDBDialect (InnoDB storage engine): row-level locking is aquired via FOR UPDATE // For MySQL8Dialect (InnoDB storage engine): row-level locking is aquired via FOR UPDATE NOWAIT // running the below method will throw: org.hibernate.QueryTimeoutException // Caused by: com.mysql.cj.jdbc.exceptions.MySQLTimeoutException // bookstoreService.editChapterTestLocking(); // For all dialects (MySQL5Dialect, MySQL5InnoDBDialect, MySQL8Dialect) // running the below method will throw: javax.persistence.OptimisticLockException // Caused by: org.hibernate.StaleObjectStateException: bookstoreService.editChapterTestVersion(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPesimisticForceIncrement\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public void setEventDate (final @Nullable java.sql.Timestamp EventDate) { set_Value (COLUMNNAME_EventDate, EventDate); } @Override public java.sql.Timestamp getEventDate() { return get_ValueAsTimestamp(COLUMNNAME_EventDate); } /** * EventType AD_Reference_ID=540013 * Reference name: C_SubscriptionProgress EventType */ public static final int EVENTTYPE_AD_Reference_ID=540013; /** Delivery = DE */ public static final String EVENTTYPE_Delivery = "DE"; /** BeginOfPause = PB */ public static final String EVENTTYPE_BeginOfPause = "PB"; /** EndOfPause = PE */ public static final String EVENTTYPE_EndOfPause = "PE"; /** Quantity = QT */ public static final String EVENTTYPE_Quantity = "QT"; /** Price = P */ public static final String EVENTTYPE_Price = "P"; @Override public void setEventType (final java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } @Override public java.lang.String getEventType() { return get_ValueAsString(COLUMNNAME_EventType); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty);
} @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Status AD_Reference_ID=540002 * Reference name: C_SubscriptionProgress Status */ public static final int STATUS_AD_Reference_ID=540002; /** Planned = P */ public static final String STATUS_Planned = "P"; /** Open = O */ public static final String STATUS_Open = "O"; /** Delivered = D */ public static final String STATUS_Delivered = "D"; /** InPicking = C */ public static final String STATUS_InPicking = "C"; /** Done = E */ public static final String STATUS_Done = "E"; /** Delayed = H */ public static final String STATUS_Delayed = "H"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscriptionProgress.java
1
请完成以下Java代码
protected Map<String, List<ExecutableScript>> getEnv(String language) { ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration(); ProcessApplicationReference processApplication = Context.getCurrentProcessApplication(); Map<String, List<ExecutableScript>> result = null; if (config.isEnableFetchScriptEngineFromProcessApplication()) { if(processApplication != null) { result = getPaEnvScripts(processApplication); } } return result != null ? result : env; } protected Map<String, List<ExecutableScript>> getPaEnvScripts(ProcessApplicationReference pa) { try { ProcessApplicationInterface processApplication = pa.getProcessApplication(); ProcessApplicationInterface rawObject = processApplication.getRawObject(); if (rawObject instanceof AbstractProcessApplication) { AbstractProcessApplication abstractProcessApplication = (AbstractProcessApplication) rawObject; return abstractProcessApplication.getEnvironmentScripts(); } return null; } catch (ProcessApplicationUnavailableException e) { throw new ProcessEngineException("Process Application is unavailable.", e); } } protected List<ExecutableScript> getEnvScripts(ExecutableScript script, ScriptEngine scriptEngine) { List<ExecutableScript> envScripts = getEnvScripts(script.getLanguage().toLowerCase()); if (envScripts.isEmpty()) { envScripts = getEnvScripts(scriptEngine.getFactory().getLanguageName().toLowerCase()); } return envScripts; } /** * Returns the env scripts for the given language. Performs lazy initialization of the env scripts. * * @param scriptLanguage the language * @return a list of executable environment scripts. Never null. */ protected List<ExecutableScript> getEnvScripts(String scriptLanguage) { Map<String, List<ExecutableScript>> environment = getEnv(scriptLanguage); List<ExecutableScript> envScripts = environment.get(scriptLanguage); if(envScripts == null) { synchronized (this) { envScripts = environment.get(scriptLanguage); if(envScripts == null) { envScripts = initEnvForLanguage(scriptLanguage); environment.put(scriptLanguage, envScripts); } }
} return envScripts; } /** * Initializes the env scripts for a given language. * * @param language the language * @return the list of env scripts. Never null. */ protected List<ExecutableScript> initEnvForLanguage(String language) { List<ExecutableScript> scripts = new ArrayList<>(); for (ScriptEnvResolver resolver : envResolvers) { String[] resolvedScripts = resolver.resolve(language); if(resolvedScripts != null) { for (String resolvedScript : resolvedScripts) { scripts.add(scriptFactory.createScriptFromSource(language, resolvedScript)); } } } return scripts; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\env\ScriptingEnvironment.java
1
请完成以下Java代码
public void setBeanResolver(BeanResolver beanResolver) { Assert.notNull(beanResolver, "beanResolver cannot be null"); this.beanResolver = beanResolver; } /** * Configure CurrentSecurityContext template resolution * <p> * By default, this value is <code>null</code>, which indicates that templates should * not be resolved. * @param templateDefaults - whether to resolve CurrentSecurityContext templates * parameters * @since 6.4 */ public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.useAnnotationTemplate = templateDefaults != null; this.scanner = SecurityAnnotationScanners.requireUnique(CurrentSecurityContext.class, templateDefaults); } private @Nullable Object resolveSecurityContextFromAnnotation(MethodParameter parameter, CurrentSecurityContext annotation, SecurityContext securityContext) { Object securityContextResult = securityContext; String expressionToParse = annotation.expression(); if (StringUtils.hasLength(expressionToParse)) { StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(securityContext); context.setVariable("this", securityContext); // https://github.com/spring-projects/spring-framework/issues/35371 if (this.beanResolver != null) { context.setBeanResolver(this.beanResolver); } Expression expression = this.parser.parseExpression(expressionToParse); securityContextResult = expression.getValue(context); } if (securityContextResult != null && !parameter.getParameterType().isAssignableFrom(securityContextResult.getClass())) { if (annotation.errorOnInvalidType()) { throw new ClassCastException( securityContextResult + " is not assignable to " + parameter.getParameterType()); } return null; } return securityContextResult;
} /** * Obtain the specified {@link Annotation} on the specified {@link MethodParameter}. * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private @Nullable CurrentSecurityContext findMethodAnnotation(MethodParameter parameter) { if (this.useAnnotationTemplate) { return this.scanner.scan(parameter.getParameter()); } CurrentSecurityContext annotation = parameter.getParameterAnnotation(this.annotationType); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType); if (annotation != null) { return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize(); } } return null; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\method\annotation\CurrentSecurityContextArgumentResolver.java
1
请完成以下Java代码
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order) { set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order); } @Override public void setPP_Order_ID (final int PP_Order_ID) { if (PP_Order_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID); } @Override public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public org.compiere.model.I_AD_Sequence getSerialNo_Sequence() { return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence) {
set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence); } @Override public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID) { if (SerialNo_Sequence_ID < 1) set_Value (COLUMNNAME_SerialNo_Sequence_ID, null); else set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID); } @Override public int getSerialNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOM.java
1
请完成以下Java代码
private boolean isShowLoginDate() { final Properties ctx = getCtx(); // Make sure AD_Client_ID was not set if (Check.isEmpty(Env.getContext(ctx, Env.CTXNAME_AD_Client_ID), true)) { return false; } final boolean allowLoginDateOverride = m_login.isAllowLoginDateOverride(); if (allowLoginDateOverride) { return true; } final ClientId adClientId = m_login.getCtx().getClientId(); final boolean dateAutoupdate = sysConfigBL.getBooleanValue("LOGINDATE_AUTOUPDATE", false, adClientId.getRepoId()); if (dateAutoupdate) { return false; } return true; }
private boolean disposed = false; @Override public void dispose() { super.dispose(); if (disposed) { // NOTE: for some reason this method is called twice on login, so we introduced disposed flag to prevent running the code twice return; } Env.clearWinContext(getCtx(), m_WindowNo); disposed = true; } } // ALogin
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALogin.java
1
请完成以下Java代码
public List<VariableListener<?>> getVariableListenersLocal(String eventName) { List<VariableListener<?>> listenerList = getVariableListeners().get(eventName); if (listenerList != null) { return listenerList; } return Collections.emptyList(); } public List<VariableListener<?>> getBuiltInVariableListenersLocal(String eventName) { List<VariableListener<?>> listenerList = getBuiltInVariableListeners().get(eventName); if (listenerList != null) { return listenerList; } return Collections.emptyList(); } public void addListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener) { addListener(eventName, listener, -1); } public void addBuiltInListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener) { addBuiltInListener(eventName, listener, -1); } public void addBuiltInListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) { addListenerToMap(listeners, eventName, listener, index); addListenerToMap(builtInListeners, eventName, listener, index); } public void addListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) { addListenerToMap(listeners, eventName, listener, index); } protected <T> void addListenerToMap(Map<String, List<T>> listenerMap, String eventName, T listener, int index) { List<T> listeners = listenerMap.get(eventName); if (listeners == null) { listeners = new ArrayList<T>(); listenerMap.put(eventName, listeners); } if (index < 0) { listeners.add(listener);
} else { listeners.add(index, listener); } } public void addVariableListener(String eventName, VariableListener<?> listener) { addVariableListener(eventName, listener, -1); } public void addVariableListener(String eventName, VariableListener<?> listener, int index) { addListenerToMap(variableListeners, eventName, listener, index); } public void addBuiltInVariableListener(String eventName, VariableListener<?> listener) { addBuiltInVariableListener(eventName, listener, -1); } public void addBuiltInVariableListener(String eventName, VariableListener<?> listener, int index) { addListenerToMap(variableListeners, eventName, listener, index); addListenerToMap(builtInVariableListeners, eventName, listener, index); } public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getListeners() { return listeners; } public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getBuiltInListeners() { return builtInListeners; } public Map<String, List<VariableListener<?>>> getBuiltInVariableListeners() { return builtInVariableListeners; } public Map<String, List<VariableListener<?>>> getVariableListeners() { return variableListeners; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CoreModelElement.java
1
请完成以下Java代码
public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the ssn property. * * @return * possible object is * {@link String } *
*/ public String getSsn() { return ssn; } /** * Sets the value of the ssn property. * * @param value * allowed object is * {@link String } * */ public void setSsn(String value) { this.ssn = 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\MvgLawType.java
1
请完成以下Java代码
public java.lang.String getMSV3_Pzn () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Pzn); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel. @param MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel. @return MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne getMSV3_VerfuegbarkeitsanfrageEinzelne() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class); } @Override
public void setMSV3_VerfuegbarkeitsanfrageEinzelne(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne MSV3_VerfuegbarkeitsanfrageEinzelne) { set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsanfrageEinzelne.class, MSV3_VerfuegbarkeitsanfrageEinzelne); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne_Artikel.java
1