instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id private Long id; private String name; @ManyToOne @JoinColumn(name = "department_id") private Department department; public Long getId() { return id; } public void setId(Long id) { this.id = id;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\associations\biredirectional\Employee.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_ElementValue getParent() { return get_ValueAsPO(COLUMNNAME_Parent_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setParent(final org.compiere.model.I_C_ElementValue Parent) { set_ValueFromPO(COLUMNNAME_Parent_ID, org.compiere.model.I_C_ElementValue.class, Parent); } @Override public void setParent_ID (final int Parent_ID) { if (Parent_ID < 1) set_ValueNoCheck (COLUMNNAME_Parent_ID, null); else set_ValueNoCheck (COLUMNNAME_Parent_ID, Parent_ID); } @Override public int getParent_ID() { return get_ValueAsInt(COLUMNNAME_Parent_ID); } @Override public void setPostActual (final boolean PostActual) { set_Value (COLUMNNAME_PostActual, PostActual); } @Override public boolean isPostActual() { return get_ValueAsBoolean(COLUMNNAME_PostActual); } @Override public void setPostBudget (final boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, PostBudget); } @Override public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() {
return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setSeqNo (final int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @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\compiere\model\X_C_ElementValue.java
1
请在Spring Boot框架中完成以下Java代码
public void setConsume(List<PropagationType> consume) { this.consume = consume; } public @Nullable List<PropagationType> getType() { return this.type; } public List<PropagationType> getProduce() { return this.produce; } public List<PropagationType> getConsume() { return this.consume; } /** * Supported propagation types. The declared order of the values matter. */ public enum PropagationType {
/** * <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation. */ W3C, /** * <a href="https://github.com/openzipkin/b3-propagation#single-header">B3 * single header</a> propagation. */ B3, /** * <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3 * multiple headers</a> propagation. */ B3_MULTI } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java
2
请完成以下Spring Boot application配置
management: endpoint: # Info 端点配置项 info: enabled: true # 是否开启。默认为 true 开启。 info: # EnvironmentInfoContributor 的配置项 env: enabled: true # BuildInfoContributor 的配置属性 build: enabled: true # GitInfoContributor 的配置属性 git: enabled: true mode: SIMPLE # Git 信息展示模式。SIMPLE 默认,只展示精简的 Git 版本信息;FULL 模式,展示完整的 Git 版本信息。 endpoints: # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 web: base-path: /actuator # Actuator 提供的 API 接口的根目录。默认为 /actuator exposure: include: '*' # 需要开放的端点。默认值只
打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。 # info 配置项 info: app: java: source: @java.version@ target: @java.version@ encoding: UTF-8 version: @project.version@
repos\SpringBoot-Labs-master\lab-34\lab-34-actuator-demo-info\src\main\resources\application.yaml
2
请完成以下Java代码
public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getTaskId() { return taskId; } public String getTenantId() { return tenantId; } public String getUserOperationId() { return userOperationId; } public Date getTime() { return time; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) { HistoricDetailDto dto = null; if (historicDetail instanceof HistoricFormField) { HistoricFormField historicFormField = (HistoricFormField) historicDetail; dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField); } else if (historicDetail instanceof HistoricVariableUpdate) { HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail; dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate); }
fromHistoricDetail(historicDetail, dto); return dto; } protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) { dto.id = historicDetail.getId(); dto.processDefinitionKey = historicDetail.getProcessDefinitionKey(); dto.processDefinitionId = historicDetail.getProcessDefinitionId(); dto.processInstanceId = historicDetail.getProcessInstanceId(); dto.activityInstanceId = historicDetail.getActivityInstanceId(); dto.executionId = historicDetail.getExecutionId(); dto.taskId = historicDetail.getTaskId(); dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey(); dto.caseDefinitionId = historicDetail.getCaseDefinitionId(); dto.caseInstanceId = historicDetail.getCaseInstanceId(); dto.caseExecutionId = historicDetail.getCaseExecutionId(); dto.tenantId = historicDetail.getTenantId(); dto.userOperationId = historicDetail.getUserOperationId(); dto.time = historicDetail.getTime(); dto.removalTime = historicDetail.getRemovalTime(); dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDetailDto.java
1
请完成以下Spring Boot application配置
spring.ai.vectorstore.chroma.initialize-schema=true spring.ai.vectorstore.chroma.collection-name=poetries spring.ai.ollama.init.chat.include=false spring.ai.ollama.init.pull-model-s
trategy=WHEN_MISSING spring.ai.ollama.embedding.options.model=nomic-embed-text
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-chromadb.properties
2
请在Spring Boot框架中完成以下Java代码
protected KeyStore createKeyStore() { try { KeyStore store = ssl.getKeyStoreProvider() != null ? KeyStore.getInstance(ssl.getKeyStoreType(), ssl.getKeyStoreProvider()) : KeyStore.getInstance(ssl.getKeyStoreType()); try { URL url = ResourceUtils.getURL(ssl.getKeyStore()); store.load(url.openStream(), ssl.getKeyStorePassword() != null ? ssl.getKeyStorePassword().toCharArray() : null); } catch (Exception e) { throw new RuntimeException("Could not load key store '" + ssl.getKeyStore() + "'", e); } return store;
} catch (KeyStoreException | NoSuchProviderException e) { throw new RuntimeException("Could not load KeyStore for given type and provider", e); } } protected void setTrustManager(SslContextBuilder sslContextBuilder, X509Certificate... trustedX509Certificates) { sslContextBuilder.trustManager(trustedX509Certificates); } protected void setTrustManager(SslContextBuilder sslContextBuilder, TrustManagerFactory factory) { sslContextBuilder.trustManager(factory); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\AbstractSslConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteIdentityLink(@ApiParam(name = "processInstanceId") @PathVariable("processInstanceId") String processInstanceId, @ApiParam(name = "identityId") @PathVariable("identityId") String identityId, @ApiParam(name = "type") @PathVariable("type") String type) { ProcessInstance processInstance = getProcessInstanceFromRequestWithoutAccessCheck(processInstanceId); validateIdentityLinkArguments(identityId, type); IdentityLink link = getIdentityLink(identityId, type, processInstance.getId()); if (restApiInterceptor != null) { restApiInterceptor.deleteProcessInstanceIdentityLink(processInstance, link); } runtimeService.deleteUserIdentityLink(processInstance.getId(), identityId, type); } protected void validateIdentityLinkArguments(String identityId, String type) { if (identityId == null) { throw new FlowableIllegalArgumentException("IdentityId is required."); } if (type == null) { throw new FlowableIllegalArgumentException("Type is required.");
} } protected IdentityLink getIdentityLink(String identityId, String type, String processInstanceId) { // Perhaps it would be better to offer getting a single identity link // from the API List<IdentityLink> allLinks = runtimeService.getIdentityLinksForProcessInstance(processInstanceId); for (IdentityLink link : allLinks) { if (identityId.equals(link.getUserId()) && link.getType().equals(type)) { return link; } } throw new FlowableObjectNotFoundException("Could not find the requested identity link.", IdentityLink.class); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceIdentityLinkResource.java
2
请完成以下Java代码
public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getSourceProcessDefinitionId() { return sourceProcessDefinitionId; } public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { this.sourceProcessDefinitionId = sourceProcessDefinitionId; } public String getTargetProcessDefinitionId() { return targetProcessDefinitionId; }
public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public String getMigrationMessage() { return migrationMessage; } public void setMigrationMessage(String migrationMessage) { this.migrationMessage = migrationMessage; } public String getMigrationStacktrace() { return migrationStacktrace; } public void setMigrationStacktrace(String migrationStacktrace) { this.migrationStacktrace = migrationStacktrace; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\migration\ProcessInstanceBatchMigrationPartResult.java
1
请在Spring Boot框架中完成以下Java代码
public TaskExecutionProperties taskExecutionProperties() { return new TaskExecutionProperties(); } @Bean(name = EXECUTOR_TWO_BEAN_NAME) public ThreadPoolTaskExecutor threadPoolTaskExecutor() { // 创建 TaskExecutorBuilder 对象 TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties()); // 创建 ThreadPoolTaskExecutor 对象 return builder.build(); } } private static TaskExecutorBuilder createTskExecutorBuilder(TaskExecutionProperties properties) { // Pool 属性 TaskExecutionProperties.Pool pool = properties.getPool();
TaskExecutorBuilder builder = new TaskExecutorBuilder(); builder = builder.queueCapacity(pool.getQueueCapacity()); builder = builder.corePoolSize(pool.getCoreSize()); builder = builder.maxPoolSize(pool.getMaxSize()); builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout()); builder = builder.keepAlive(pool.getKeepAlive()); // Shutdown 属性 TaskExecutionProperties.Shutdown shutdown = properties.getShutdown(); builder = builder.awaitTermination(shutdown.isAwaitTermination()); builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod()); // 其它基本属性 builder = builder.threadNamePrefix(properties.getThreadNamePrefix()); // builder = builder.customizers(taskExecutorCustomizers.orderedStream()::iterator); // builder = builder.taskDecorator(taskDecorator.getIfUnique()); return builder; } }
repos\SpringBoot-Labs-master\lab-29\lab-29-async-two\src\main\java\cn\iocoder\springboot\lab29\asynctask\config\AsyncConfig.java
2
请在Spring Boot框架中完成以下Java代码
public String getTaskNameLikeIgnoreCase() { return taskNameLikeIgnoreCase; } public String getTaskDescriptionLikeIgnoreCase() { return taskDescriptionLikeIgnoreCase; } public String getTaskOwnerLikeIgnoreCase() { return taskOwnerLikeIgnoreCase; } public String getTaskAssigneeLikeIgnoreCase() { return taskAssigneeLikeIgnoreCase; } public boolean isWithoutDeleteReason() { return withoutDeleteReason; } public String getLocale() { return locale; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionKeyLike() { return caseDefinitionKeyLike; } public String getCaseDefinitionKeyLikeIgnoreCase() { return caseDefinitionKeyLikeIgnoreCase; } public Collection<String> getCaseDefinitionKeys() { return caseDefinitionKeys; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; }
public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; } public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public Set<String> getScopeIds() { return scopeIds; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskInstanceQueryImpl.java
2
请完成以下Java代码
class ServletWebServerApplicationContextLocalTestWebServerProvider implements LocalTestWebServer.Provider { private final @Nullable ServletWebServerApplicationContext context; ServletWebServerApplicationContextLocalTestWebServerProvider(ApplicationContext context) { this.context = getWebServerApplicationContextIfPossible(context); } static @Nullable ServletWebServerApplicationContext getWebServerApplicationContextIfPossible( ApplicationContext context) { try { return (ServletWebServerApplicationContext) context; } catch (NoClassDefFoundError | ClassCastException ex) { return null; } } @Override public @Nullable LocalTestWebServer getLocalTestWebServer() { if (this.context == null) { return null;
} return LocalTestWebServer.of((isSslEnabled(this.context)) ? Scheme.HTTPS : Scheme.HTTP, () -> { int port = this.context.getEnvironment().getProperty("local.server.port", Integer.class, 8080); String path = this.context.getEnvironment().getProperty("server.servlet.context-path", ""); return new BaseUriDetails(port, path); }); } private boolean isSslEnabled(ServletWebServerApplicationContext context) { try { AbstractConfigurableWebServerFactory webServerFactory = context .getBean(AbstractConfigurableWebServerFactory.class); return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled(); } catch (NoSuchBeanDefinitionException ex) { return false; } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContextLocalTestWebServerProvider.java
1
请完成以下Java代码
private boolean huEditorWasNotOpenedFromADDOrderLine() { final ViewId parentViewId = getView().getParentViewId(); if (parentViewId == null || getView().getParentRowId() == null) { return true; } final String parentViewTableName = viewsRepository.getView(parentViewId).getTableNameOrNull(); return !I_DD_OrderLine.Table_Name.equals(parentViewTableName); } private boolean selectedRowIsNotATopHU() { return getView(HUEditorView.class) .streamByIds(getSelectedRowIds()) .noneMatch(HUEditorRow::isTopLevel); } @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final I_DD_OrderLine ddOrderLine = getViewSelectedDDOrderLine(); final String parameterName = parameter.getColumnName(); if (PARAM_M_HU_ID.equals(parameterName)) { return getRecord_ID(); } else if (PARAM_DD_ORDER_LINE_ID.equals(parameterName)) { return ddOrderLine.getDD_OrderLine_ID();
} else if (PARAM_LOCATOR_TO_ID.equals(parameterName)) { return ddOrderLine.getM_LocatorTo_ID(); } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } private I_DD_OrderLine getViewSelectedDDOrderLine() { final DDOrderLineId ddOrderLineId = getViewSelectedDDOrderLineId(); return ddOrderService.getLineById(ddOrderLineId); } @NonNull private DDOrderLineId getViewSelectedDDOrderLineId() { final ViewId parentViewId = getView().getParentViewId(); final DocumentIdsSelection selectedParentRow = DocumentIdsSelection.of(ImmutableList.of(getView().getParentRowId())); final int selectedOrderLineId = viewsRepository.getView(parentViewId) .streamByIds(selectedParentRow) .findFirst() .orElseThrow(() -> new AdempiereException("No DD_OrderLine was selected!")) .getFieldValueAsInt(I_DD_OrderLine.COLUMNNAME_DD_OrderLine_ID, -1); return DDOrderLineId.ofRepoId(selectedOrderLineId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_DD_OrderLine_MoveSelected_HU.java
1
请完成以下Java代码
private void closeAllGroupsExcept(@Nullable final GroupType exceptGroup) { final Iterator<GroupType> groups = _itemHashKey2group.values().iterator(); while (groups.hasNext()) { final GroupType group = groups.next(); if (group == null) { continue; } // Skip the excepted group if (group == exceptGroup) { continue; } closeGroupAndCollect(group); groups.remove(); } }
/** * @return how many groups were created */ public final int getGroupsCount() { return _countGroups; } /** * @return how many items were added */ public final int getItemsCount() { return _countItems; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MapReduceAggregator.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> uploadMinio(HttpServletRequest request) throws Exception { Result<?> result = new Result<>(); // 获取业务路径 String bizPath = request.getParameter("biz"); // 获取上传文件对象 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); // 文件安全校验,防止上传漏洞文件 SsrfFileTypeFilter.checkUploadFileType(file, bizPath); if(oConvertUtils.isEmpty(bizPath)){ bizPath = ""; } // 获取文件名
String orgName = file.getOriginalFilename(); orgName = CommonUtils.getFileName(orgName); String fileUrl = MinioUtil.upload(file,bizPath); if(oConvertUtils.isEmpty(fileUrl)){ return Result.error("上传失败,请检查配置信息是否正确!"); } //保存文件信息 OssFile minioFile = new OssFile(); minioFile.setFileName(orgName); minioFile.setUrl(fileUrl); ossFileService.save(minioFile); result.setMessage(fileUrl); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysUploadController.java
2
请完成以下Java代码
public void updateOrderLineRecordAndDoNotSave(@NonNull final I_C_OrderLine orderLineRecord) { // we use the date at which the order needs to be ready for shipping final ZonedDateTime preparationDate = TimeUtil.asZonedDateTime(orderLineRecord.getC_Order().getPreparationDate()); final OrderLineKey orderLineKey = createOrderKeyForOrderLineRecord(orderLineRecord); final AvailableToPromiseQuery query = createSingleQuery(preparationDate, orderLineKey); final BigDecimal result = stockRepository.retrieveAvailableStockQtySum(query); orderLineRecord.setQty_AvailableToPromise(result); } private static AvailableToPromiseQuery createSingleQuery( @NonNull final ZonedDateTime preparationDate, @NonNull final OrderLineKey orderLineKey) { final AvailableToPromiseQuery query = AvailableToPromiseQuery .builder() .productId(orderLineKey.getProductId()) .storageAttributesKeyPattern(AttributesKeyPatternsUtil.ofAttributeKey(orderLineKey.getAttributesKey())) .bpartner(orderLineKey.getBpartner()) .date(preparationDate) .build(); return query; } private OrderLineKey createOrderKeyForOrderLineRecord(@NonNull final I_C_OrderLine orderLineRecord) { final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(orderLineRecord, AttributesKey.ALL); final BPartnerId bpartnerId = BPartnerId.ofRepoId(orderLineRecord.getC_BPartner_ID()); // this column is mandatory and always > 0 return new OrderLineKey( productDescriptor.getProductId(), productDescriptor.getStorageAttributesKey(), BPartnerClassifier.specific(bpartnerId)); } @Value private static class OrderLineKey
{ int productId; AttributesKey attributesKey; BPartnerClassifier bpartner; private static OrderLineKey forResultGroup(@NonNull final AvailableToPromiseResultGroup resultGroup) { return new OrderLineKey( resultGroup.getProductId().getRepoId(), resultGroup.getStorageAttributesKey(), resultGroup.getBpartner()); } private OrderLineKey( final int productId, @NonNull final AttributesKey attributesKey, @NonNull final BPartnerClassifier bpartner) { this.productId = productId; this.attributesKey = attributesKey; this.bpartner = bpartner; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\interceptor\OrderAvailableToPromiseTool.java
1
请完成以下Spring Boot application配置
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring-security-jwt?useUnicode=true&characte
rEncoding=utf-8&useSSL=false username: root password: root
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\resources\application.yml
2
请完成以下Java代码
public int getC_DocLine_Sort_Item_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocLine_Sort_Item_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocLine_Sort_Item.java
1
请完成以下Java代码
public class ArrayConcatUtil { private ArrayConcatUtil() {} static <T> T[] concatWithCollection(T[] array1, T[] array2) { List<T> resultList = new ArrayList<>(array1.length + array2.length); Collections.addAll(resultList, array1); Collections.addAll(resultList, array2); @SuppressWarnings("unchecked") //the type cast is safe as the array1 has the type T[] T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0); return resultList.toArray(resultArray); } static <T> T[] concatWithArrayCopy(T[] array1, T[] array2) { T[] result = Arrays.copyOf(array1, array1.length + array2.length); System.arraycopy(array2, 0, result, array1.length, array2.length); return result; } static <T> T concatWithCopy2(T array1, T array2) { if (!array1.getClass().isArray() || !array2.getClass().isArray()) { throw new IllegalArgumentException("Only arrays are accepted."); } Class<?> compType1 = array1.getClass().getComponentType(); Class<?> compType2 = array2.getClass().getComponentType(); if (!compType1.equals(compType2)) { throw new IllegalArgumentException("Two arrays have different types."); } int len1 = Array.getLength(array1); int len2 = Array.getLength(array2); @SuppressWarnings("unchecked")
//the cast is safe due to the previous checks T result = (T) Array.newInstance(compType1, len1 + len2); System.arraycopy(array1, 0, result, 0, len1); System.arraycopy(array2, 0, result, len1, len2); return result; } @SuppressWarnings("unchecked") static <T> T[] concatWithStream(T[] array1, T[] array2) { return Stream.concat(Arrays.stream(array1), Arrays.stream(array2)) .toArray(size -> (T[]) Array.newInstance(array1.getClass().getComponentType(), size)); } static int[] concatIntArraysWithIntStream(int[] array1, int[] array2) { return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray(); } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\arrayconcat\ArrayConcatUtil.java
1
请完成以下Java代码
public static Set<String> getInvolvedCaseInstanceIds(CommandContext commandContext) { Object obj = commandContext.getAttribute(ATTRIBUTE_INVOLVED_CASE_INSTANCE_IDS); if (obj != null) { return (Set<String>) obj; } return null; } public static CaseInstanceHelper getCaseInstanceHelper() { return getCaseInstanceHelper(getCommandContext()); } public static CaseInstanceHelper getCaseInstanceHelper(CommandContext commandContext) { return getCmmnEngineConfiguration(commandContext).getCaseInstanceHelper(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } public static DmnEngineConfigurationApi getDmnEngineConfiguration(CommandContext commandContext) { return (DmnEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_DMN_ENGINE_CONFIG); }
public static DmnDecisionService getDmnRuleService(CommandContext commandContext) { DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration(commandContext); if (dmnEngineConfiguration == null) { throw new FlowableException("Dmn engine is not configured"); } return dmnEngineConfiguration.getDmnDecisionService(); } public static InternalTaskAssignmentManager getInternalTaskAssignmentManager(CommandContext commandContext) { return getCmmnEngineConfiguration(commandContext).getTaskServiceConfiguration().getInternalTaskAssignmentManager(); } public static InternalTaskAssignmentManager getInternalTaskAssignmentManager() { return getInternalTaskAssignmentManager(getCommandContext()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\CommandContextUtil.java
1
请完成以下Java代码
protected static class DefaultJacksonCodecs { private static final JsonMapper JSON_MAPPER = JsonMapper.builder() .addModule(new GraphQlJacksonModule()).build(); static Encoder<?> encoder() { return new JacksonJsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON); } static Decoder<?> decoder() { return new JacksonJsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE); } } @SuppressWarnings("removal")
protected static class DefaultJackson2Codecs { private static final com.fasterxml.jackson.databind.ObjectMapper JSON_MAPPER = Jackson2ObjectMapperBuilder.json().modulesToInstall(new GraphQlJackson2Module()).build(); static Encoder<?> encoder() { return new Jackson2JsonEncoder(JSON_MAPPER, MediaType.APPLICATION_JSON); } static Decoder<?> decoder() { return new Jackson2JsonDecoder(JSON_MAPPER, MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\AbstractGraphQlClientBuilder.java
1
请完成以下Java代码
public void setCity (final @Nullable java.lang.String City) { set_Value (COLUMNNAME_City, City); } @Override public java.lang.String getCity() { return get_ValueAsString(COLUMNNAME_City); } @Override public void setES_DocumentId (final java.lang.String ES_DocumentId) { set_ValueNoCheck (COLUMNNAME_ES_DocumentId, ES_DocumentId); } @Override public java.lang.String getES_DocumentId() { return get_ValueAsString(COLUMNNAME_ES_DocumentId); } @Override public void setFirstname (final @Nullable java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return get_ValueAsString(COLUMNNAME_Firstname); } @Override public void setIsCompany (final boolean IsCompany) { set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany); } @Override public boolean isCompany() { return get_ValueAsBoolean(COLUMNNAME_IsCompany); } @Override public void setLastname (final @Nullable java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); }
@Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); } @Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final @Nullable 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\compiere\model\X_C_BPartner_Adv_Search.java
1
请在Spring Boot框架中完成以下Java代码
public class InMemoryBookService implements BookService { static Map<Long, Book> booksDB = new HashMap<>(); @Override public List<Book> findAll() { return new ArrayList<>(booksDB.values()); } @Override public void saveAll(List<Book> books) { long nextId = getNextId(); for (Book book : books) { if (book.getId() == 0) { book.setId(nextId++); } }
Map<Long, Book> bookMap = books.stream() .collect(Collectors.toMap(Book::getId, Function.identity())); booksDB.putAll(bookMap); } private Long getNextId() { return booksDB.keySet() .stream() .mapToLong(value -> value) .max() .orElse(0) + 1; } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\listbindingexample\InMemoryBookService.java
2
请完成以下Java代码
public static Optional<Integer> getCpuCount() { try { return Optional.of(HARDWARE.getProcessor().getLogicalProcessorCount()); } catch (Throwable e) { log.debug("Failed to get total cpu count!!!", e); } return Optional.empty(); } public static Optional<Integer> getDiscSpaceUsage() { try { FileStore store = Files.getFileStore(Paths.get("/")); long total = store.getTotalSpace(); long available = store.getUsableSpace(); return Optional.of(toPercent(total - available, total)); } catch (Throwable e) { log.debug("Failed to get free disc space!!!", e); } return Optional.empty(); }
public static Optional<Long> getTotalDiscSpace() { try { FileStore store = Files.getFileStore(Paths.get("/")); return Optional.of(store.getTotalSpace()); } catch (Throwable e) { log.debug("Failed to get total disc space!!!", e); } return Optional.empty(); } private static int toPercent(long used, long total) { BigDecimal u = new BigDecimal(used); BigDecimal t = new BigDecimal(total); BigDecimal i = new BigDecimal(100); return u.multiply(i).divide(t, RoundingMode.HALF_UP).intValue(); } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\SystemUtil.java
1
请完成以下Java代码
private static <T> JAXBElement<T> unmarshal( @NonNull final JAXBContext jaxbContext, @NonNull final InputStream xmlInput) throws JAXBException { final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); @SuppressWarnings("unchecked") final JAXBElement<T> jaxbElement = (JAXBElement<T>)unmarshaller.unmarshal(xmlInput); return jaxbElement; } public static <T> void marshal( @NonNull final JAXBElement<T> jaxbElement, @NonNull final Class<T> jaxbType, @NonNull final String xsdName, @NonNull final OutputStream outputStream, final boolean prettyPrint ) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(jaxbType.getPackage().getName());
final Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name()); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, xsdName); // important; for us, finding the correct converter depends on the schema location if (prettyPrint) { marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); } // we want the XML header to have " (just like all the rest of the XML) and not ' // background: some systems that shall be able to work with our XML have issues with the single quote in the XML header // https://stackoverflow.com/questions/18451870/altering-the-xml-header-produced-by-the-jaxb-marshaller/32892565 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // let the marshaler *not* provide stupid single-quote header marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // let the marshaller provide our header marshaller.marshal(jaxbElement, outputStream); } catch (final JAXBException | FactoryConfigurationError e) { throw new RuntimeException(e); } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\JaxbUtil.java
1
请完成以下Spring Boot application配置
spring.task.execution.pool.core-size=2 spring.task.execution.pool.max-size=5 spring.task.execution.pool.queue-capacity=10 spring.task.execution.pool.keep-alive=60s spring.task.execution.pool.allow-core-thread-timeout=true spring.task.execution.thread-name-prefix=task-
spring.task.execution.shutdown.await-termination=false spring.task.execution.shutdown.await-termination-period=30s
repos\SpringBoot-Learning-master\2.x\chapter7-6\src\main\resources\application.properties
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Org_Mapping_ID (final int AD_Org_Mapping_ID) { if (AD_Org_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, AD_Org_Mapping_ID); } @Override public int getAD_Org_Mapping_ID() { return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) {
if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setValue (final @Nullable 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\compiere\model\X_AD_Org_Mapping.java
1
请在Spring Boot框架中完成以下Java代码
public void setDDATE1(DDATE1 value) { this.ddate1 = value; } /** * Gets the value of the damou1 property. * * @return * possible object is * {@link DAMOU1 } * */ public DAMOU1 getDAMOU1() { return damou1; } /** * Sets the value of the damou1 property. * * @param value * allowed object is * {@link DAMOU1 } * */ public void setDAMOU1(DAMOU1 value) { this.damou1 = value; } /** * Gets the value of the dtext1 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 dtext1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDTEXT1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DTEXT1 } * * */ public List<DTEXT1> getDTEXT1() { if (dtext1 == null) { dtext1 = new ArrayList<DTEXT1>(); } return this.dtext1; } /** * Gets the value of the dpric1 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 dpric1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDPRIC1().add(newItem); * </pre> * * * <p>
* Objects of the following type(s) are allowed in the list * {@link DPRIC1 } * * */ public List<DPRIC1> getDPRIC1() { if (dpric1 == null) { dpric1 = new ArrayList<DPRIC1>(); } return this.dpric1; } /** * Gets the value of the drefe1 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 drefe1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDREFE1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DREFE1 } * * */ public List<DREFE1> getDREFE1() { if (drefe1 == null) { drefe1 = new ArrayList<DREFE1>(); } return this.drefe1; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_orders\de\metas\edi\esb\jaxb\stepcom\orders\DETAILXbest.java
2
请完成以下Java代码
public String getDepartNameAbbr() { return departNameAbbr; } public void setDepartNameAbbr(String departNameAbbr) { this.departNameAbbr = departNameAbbr; } public Integer getDepartOrder() { return departOrder; } public void setDepartOrder(Integer departOrder) { this.departOrder = departOrder; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOrgCategory() { return orgCategory; } public void setOrgCategory(String orgCategory) { this.orgCategory = orgCategory; } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType; } public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; }
public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java
1
请完成以下Spring Boot application配置
com.auth0.domain: dev-example.auth0.com com.auth0.clientId: exampleClientId com.auth0.clientSecret: exampleClientSecret com.auth0.managementApi.clientId: exampleManagementApiClientId com.auth0.managementApi.clientS
ecret: exampleManagementApiClientSecret com.auth0.managementApi.grantType: client_credentials
repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public XMLGregorianCalendar getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setValue(XMLGregorianCalendar value) { this.value = value; } /** * Gets the value of the dateFunctionCodeQualifier property. * * @return * possible object is * {@link String } * */ public String getDateFunctionCodeQualifier() { return dateFunctionCodeQualifier; } /** * Sets the value of the dateFunctionCodeQualifier property. * * @param value * allowed object is * {@link String } * */ public void setDateFunctionCodeQualifier(String value) { this.dateFunctionCodeQualifier = value; } /** * Gets the value of the dateFormatCode property. * * @return * possible object is * {@link String } * */
public String getDateFormatCode() { return dateFormatCode; } /** * Sets the value of the dateFormatCode property. * * @param value * allowed object is * {@link String } * */ public void setDateFormatCode(String value) { this.dateFormatCode = value; } } } } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ListLineItemExtensionType.java
2
请完成以下Java代码
public static CurrencyId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<CurrencyId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final CurrencyId currencyId) { return currencyId != null ? currencyId.getRepoId() : -1; } int repoId; private CurrencyId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Currency_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CurrencyId currencyId1, @Nullable final CurrencyId currencyId2) { return Objects.equals(currencyId1, currencyId2); } @NonNull @SafeVarargs public static <T> CurrencyId getCommonCurrencyIdOfAll( @NonNull final Function<T, CurrencyId> getCurrencyId, @NonNull final String name, @Nullable final T... objects) { if (objects == null || objects.length == 0) { throw new AdempiereException("No " + name + " provided"); } else if (objects.length == 1 && objects[0] != null) { return getCurrencyId.apply(objects[0]); } else { CurrencyId commonCurrencyId = null; for (final T object : objects) { if (object == null) { continue; } final CurrencyId currencyId = getCurrencyId.apply(object); if (commonCurrencyId == null) { commonCurrencyId = currencyId; } else if (!CurrencyId.equals(commonCurrencyId, currencyId)) { throw new AdempiereException("All given " + name + "(s) shall have the same currency: " + Arrays.asList(objects)); } } if (commonCurrencyId == null) { throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects));
} return commonCurrencyId; } } @SafeVarargs public static <T> void assertCurrencyMatching( @NonNull final Function<T, CurrencyId> getCurrencyId, @NonNull final String name, @Nullable final T... objects) { if (objects == null || objects.length <= 1) { return; } CurrencyId expectedCurrencyId = null; for (final T object : objects) { if (object == null) { continue; } final CurrencyId currencyId = getCurrencyId.apply(object); if (expectedCurrencyId == null) { expectedCurrencyId = currencyId; } else if (!CurrencyId.equals(currencyId, expectedCurrencyId)) { throw new AdempiereException("" + name + " has invalid currency: " + object + ". Expected: " + expectedCurrencyId); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\CurrencyId.java
1
请在Spring Boot框架中完成以下Java代码
public class BlogPost { @Id @GeneratedValue private Long id; private String title; private String body; @ManyToOne private User user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String code) { this.title = code; } public String getBody() {
return body; } public void setBody(String body) { this.body = body; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\querydsl\intro\entities\BlogPost.java
2
请完成以下Java代码
private ListMultimap<GroupTemplate, OrderLineId> extractOrderLineIdsByGroupTemplate(final List<I_C_OrderLine> orderLines) { final List<I_C_OrderLine> orderLinesSorted = orderLines.stream() .sorted(Comparator.comparing(I_C_OrderLine::getLine)) .collect(ImmutableList.toImmutableList()); final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = LinkedListMultimap.create(); for (final I_C_OrderLine orderLine : orderLinesSorted) { final GroupTemplate groupTemplate = extractGroupTemplate(orderLine); if (groupTemplate == null) { continue; } orderLineIdsByGroupTemplate.put(groupTemplate, OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())); } return orderLineIdsByGroupTemplate; } @Nullable private GroupTemplate extractGroupTemplate(final I_C_OrderLine orderLine) { final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID()); if (productId == null) { return null; } final IProductDAO productsRepo = Services.get(IProductDAO.class); final ProductCategoryId productCategoryId = productsRepo.retrieveProductCategoryByProductId(productId);
final I_M_Product_Category productCategory = productsRepo.getProductCategoryById(productCategoryId, I_M_Product_Category.class); final GroupTemplateId groupTemplateId = GroupTemplateId.ofRepoIdOrNull(productCategory.getC_CompensationGroup_Schema_ID()); if (groupTemplateId == null) { return null; } return groupTemplateRepo.getById(groupTemplateId); } private Group createGroup(final GroupTemplate groupTemplate, final Collection<OrderLineId> orderLineIds) { return groupsRepo.prepareNewGroup() .groupTemplate(groupTemplate) .createGroup(orderLineIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\C_Order_CreateCompensationMultiGroups.java
1
请在Spring Boot框架中完成以下Java代码
public void createExecutionVariableAsync(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId, HttpServletRequest request, HttpServletResponse response) { Execution execution = getExecutionFromRequestWithoutAccessCheck(processInstanceId); createExecutionVariable(execution, false, true, request, response); } // FIXME Documentation @ApiOperation(value = "Delete all variables", tags = { "Process Instance Variables" }, nickname = "deleteLocalProcessVariable", code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates variables were found and have been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested process instance was not found.") }) @DeleteMapping(value = "/runtime/process-instances/{processInstanceId}/variables") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteLocalVariables(@ApiParam(name = "processInstanceId") @PathVariable String processInstanceId) { Execution execution = getExecutionFromRequestWithoutAccessCheck(processInstanceId); deleteAllLocalVariables(execution); } @Override protected void addGlobalVariables(Execution execution, Map<String, RestVariable> variableMap) {
// no global variables } // For process instance there's only one scope. Using the local variables // method for that @Override protected void addLocalVariables(Execution execution, Map<String, RestVariable> variableMap) { Map<String, Object> rawVariables = runtimeService.getVariables(execution.getId()); List<RestVariable> globalVariables = restResponseFactory.createRestVariables(rawVariables, execution.getId(), variableType, RestVariableScope.LOCAL); // Overlay global variables over local ones. In case they are present // the values are not overridden, // since local variables get precedence over global ones at all times. for (RestVariable var : globalVariables) { if (!variableMap.containsKey(var.getName())) { variableMap.put(var.getName(), var); } } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceVariableCollectionResource.java
2
请完成以下Java代码
public void setC_AcctSchema(final org.compiere.model.I_C_AcctSchema C_AcctSchema) { set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema); } @Override public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setM_CostElement_Acct_ID (final int M_CostElement_Acct_ID) { if (M_CostElement_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_Acct_ID, M_CostElement_Acct_ID); } @Override public int getM_CostElement_Acct_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_Acct_ID); } @Override public org.compiere.model.I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class); } @Override public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
} @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } @Override public org.compiere.model.I_C_ValidCombination getP_CostClearing_A() { return get_ValueAsPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setP_CostClearing_A(final org.compiere.model.I_C_ValidCombination P_CostClearing_A) { set_ValueFromPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class, P_CostClearing_A); } @Override public void setP_CostClearing_Acct (final int P_CostClearing_Acct) { set_Value (COLUMNNAME_P_CostClearing_Acct, P_CostClearing_Acct); } @Override public int getP_CostClearing_Acct() { return get_ValueAsInt(COLUMNNAME_P_CostClearing_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostElement_Acct.java
1
请完成以下Java代码
private void formatDeviceProfileCertificate(DeviceProfile deviceProfile, X509CertificateChainProvisionConfiguration x509Configuration) { String formattedCertificateValue = formatCertificateValue(x509Configuration.getProvisionDeviceSecret()); String cert = fetchLeafCertificateFromChain(formattedCertificateValue); String sha3Hash = EncryptionUtil.getSha3Hash(cert); DeviceProfileData deviceProfileData = deviceProfile.getProfileData(); x509Configuration.setProvisionDeviceSecret(formattedCertificateValue); deviceProfileData.setProvisionConfiguration(x509Configuration); deviceProfile.setProfileData(deviceProfileData); deviceProfile.setProvisionDeviceKey(sha3Hash); } private String fetchLeafCertificateFromChain(String value) { String regex = "-----BEGIN CERTIFICATE-----\\s*.*?\\s*-----END CERTIFICATE-----"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(value); if (matcher.find()) { // if the method receives a chain it fetches the leaf (end-entity) certificate, else if it gets a single certificate, it returns the single certificate return matcher.group(0); }
return value; } private String formatCertificateValue(String certificateValue) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream inputStream = new ByteArrayInputStream(certificateValue.getBytes()); Certificate[] certificates = cf.generateCertificates(inputStream).toArray(new Certificate[0]); if (certificates.length > 1) { return EncryptionUtil.certTrimNewLinesForChainInDeviceProfile(certificateValue); } } catch (CertificateException ignored) {} return EncryptionUtil.certTrimNewLines(certificateValue); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\device\DeviceProfileServiceImpl.java
1
请完成以下Java代码
protected List<URL> getDeploymentDescriptorUrls(final Module module, String[] deploymentDescriptors) throws DeploymentUnitProcessingException { List<URL> deploymentDescriptorURLs = new ArrayList<URL>(); for (String deploymentDescriptor : deploymentDescriptors) { Enumeration<URL> resources = null; try { resources = module.getClassLoader().getResources(deploymentDescriptor); } catch (IOException e) { throw new DeploymentUnitProcessingException("Could not load processes.xml resource: ", e); } while (resources.hasMoreElements()) { deploymentDescriptorURLs.add(resources.nextElement()); } } return deploymentDescriptorURLs; } protected String[] getDeploymentDescriptors(DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final ComponentDescription processApplicationComponent = ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit); final String paClassName = processApplicationComponent.getComponentClassName(); String[] deploymentDescriptorResourceNames = null; Module module = deploymentUnit.getAttachment(MODULE); Class<?> paClass = null; try { paClass = module.getClassLoader().loadClass(paClassName); } catch (ClassNotFoundException e) { throw new DeploymentUnitProcessingException("Unable to load process application class '"+paClassName+"'."); } ProcessApplication annotation = paClass.getAnnotation(ProcessApplication.class); if(annotation == null) { deploymentDescriptorResourceNames = new String[]{ PROCESSES_XML }; } else { deploymentDescriptorResourceNames = annotation.deploymentDescriptors(); } return deploymentDescriptorResourceNames; } protected Enumeration<URL> getProcessesXmlResources(Module module, String[] deploymentDescriptors) throws DeploymentUnitProcessingException { try { return module.getClassLoader().getResources(PROCESSES_XML); } catch (IOException e) { throw new DeploymentUnitProcessingException(e); } }
protected VirtualFile getFile(URL processesXmlResource) throws DeploymentUnitProcessingException { try { return VFS.getChild(processesXmlResource.toURI()); } catch(Exception e) { throw new DeploymentUnitProcessingException(e); } } protected boolean isEmptyFile(URL url) { InputStream inputStream = null; try { inputStream = url.openStream(); return inputStream.available() == 0; } catch (IOException e) { throw new ProcessEngineException("Could not open stream for " + url, e); } finally { IoUtil.closeSilently(inputStream); } } protected ProcessesXml parseProcessesXml(URL url) { final ProcessesXmlParser processesXmlParser = new ProcessesXmlParser(); ProcessesXml processesXml = processesXmlParser.createParse() .sourceUrl(url) .execute() .getProcessesXml(); return processesXml; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessesXmlProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public LegacyEndpointConverter beansLegacyEndpointConverter() { return LegacyEndpointConverters.beans(); } @Bean @ConditionalOnMissingBean(name = "configpropsLegacyEndpointConverter") public LegacyEndpointConverter configpropsLegacyEndpointConverter() { return LegacyEndpointConverters.configprops(); } @Bean @ConditionalOnMissingBean(name = "mappingsLegacyEndpointConverter") public LegacyEndpointConverter mappingsLegacyEndpointConverter() { return LegacyEndpointConverters.mappings(); } @Bean @ConditionalOnMissingBean(name = "startupLegacyEndpointConverter") public LegacyEndpointConverter startupLegacyEndpointConverter() { return LegacyEndpointConverters.startup(); } } @Configuration(proxyBeanMethods = false) protected static class CookieStoreConfiguration { /** * Creates a default {@link PerInstanceCookieStore} that should be used. * @return the cookie store */ @Bean @ConditionalOnMissingBean
public PerInstanceCookieStore cookieStore() { return new JdkPerInstanceCookieStore(CookiePolicy.ACCEPT_ORIGINAL_SERVER); } /** * Creates a default trigger to cleanup the cookie store on deregistering of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance}. * @param publisher publisher of {@link InstanceEvent}s events * @param cookieStore the store to inform about deregistration of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance} * @return a new trigger */ @Bean(initMethod = "start", destroyMethod = "stop") @ConditionalOnMissingBean public CookieStoreCleanupTrigger cookieStoreCleanupTrigger(final Publisher<InstanceEvent> publisher, final PerInstanceCookieStore cookieStore) { return new CookieStoreCleanupTrigger(publisher, cookieStore); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerInstanceWebClientConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void changeCurrentRefundConfig(@NonNull final RefundConfig refundConfig) { assertCorrectRefundBase(refundConfig); this.formerRefundConfig = this.currentRefundConfig; this.currentRefundConfig = refundConfig; } private void assertCorrectRefundBase(final RefundConfig refundConfig) { Check.errorUnless(getExpectedRefundBase().equals(refundConfig.getRefundBase()), "The given currentRefundConfig needs to have refundBase = AMOUNT_PER_UNIT; currentRefundConfig={}", refundConfig); } /**
* @return the refund config that was the current config before {@link #currentRefundConfig(RefundConfig)} was called. */ public RefundConfig getFormerRefundConfig() { return Check.assumeNotNull(formerRefundConfig, "formerRefundConfig may not be null; invoke the currentRefundConfig() method first; this={}", this); } /** * @param existingAssignment an assignment that belongs to the refund config from {@link #getFormerRefundConfig()}. * @return a new assignment that belongs to the refund config that was last set using {@link #currentRefundConfig(RefundConfig)}. */ public abstract AssignmentToRefundCandidate createNewAssignment(AssignmentToRefundCandidate existingAssignment); protected abstract RefundBase getExpectedRefundBase(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\allqties\refundconfigchange\RefundConfigChangeHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class ProductPrice { @NonNull OrgId orgId; @NonNull ProductId productId; @NonNull ProductPriceId productPriceId; @NonNull PriceListVersionId priceListVersionId; @NonNull BigDecimal priceStd; @NonNull @Builder.Default BigDecimal priceList = BigDecimal.ZERO; @NonNull
@Builder.Default BigDecimal priceLimit = BigDecimal.ZERO; @NonNull TaxCategoryId taxCategoryId; @Nullable String internalName; @NonNull Boolean isActive; @NonNull UomId uomId; @NonNull Integer seqNo; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\productprice\ProductPrice.java
2
请完成以下Java代码
public void onLocationChanged(@NonNull final I_C_BPartner_Location_QuickInput record) { final LocationId id = LocationId.ofRepoIdOrNull(record.getC_Location_ID()); if (id == null) { return; } final I_C_Location locationRecord = locationDAO.getById(id); if (locationRecord == null) { // location not yet created. Nothing to do yet return; } final POInfo poInfo = POInfo.getPOInfo(I_C_BPartner_Location_QuickInput.Table_Name); // gh12157: Please, keep in sync with org.compiere.model.MBPartnerLocation.beforeSave final String name = MakeUniqueLocationNameCommand.builder() .name(record.getName()) .address(locationRecord) .companyName(getCompanyNameOrNull(record))
.existingNames(repo.getOtherLocationNames(record.getC_BPartner_QuickInput_ID(), record.getC_BPartner_Location_QuickInput_ID())) .maxLength(poInfo.getFieldLength(I_C_BPartner_Location_QuickInput.COLUMNNAME_Name)) .build() .execute(); record.setName(name); } @Nullable private String getCompanyNameOrNull(@NonNull final I_C_BPartner_Location_QuickInput record) { final BPartnerQuickInputId bpartnerQuickInputId = BPartnerQuickInputId.ofRepoIdOrNull(record.getC_BPartner_QuickInput_ID()); if (bpartnerQuickInputId != null) { final I_C_BPartner_QuickInput bpartnerQuickInputRecord = repo.getById(bpartnerQuickInputId); return bpartnerQuickInputRecord.getCompanyname(); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\callout\C_BPartner_Location_QuickInput.java
1
请完成以下Java代码
public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } @Override public String[] getIncidentIds() { return incidentIds; } public void setIncidentIds(String[] incidentIds) { this.incidentIds = incidentIds; } @Override public Incident[] getIncidents() { return incidents; } public void setIncidents(Incident[] incidents) { this.incidents = incidents; } public void setSubProcessInstanceId(String subProcessInstanceId) { this.subProcessInstanceId = subProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public String toString() {
return this.getClass().getSimpleName() + "[executionId=" + executionId + ", targetActivityId=" + activityId + ", activityName=" + activityName + ", activityType=" + activityType + ", id=" + id + ", parentActivityInstanceId=" + parentActivityInstanceId + ", processInstanceId=" + processInstanceId + ", processDefinitionId=" + processDefinitionId + ", incidentIds=" + Arrays.toString(incidentIds) + ", incidents=" + Arrays.toString(incidents) + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TransitionInstanceImpl.java
1
请完成以下Java代码
public Object mapDecisionResult(DmnDecisionResult decisionResult) { if (decisionResult.isEmpty()) { return Collections.emptyList(); } else { Set<String> outputNames = collectOutputNames(decisionResult); if (outputNames.size() > 1) { throw LOG.decisionResultCollectMappingException(outputNames, decisionResult, this); } else { String outputName = outputNames.iterator().next(); return decisionResult.collectEntries(outputName); } } }
protected Set<String> collectOutputNames(DmnDecisionResult decisionResult) { Set<String> outputNames = new HashSet<String>(); for (Map<String, Object> entryMap : decisionResult.getResultList()) { outputNames.addAll(entryMap.keySet()); } return outputNames; } @Override public String toString() { return "CollectEntriesDecisionResultMapper{}"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\result\CollectEntriesDecisionResultMapper.java
1
请完成以下Java代码
public class SuspendProcessDefinitionCmd extends AbstractSetProcessDefinitionStateCmd { public SuspendProcessDefinitionCmd( ProcessDefinitionEntity processDefinitionEntity, boolean includeProcessInstances, Date executionDate, String tenantId ) { super(processDefinitionEntity, includeProcessInstances, executionDate, tenantId); } public SuspendProcessDefinitionCmd( String processDefinitionId, String processDefinitionKey, boolean suspendProcessInstances, Date suspensionDate, String tenantId
) { super(processDefinitionId, processDefinitionKey, suspendProcessInstances, suspensionDate, tenantId); } protected SuspensionState getProcessDefinitionSuspensionState() { return SuspensionState.SUSPENDED; } protected String getDelayedExecutionJobHandlerType() { return TimerSuspendProcessDefinitionHandler.TYPE; } protected AbstractSetProcessInstanceStateCmd getProcessInstanceChangeStateCmd(ProcessInstance processInstance) { return new SuspendProcessInstanceCmd(processInstance.getId()); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SuspendProcessDefinitionCmd.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(_id, label, parent, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).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\Region.java
2
请完成以下Java代码
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached AuthorRecord */
public AuthorRecord() { super(Author.AUTHOR); } /** * Create a detached, initialised AuthorRecord */ public AuthorRecord(Integer id, String firstName, String lastName, Integer age) { super(Author.AUTHOR); set(0, id); set(1, firstName); set(2, lastName); set(3, age); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java
1
请在Spring Boot框架中完成以下Java代码
public static BPartnerCreditLimitId ofRepoIdOrNull( @Nullable final BPartnerId bpartnerId, @Nullable final Integer bPartnerCreditLimitId) { return bpartnerId != null && bPartnerCreditLimitId != null && bPartnerCreditLimitId > 0 ? ofRepoId(bpartnerId, bPartnerCreditLimitId) : null; } @Jacksonized @Builder private BPartnerCreditLimitId(@NonNull final BPartnerId bpartnerId, final int bPartnerCreditLimitId) { this.bpartnerId = bpartnerId; this.repoId = Check.assumeGreaterThanZero(bPartnerCreditLimitId, "C_BPartner_CreditLimit_ID"); } public static int toRepoId(@Nullable final BPartnerCreditLimitId bPartnerCreditLimitId)
{ return bPartnerCreditLimitId != null ? bPartnerCreditLimitId.getRepoId() : -1; } public static boolean equals(final @Nullable BPartnerCreditLimitId id1, final @Nullable BPartnerCreditLimitId id2) { return Objects.equals(id1, id2); } @JsonValue public int toJson() { return getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerCreditLimitId.java
2
请在Spring Boot框架中完成以下Java代码
public boolean getDefaultAllowLoggingByColumnName(@NonNull final String columnName) { if (columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Created) || columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_CreatedBy) || columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Updated) || columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_UpdatedBy)) { return false; } return true; } @Override public boolean getDefaultIsCalculatedByColumnName(@NonNull final String columnName)
{ return columnName.equalsIgnoreCase("Value") || columnName.equalsIgnoreCase("DocumentNo") || columnName.equalsIgnoreCase("DocStatus") || columnName.equalsIgnoreCase("Docaction") || columnName.equalsIgnoreCase("Processed") || columnName.equalsIgnoreCase("Processing") || StringUtils.containsIgnoreCase(columnName, "ExternalID") || columnName.equalsIgnoreCase("ExternalHeaderId") || columnName.equalsIgnoreCase("ExternalLineId") || columnName.equalsIgnoreCase("IsReconciled") ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\service\impl\ColumnBL.java
2
请在Spring Boot框架中完成以下Java代码
public Optional<Authentication> retrieve(@Nullable final Object token) { if (token == null) { return Optional.empty(); } return Optional.ofNullable(restApiAuthToken.get(String.valueOf(token))); } public void expiryToken(@NonNull final Object token) { restApiAuthToken.remove(String.valueOf(token)); } public int getNumberOfAuthenticatedTokens(@NonNull final String authority) { final SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority); return (int)restApiAuthToken.values() .stream() .map(Authentication::getAuthorities) .filter(item -> item.contains(grantedAuthority)) .count(); }
@PostConstruct private void registerPreAuthenticatedIdentities() { for (final PreAuthenticatedIdentity preAuthenticatedIdentity : preAuthenticatedIdentities) { final Optional<PreAuthenticatedAuthenticationToken> preAuthenticatedAuthenticationToken = preAuthenticatedIdentity.getPreAuthenticatedToken(); if (preAuthenticatedAuthenticationToken.isEmpty()) { logger.warning(preAuthenticatedIdentity.getClass().getName() + ": not configured!"); continue; } restApiAuthToken.put((String)preAuthenticatedAuthenticationToken.get().getPrincipal(), preAuthenticatedAuthenticationToken.get()); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\TokenBasedAuthService.java
2
请完成以下Java代码
public class BookListener { @PrePersist void onPrePersist(Book book) { System.out.println("BookListener.onPrePersist(): " + book); } @PostPersist void onPostPersist(Book book) { System.out.println("BookListener.onPostPersist(): " + book); } @PostLoad void onPostLoad(Book book) { System.out.println("BookListener.onPostLoad(): " + book); } @PreUpdate
void onPreUpdate(Book book) { System.out.println("BookListener.onPreUpdate(): " + book); } @PostUpdate void onPostUpdate(Book book) { System.out.println("BookListener.onPostUpdate(): " + book); } @PreRemove void onPreRemove(Book book) { System.out.println("BookListener.onPreRemove(): " + book); } @PostRemove void onPostRemove(Book book) { System.out.println("BookListener.onPostRemove(): " + book); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootEntityListener\src\main\java\com\bookstore\listener\BookListener.java
1
请完成以下Java代码
public Integer getLastReceiptInDays() { return calculateDaysFrom(getLastReceiptDate()); } public Integer getLastShipmentInDays() { return calculateDaysFrom(getLastShipmentDate()); } private static Integer calculateDaysFrom(final ZonedDateTime date) { if (date != null) { return (int)Duration.between(date, SystemTime.asZonedDateTime()).toDays(); } else { return null; } } public void updateLastReceiptDate(@NonNull final ZonedDateTime receiptDate) { lastReceiptDate = max(lastReceiptDate, receiptDate); } public void updateLastShipmentDate(@NonNull final ZonedDateTime shipmentDate) { lastShipmentDate = max(lastShipmentDate, shipmentDate); } private static final ZonedDateTime max(final ZonedDateTime date1, final ZonedDateTime date2) { if (date1 == null) { return date2; } else if (date2 == null) { return date1; } else { return date1.isAfter(date2) ? date1 : date2; } } public void updateLastSalesInvoiceInfo(@NonNull final LastInvoiceInfo lastSalesInvoice) { if (lastSalesInvoice.isAfter(this.lastSalesInvoice)) { this.lastSalesInvoice = lastSalesInvoice; } } @Value @Builder public static class LastInvoiceInfo { @NonNull private InvoiceId invoiceId;
@NonNull private LocalDate invoiceDate; @NonNull private Money price; public boolean isAfter(@Nullable LastInvoiceInfo other) { if (other == null) { return true; } else if (this.invoiceDate.compareTo(other.invoiceDate) > 0) { return true; } else if (this.invoiceDate.compareTo(other.invoiceDate) == 0) { return this.invoiceId.getRepoId() > other.invoiceId.getRepoId(); } else // if(this.invoiceDate.compareTo(other.invoiceDate) < 0) { return false; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\product\stats\BPartnerProductStats.java
1
请完成以下Java代码
public MigrationInstruction findSingleMigrationInstruction(String sourceScopeId) { List<MigrationInstruction> instructions = instructionsBySourceScope.get(sourceScopeId); if (instructions != null && !instructions.isEmpty()) { return instructions.get(0); } else { return null; } } protected Map<String, List<MigrationInstruction>> organizeInstructionsBySourceScope(MigrationPlan migrationPlan) { Map<String, List<MigrationInstruction>> organizedInstructions = new HashMap<String, List<MigrationInstruction>>(); for (MigrationInstruction instruction : migrationPlan.getInstructions()) { CollectionUtil.addToMapOfLists(organizedInstructions, instruction.getSourceActivityId(), instruction); } return organizedInstructions; } public void handleDependentActivityInstanceJobs(MigratingActivityInstance migratingInstance, List<JobEntity> jobs) { parser.getDependentActivityInstanceJobHandler().handle(this, migratingInstance, jobs); } public void handleDependentTransitionInstanceJobs(MigratingTransitionInstance migratingInstance, List<JobEntity> jobs) { parser.getDependentTransitionInstanceJobHandler().handle(this, migratingInstance, jobs); } public void handleDependentEventSubscriptions(MigratingActivityInstance migratingInstance, List<EventSubscriptionEntity> eventSubscriptions) { parser.getDependentEventSubscriptionHandler().handle(this, migratingInstance, eventSubscriptions); } public void handleDependentVariables(MigratingProcessElementInstance migratingInstance, List<VariableInstanceEntity> variables) { parser.getDependentVariablesHandler().handle(this, migratingInstance, variables); }
public void handleTransitionInstance(TransitionInstance transitionInstance) { parser.getTransitionInstanceHandler().handle(this, transitionInstance); } public void validateNoEntitiesLeft(MigratingProcessInstanceValidationReportImpl processInstanceReport) { processInstanceReport.setProcessInstanceId(migratingProcessInstance.getProcessInstanceId()); ensureNoEntitiesAreLeft("tasks", tasks, processInstanceReport); ensureNoEntitiesAreLeft("externalTask", externalTasks, processInstanceReport); ensureNoEntitiesAreLeft("incidents", incidents, processInstanceReport); ensureNoEntitiesAreLeft("jobs", jobs, processInstanceReport); ensureNoEntitiesAreLeft("event subscriptions", eventSubscriptions, processInstanceReport); ensureNoEntitiesAreLeft("variables", variables, processInstanceReport); } public void ensureNoEntitiesAreLeft(String entityName, Collection<? extends DbEntity> dbEntities, MigratingProcessInstanceValidationReportImpl processInstanceReport) { if (!dbEntities.isEmpty()) { processInstanceReport.addFailure("Process instance contains not migrated " + entityName + ": [" + StringUtil.joinDbEntityIds(dbEntities) + "]"); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\MigratingInstanceParseContext.java
1
请完成以下Java代码
private ESRStatement importCamt54v02(final MultiVersionStreamReaderDelegate mxsr) { final BankToCustomerDebitCreditNotificationV02 bkToCstmrDbtCdtNtfctn = ESRDataImporterCamt54v02.loadXML(mxsr); if (bkToCstmrDbtCdtNtfctn.getGrpHdr() != null && bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf() != null) { Loggables.withLogger(logger, Level.INFO).addLog("The given input is a test file: bkToCstmrDbtCdtNtfctn/grpHdr/addtlInf={}", bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf()); } return ESRDataImporterCamt54v02.builder() .bankAccountCurrencyCode(bankAccountCurrencyCode) .adLanguage(adLanguage) .build() .createESRStatement(bkToCstmrDbtCdtNtfctn); } private ESRStatement importCamt54v06(final MultiVersionStreamReaderDelegate mxsr) { final BankToCustomerDebitCreditNotificationV06 bkToCstmrDbtCdtNtfctn = ESRDataImporterCamt54v06.loadXML(mxsr); if (bkToCstmrDbtCdtNtfctn.getGrpHdr() != null && bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf() != null) { Loggables.withLogger(logger, Level.INFO).addLog("The given input is a test file: bkToCstmrDbtCdtNtfctn/grpHdr/addtlInf={}", bkToCstmrDbtCdtNtfctn.getGrpHdr().getAddtlInf()); } return ESRDataImporterCamt54v06.builder() .bankAccountCurrencyCode(bankAccountCurrencyCode) .adLanguage(adLanguage) .build() .createESRStatement(bkToCstmrDbtCdtNtfctn); } private void closeXmlReaderAndInputStream(@Nullable final XMLStreamReader xsr)
{ try { if (xsr != null) { xsr.close(); } input.close(); } catch (XMLStreamException | IOException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\camt54\ESRDataImporterCamt54.java
1
请完成以下Java代码
public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set SKU. @param SKU Stock Keeping Unit */ @Override public void setSKU (java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); } /** Get SKU. @return Stock Keeping Unit */ @Override public java.lang.String getSKU () { return (java.lang.String)get_Value(COLUMNNAME_SKU); } /** Set Symbol. @param UOMSymbol Symbol for a Unit of Measure */ @Override public void setUOMSymbol (java.lang.String UOMSymbol) { set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol); } /** Get Symbol. @return Symbol for a Unit of Measure */ @Override public java.lang.String getUOMSymbol ()
{ return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol); } /** Set UPC/EAN. @param UPC Bar Code (Universal Product Code or its superset European Article Number) */ @Override public void setUPC (java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } /** Get UPC/EAN. @return Bar Code (Universal Product Code or its superset European Article Number) */ @Override public java.lang.String getUPC () { return (java.lang.String)get_Value(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLine_v.java
1
请完成以下Java代码
public WorkflowLaunchersFacetGroupList getFacets(@NonNull final WorkflowLaunchersFacetQuery query) { return getFacets( newDDOrderReferenceQuery(query.getUserId()) .activeFacetIds(DistributionFacetIdsCollection.ofWorkflowLaunchersFacetIds(query.getActiveFacetIds())) .build() ) .toWorkflowLaunchersFacetGroupList(query.getActiveFacetIds()); } private DistributionFacetsCollection getFacets(@NonNull final DDOrderReferenceQuery query) { final DistributionFacetsCollector collector = DistributionFacetsCollector.builder() .ddOrderService(ddOrderService) .productService(productService) .warehouseService(warehouseService) .sourceDocService(sourceDocService) .build(); collect(query, collector); return collector.toFacetsCollection(); } private <T> void collect( @NonNull final DDOrderReferenceQuery query, @NonNull final DistributionOrderCollector<T> collector) { // // Already started jobs if (!query.isExcludeAlreadyStarted()) { ddOrderService.streamDDOrders(DistributionJobQueries.ddOrdersAssignedToUser(query)) .forEach(collector::collect); } // // New possible jobs @NonNull final QueryLimit suggestedLimit = query.getSuggestedLimit(); if (suggestedLimit.isNoLimit() || !suggestedLimit.isLimitHitOrExceeded(collector.getCollectedItems())) { ddOrderService.streamDDOrders(DistributionJobQueries.toActiveNotAssignedDDOrderQuery(query)) .limit(suggestedLimit.minusSizeOf(collector.getCollectedItems()).toIntOr(Integer.MAX_VALUE)) .forEach(collector::collect); } } @NonNull private ImmutableSet<String> computeActions( @NonNull final List<DDOrderReference> jobReferences, @NonNull final UserId userId) { final ImmutableSet.Builder<String> actions = ImmutableSet.builder();
if (hasInTransitSchedules(jobReferences, userId)) { actions.add(ACTION_DROP_ALL); if (warehouseService.getTrolleyByUserId(userId).isPresent()) { actions.add(ACTION_PRINT_IN_TRANSIT_REPORT); } } return actions.build(); } private boolean hasInTransitSchedules( @NonNull final List<DDOrderReference> jobReferences, @NonNull final UserId userId) { final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId) .map(LocatorQRCode::getLocatorId) .orElse(null); if (inTransitLocatorId != null) { return loadingSupportServices.hasInTransitSchedules(inTransitLocatorId); } else { return jobReferences.stream().anyMatch(DDOrderReference::isInTransit); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionWorkflowLaunchersProvider.java
1
请在Spring Boot框架中完成以下Java代码
public void setExceptionByteArrayRef(ByteArrayRef exceptionByteArrayRef) { this.exceptionByteArrayRef = exceptionByteArrayRef; } @Override public ByteArrayRef getExceptionByteArrayRef() { return exceptionByteArrayRef; } @Override public String getExceptionStacktrace() { return getJobByteArrayRefAsString(exceptionByteArrayRef); } @Override public void setExceptionStacktrace(String exception) { if (exceptionByteArrayRef == null) { exceptionByteArrayRef = new ByteArrayRef(); } exceptionByteArrayRef.setValue("stacktrace", exception, getEngineType()); } @Override public String getExceptionMessage() { return exceptionMessage; } @Override public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, JobInfo.MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String claimedBy) { this.lockOwner = claimedBy; }
@Override public Date getLockExpirationTime() { return lockExpirationTime; } @Override public void setLockExpirationTime(Date claimedUntil) { this.lockExpirationTime = claimedUntil; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) { if (jobByteArrayRef == null) { return null; } return jobByteArrayRef.asString(getEngineType()); } protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoryJobEntity[").append("id=").append(id) .append(", jobHandlerType=").append(jobHandlerType); if (scopeType != null) { sb.append(", scopeType=").append(scopeType); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java
2
请完成以下Java代码
public String getId() { return id; } public String getDecisionInstanceId() { return decisionInstanceId; } public String getClauseId() { return clauseId; } public String getClauseName() { return clauseName; } public String getRuleId() { return ruleId; } public Integer getRuleOrder() { return ruleOrder; } public String getVariableName() { return variableName; } public String getErrorMessage() { return errorMessage; } public Date getCreateTime() { return createTime; } public Date getRemovalTime() {
return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricDecisionOutputInstanceDto fromHistoricDecisionOutputInstance(HistoricDecisionOutputInstance historicDecisionOutputInstance) { HistoricDecisionOutputInstanceDto dto = new HistoricDecisionOutputInstanceDto(); dto.id = historicDecisionOutputInstance.getId(); dto.decisionInstanceId = historicDecisionOutputInstance.getDecisionInstanceId(); dto.clauseId = historicDecisionOutputInstance.getClauseId(); dto.clauseName = historicDecisionOutputInstance.getClauseName(); dto.ruleId = historicDecisionOutputInstance.getRuleId(); dto.ruleOrder = historicDecisionOutputInstance.getRuleOrder(); dto.variableName = historicDecisionOutputInstance.getVariableName(); dto.createTime = historicDecisionOutputInstance.getCreateTime(); dto.removalTime = historicDecisionOutputInstance.getRemovalTime(); dto.rootProcessInstanceId = historicDecisionOutputInstance.getRootProcessInstanceId(); if(historicDecisionOutputInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, historicDecisionOutputInstance.getTypedValue()); } else { dto.errorMessage = historicDecisionOutputInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(historicDecisionOutputInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionOutputInstanceDto.java
1
请完成以下Java代码
public class DBRes_vi extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][] { { "CConnectionDialog", "K\u1EBFt n\u1ED1i" }, { "Name", "T�n" }, { "AppsHost", "M�y ch\u1EE7 \u1EE9ng d\u1EE5ng" }, { "AppsPort", "C\u1ED5ng \u1EE9ng d\u1EE5ng" }, { "TestApps", "Th\u1EED nghi\u1EC7m \u1EE9ng d\u1EE5ng" }, { "DBHost", "M�y ch\u1EE7 CSDL" }, { "DBPort", "C\u1ED5ng CSDL" }, { "DBName", "T�n CSDL" }, { "DBUidPwd", "Ng\u01B0\u1EDDi d�ng / M\u1EADt kh\u1EA9u" }, { "ViaFirewall", "Qua b\u1EE9c t\u01B0\u1EDDng l\u1EEDa" }, { "FWHost", "M�y ch\u1EE7 b\u1EE9c t\u01B0\u1EDDng l\u1EEDa" }, { "FWPort", "C\u1ED5ng v�o b\u1EE9c t\u01B0\u1EDDng l\u1EEDa" }, { "TestConnection", "Ki\u1EC3m tra CSDL" }, { "Type", "Lo\u1EA1i CSDL" }, { "BequeathConnection", "Truy\u1EC1n l\u1EA1i k\u1EBFt n\u1ED1i" }, { "Overwrite", "Ghi \u0111�" }, { "ConnectionProfile", "Connection" }, { "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "L\u1ED7i k\u1EBFt n\u1ED1i" }, { "ServerNotActive", "M�y ch\u1EE7 hi\u1EC7n kh�ng ho\u1EA1t \u0111\u1ED9ng" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_vi.java
1
请完成以下Java代码
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { if (evt.getPropertyName().equals(I_C_OrderLine.COLUMNNAME_M_Product_ID)) { reset(false); fProduct.setValue(evt.getNewValue()); updateData(true, fProduct); } } private void reset(boolean clearPrimaryField) { fQtyOrdered.removeActionListener(this); if (clearPrimaryField) { fProduct.setValue(null); } fQtyOrdered.setValue(Env.ZERO); fQtyOrdered.setReadWrite(false); fProduct.requestFocus(); } private void updateData(boolean requestFocus, Component source) { if (requestFocus) { SwingFieldsUtil.focusNextNotEmpty(source, m_editors); } fQtyOrdered.setReadWrite(true); fQtyOrdered.addActionListener(this); } private void commit() { int M_Product_ID = getM_Product_ID(); if (M_Product_ID <= 0) throw new FillMandatoryException( I_C_OrderLine.COLUMNNAME_M_Product_ID); String productStr = fProduct.getDisplay(); if (productStr == null) productStr = ""; BigDecimal qty = getQtyOrdered(); if (qty == null || qty.signum() == 0) throw new FillMandatoryException( I_C_OrderLine.COLUMNNAME_QtyOrdered); // MOrderLine line = new MOrderLine(order); line.setM_Product_ID(getM_Product_ID(), true); line.setQty(qty); line.saveEx();
// reset(true); changed = true; refreshIncludedTabs(); setInfo(Msg.parseTranslation(Env.getCtx(), "@RecordSaved@ - @M_Product_ID@:" + productStr + ", @QtyOrdered@:" + qty), false, null); } public void showCenter() { AEnv.showCenterWindow(getOwner(), this); } public boolean isChanged() { return changed; } public void refreshIncludedTabs() { for (GridTab includedTab : orderTab.getIncludedTabs()) { includedTab.dataRefreshAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\OrderLineCreate.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public String[] getActivityInstanceIds() { return activityInstanceIds; } public String[] getProcessInstanceIds() { return processInstanceIds; } public String[] getTaskIds() { return taskIds; } public String[] getExecutionIds() { return executionIds; } public String[] getCaseExecutionIds() { return caseExecutionIds; } public String[] getCaseActivityIds() { return caseActivityIds; } public boolean isTenantIdSet() { return isTenantIdSet; } public String getVariableName() { return variableName; } public String getVariableNameLike() { return variableNameLike; } public QueryVariableValue getQueryVariableValue() { return queryVariableValue; } public Boolean getVariableNamesIgnoreCase() { return variableNamesIgnoreCase; }
public Boolean getVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } @Override public HistoricVariableInstanceQuery includeDeleted() { includeDeleted = true; return this; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public List<String> getVariableNameIn() { return variableNameIn; } public Date getCreatedAfter() { return createdAfter; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
} try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-springaop-example\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\aspect\LoggingAspect.java
1
请完成以下Java代码
public Void execute(CommandContext commandContext) { ExecutionEntityManager executionManager = commandContext.getExecutionEntityManager(); ExecutionEntity processInstance = executionManager.findById(processInstanceId); if (processInstance == null) { throw new ActivitiObjectNotFoundException( "No process instance found for id = '" + processInstanceId + "'.", ProcessInstance.class ); } else if (!processInstance.isProcessInstanceType()) { throw new ActivitiIllegalArgumentException( "A process instance id is required, but the provided id " + "'" + processInstanceId + "' " + "points to a child execution of process instance " + "'" + processInstance.getProcessInstanceId() + "'. " + "Please invoke the " + getClass().getSimpleName() +
" with a root execution id." ); } executeInternal(commandContext, executionManager, processInstance); return null; } protected void executeInternal( CommandContext commandContext, ExecutionEntityManager executionManager, ExecutionEntity processInstance ) { executionManager.updateProcessInstanceBusinessKey(processInstance, businessKey); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessInstanceBusinessKeyCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class StoreAttachmentService { private static final Logger logger = LogManager.getLogger(StoreAttachmentService.class); private final List<StoreAttachmentServiceImpl> storeAttachmentServices; private final List<AttachmentStoredListener> attachmentStoredListeners; public StoreAttachmentService( @NonNull final Optional<List<StoreAttachmentServiceImpl>> storeAttachmentServices, @NonNull final Optional<List<AttachmentStoredListener>> attachmentStoredListeners) { this.storeAttachmentServices = storeAttachmentServices.orElse(ImmutableList.of()); this.attachmentStoredListeners = attachmentStoredListeners.orElse(ImmutableList.of()); } public boolean isAttachmentStorable(@NonNull final AttachmentEntry attachmentEntry) { final StoreAttachmentServiceImpl service = extractFor(attachmentEntry); if (service == null) { return false; } return service.isAttachmentStorable(attachmentEntry); } /** * @return false if there is no StoreAttachmentService to take care of the given attachmentEntry. */ public boolean storeAttachment(@NonNull final AttachmentEntry attachmentEntry) { final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
final StoreAttachmentServiceImpl service = extractFor(attachmentEntry); if (service == null) { loggable.addLog("StoreAttachmentService - no StoreAttachmentServiceImpl found for attachment={}", attachmentEntry); return false; } final URI storageIdentifier = service.storeAttachment(attachmentEntry); loggable.addLog("StoreAttachmentService - stored attachment to URI={}; storeAttachmentServiceImpl={}, attachment={}", storageIdentifier, service, attachmentEntry); for (final AttachmentStoredListener attachmentStoredListener : attachmentStoredListeners) { attachmentStoredListener.attachmentWasStored(attachmentEntry, storageIdentifier); } return true; } private StoreAttachmentServiceImpl extractFor(@NonNull final AttachmentEntry attachmentEntry) { for (final StoreAttachmentServiceImpl storeAttachmentService : storeAttachmentServices) { if (storeAttachmentService.appliesTo(attachmentEntry)) { return storeAttachmentService; } } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\storeattachment\StoreAttachmentService.java
2
请完成以下Java代码
class UserActor extends AbstractActor { private UserService userService = new UserService(); static Props props() { return Props.create(UserActor.class); } @Override public Receive createReceive() { return receiveBuilder() .match(CreateUserMessage.class, handleCreateUser()) .match(GetUserMessage.class, handleGetUser()) .build(); }
private FI.UnitApply<CreateUserMessage> handleCreateUser() { return createUserMessageMessage -> { userService.createUser(createUserMessageMessage.getUser()); sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser() .getName())), getSelf()); }; } private FI.UnitApply<GetUserMessage> handleGetUser() { return getUserMessageMessage -> { sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf()); }; } }
repos\tutorials-master\akka-modules\akka-http\src\main\java\com\baeldung\akkahttp\UserActor.java
1
请在Spring Boot框架中完成以下Java代码
public DeleteProcessDefinitionsBuilderImpl withoutTenantId() { isTenantIdSet = true; return this; } @Override public DeleteProcessDefinitionsBuilderImpl withTenantId(String tenantId) { ensureNotNull("tenantId", tenantId); isTenantIdSet = true; this.tenantId = tenantId; return this; } @Override public DeleteProcessDefinitionsBuilderImpl cascade() { this.cascade = true; return this; } @Override public DeleteProcessDefinitionsBuilderImpl skipCustomListeners() { this.skipCustomListeners = true; return this; } @Override public DeleteProcessDefinitionsBuilderImpl skipIoMappings() { this.skipIoMappings = true; return this; } @Override public void delete() {
ensureOnlyOneNotNull(NullValueException.class, "'processDefinitionKey' or 'processDefinitionIds' cannot be null", processDefinitionKey, processDefinitionIds); Command<Void> command; if (processDefinitionKey != null) { command = new DeleteProcessDefinitionsByKeyCmd(processDefinitionKey, cascade, skipCustomListeners, skipIoMappings, tenantId, isTenantIdSet); } else if (processDefinitionIds != null && !processDefinitionIds.isEmpty()) { command = new DeleteProcessDefinitionsByIdsCmd(processDefinitionIds, cascade, skipCustomListeners, skipIoMappings); } else { return; } commandExecutor.execute(command); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeleteProcessDefinitionsBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/protected-process*") .authenticated() .anyRequest() .permitAll()) .formLogin(login -> login .loginPage("/login") .defaultSuccessUrl("/homepage") .failureUrl("/login?error=true") .permitAll()) .csrf(AbstractHttpConfigurer::disable)
.logout(logout -> logout.logoutSuccessUrl("/login")); return http.build(); } @Bean public UserDetailsService userDetailsService() { User.UserBuilder users = User.withDefaultPasswordEncoder(); UserDetails user = users.username("user") .password("{noop}pass") .authorities("ROLE_ACTIVITI_USER") .build(); return new InMemoryUserDetailsManager(user); } }
repos\tutorials-master\spring-activiti\src\main\java\com\baeldung\activiti\security\withspring\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public PatientHospital hospitalId(String hospitalId) { this.hospitalId = hospitalId; return this; } /** * Id der entlassenden Klinik (Voraussetzung, Alberta-Id ist bereits durch initialen Abgleich in WaWi vorhanden) * @return hospitalId **/ @Schema(example = "5ab2379c9d69c74b68cee819", description = "Id der entlassenden Klinik (Voraussetzung, Alberta-Id ist bereits durch initialen Abgleich in WaWi vorhanden)") public String getHospitalId() { return hospitalId; } public void setHospitalId(String hospitalId) { this.hospitalId = hospitalId; } public PatientHospital dischargeDate(LocalDate dischargeDate) { this.dischargeDate = dischargeDate; return this; } /** * letztes Entlassdatum aus der Klinik * @return dischargeDate **/ @Schema(example = "Thu Nov 21 00:00:00 GMT 2019", description = "letztes Entlassdatum aus der Klinik") public LocalDate getDischargeDate() { return dischargeDate; } public void setDischargeDate(LocalDate dischargeDate) { this.dischargeDate = dischargeDate; } @Override public boolean equals(java.lang.Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientHospital patientHospital = (PatientHospital) o; return Objects.equals(this.hospitalId, patientHospital.hospitalId) && Objects.equals(this.dischargeDate, patientHospital.dischargeDate); } @Override public int hashCode() { return Objects.hash(hospitalId, dischargeDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientHospital {\n"); sb.append(" hospitalId: ").append(toIndentedString(hospitalId)).append("\n"); sb.append(" dischargeDate: ").append(toIndentedString(dischargeDate)).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\PatientHospital.java
2
请完成以下Java代码
public class CycleDetectionBruteForce { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { if (head == null) { return new CycleDetectionResult<>(false, null); } Node<T> it1 = head; int nodesTraversedByOuter = 0; while (it1 != null && it1.next != null) { it1 = it1.next; nodesTraversedByOuter++; int x = nodesTraversedByOuter; Node<T> it2 = head; int noOfTimesCurrentNodeVisited = 0; while (x > 0) { it2 = it2.next;
if (it2 == it1) { noOfTimesCurrentNodeVisited++; } if (noOfTimesCurrentNodeVisited == 2) { return new CycleDetectionResult<>(true, it1); } x--; } } return new CycleDetectionResult<>(false, null); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\linkedlist\CycleDetectionBruteForce.java
1
请完成以下Java代码
private final UserNotificationRequest createUserNotification(@NonNull final ModelType document, final UserId recipientUserId) { Check.assumeNotNull(document, "document not null"); // // Get the recipient final UserId recipientUserIdToUse; if (recipientUserId != null) { recipientUserIdToUse = recipientUserId; } else { recipientUserIdToUse = extractRecipientUser(document); if (recipientUserIdToUse == null) { throw new AdempiereException("No recipient found for " + document); } } // // Extract event message parameters final List<Object> adMessageParams = extractEventMessageParams(document); // // Create an return the user notification return newUserNotificationRequest() .recipientUserId(recipientUserIdToUse) .contentADMessage(eventAD_Message) .contentADMessageParams(adMessageParams) .targetAction(TargetRecordAction.of(TableRecordReference.of(document))) .build(); } private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(topic); }
private List<Object> extractEventMessageParams(final ModelType document) { List<Object> params = eventAD_MessageParamsExtractor.apply(document); return params != null ? params : ImmutableList.of(); } private UserId extractRecipientUser(final ModelType document) { final Integer createdBy = InterfaceWrapperHelper.getValueOrNull(document, "CreatedBy"); return createdBy == null ? null : UserId.ofRepoIdOrNull(createdBy); } private void postNotification(final UserNotificationRequest notification) { notificationBL.sendAfterCommit(notification); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\DocumentUserNotificationsProducer.java
1
请完成以下Java代码
public void setM_TargetDistribution_ID (int M_TargetDistribution_ID) { if (M_TargetDistribution_ID < 1) set_Value (COLUMNNAME_M_TargetDistribution_ID, null); else set_Value (COLUMNNAME_M_TargetDistribution_ID, Integer.valueOf(M_TargetDistribution_ID)); } /** Get Target distribution. @return Get product from target distribution to apply the promotion reward */ public int getM_TargetDistribution_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_TargetDistribution_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Menge. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** RewardMode AD_Reference_ID=53389 */ public static final int REWARDMODE_AD_Reference_ID=53389; /** Charge = CH */ public static final String REWARDMODE_Charge = "CH"; /** Split Quantity = SQ */ public static final String REWARDMODE_SplitQuantity = "SQ"; /** Set Reward Mode. @param RewardMode Reward Mode */ public void setRewardMode (String RewardMode) { set_Value (COLUMNNAME_RewardMode, RewardMode); } /** Get Reward Mode. @return Reward Mode */ public String getRewardMode () { return (String)get_Value(COLUMNNAME_RewardMode); } /** RewardType AD_Reference_ID=53298 */
public static final int REWARDTYPE_AD_Reference_ID=53298; /** Percentage = P */ public static final String REWARDTYPE_Percentage = "P"; /** Flat Discount = F */ public static final String REWARDTYPE_FlatDiscount = "F"; /** Absolute Amount = A */ public static final String REWARDTYPE_AbsoluteAmount = "A"; /** Set Reward Type. @param RewardType Type of reward which consists of percentage discount, flat discount or absolute amount */ public void setRewardType (String RewardType) { set_Value (COLUMNNAME_RewardType, RewardType); } /** Get Reward Type. @return Type of reward which consists of percentage discount, flat discount or absolute amount */ public String getRewardType () { return (String)get_Value(COLUMNNAME_RewardType); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionReward.java
1
请完成以下Java代码
static boolean load(String path) { trie = new DoubleArrayTrie<String>(); if (loadDat(path + ".bi" + Predefine.BIN_EXT)) return true; TreeMap<String, String> map = new TreeMap<String, String>(); for (String line : IOUtil.readLineListWithLessMemory(path)) { String[] param = line.split(" "); if (param[0].endsWith("@")) { continue; } String dependency = param[1]; map.put(param[0], dependency); } if (map.size() == 0) return false; trie.build(map); if (!saveDat(path, map)) Predefine.logger.warning("缓存" + path + Predefine.BIN_EXT + "失败"); return true; } private static boolean loadDat(String path) { ByteArray byteArray = ByteArray.createByteArray(path); if (byteArray == null) return false; int size = byteArray.nextInt(); String[] valueArray = new String[size]; for (int i = 0; i < valueArray.length; ++i) { valueArray[i] = byteArray.nextUTF(); } return trie.load(byteArray, valueArray); } static boolean saveDat(String path, TreeMap<String, String> map) { Collection<String> dependencyList = map.values(); // 缓存值文件 try { DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(path + ".bi" + Predefine.BIN_EXT)); out.writeInt(dependencyList.size()); for (String dependency : dependencyList) { out.writeUTF(dependency); } if (!trie.save(out)) return false; out.close(); } catch (Exception e)
{ Predefine.logger.warning("保存失败" + e); return false; } return true; } public static String get(String key) { return trie.get(key); } /** * 获取一个词和另一个词最可能的依存关系 * @param fromWord * @param fromPos * @param toWord * @param toPos * @return */ public static String get(String fromWord, String fromPos, String toWord, String toPos) { String dependency = get(fromWord + "@" + toWord); if (dependency == null) dependency = get(fromWord + "@" + WordNatureWeightModelMaker.wrapTag(toPos)); if (dependency == null) dependency = get(WordNatureWeightModelMaker.wrapTag(fromPos) + "@" + toWord); if (dependency == null) dependency = get(WordNatureWeightModelMaker.wrapTag(fromPos) + "@" + WordNatureWeightModelMaker.wrapTag(toPos)); if (dependency == null) dependency = "未知"; return dependency; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\BigramDependencyModel.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); ensureVariablesInitialized(); return commandContext .getExecutionManager() .findExecutionCountByQueryCriteria(this); } @Override @SuppressWarnings("unchecked") public List<Execution> executeList(CommandContext commandContext, Page page) { checkQueryOk(); ensureVariablesInitialized(); return (List) commandContext .getExecutionManager() .findExecutionsByQueryCriteria(this, page); } //getters //////////////////////////////////////////////////// public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; }
public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public static class XxlJobAdminProps { /** * 调度中心地址 */ private String address; } @Data public static class XxlJobExecutorProps { /** * 执行器名称 */ private String appName; /** * 执行器 IP */ private String ip;
/** * 执行器端口 */ private int port; /** * 执行器日志 */ private String logPath; /** * 执行器日志保留天数,-1 */ private int logRetentionDays; } }
repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\config\props\XxlJobProps.java
1
请完成以下Java代码
public static AttachmentEntryCreateRequest.AttachmentEntryCreateRequestBuilder builderFromByteArray( @NonNull final String fileName, final byte[] data) { return AttachmentEntryCreateRequest.builder() .type(AttachmentEntryType.Data) .filename(fileName) .contentType(MimeType.getMimeType(fileName)) .data(data); } public static AttachmentEntryCreateRequest fromDataSource(final DataSource dataSource) { final String filename = dataSource.getName(); final String contentType = dataSource.getContentType(); final byte[] data; try { data = Util.readBytes(dataSource.getInputStream()); } catch (final IOException e) { throw new AdempiereException("Failed reading data from " + dataSource); } return builder() .type(AttachmentEntryType.Data) .filename(filename) .contentType(contentType) .data(data) .build(); } public static Collection<AttachmentEntryCreateRequest> fromResources(@NonNull final Collection<Resource> resources) { return resources .stream() .map(AttachmentEntryCreateRequest::fromResource) .collect(ImmutableList.toImmutableList()); } public static AttachmentEntryCreateRequest fromResource(@NonNull final Resource resource) { final String filename = resource.getFilename(); final String contentType = MimeType.getMimeType(filename); final byte[] data; try { data = Util.readBytes(resource.getInputStream()); }
catch (final IOException e) { throw new AdempiereException("Failed reading data from " + resource); } return builder() .type(AttachmentEntryType.Data) .filename(filename) .contentType(contentType) .data(data) .build(); } public static Collection<AttachmentEntryCreateRequest> fromFiles(@NonNull final Collection<File> files) { return files .stream() .map(AttachmentEntryCreateRequest::fromFile) .collect(ImmutableList.toImmutableList()); } public static AttachmentEntryCreateRequest fromFile(@NonNull final File file) { final String filename = file.getName(); final String contentType = MimeType.getMimeType(filename); final byte[] data = Util.readBytes(file); return builder() .type(AttachmentEntryType.Data) .filename(filename) .contentType(contentType) .data(data) .build(); } @NonNull AttachmentEntryType type; String filename; String contentType; byte[] data; URI url; AttachmentTags tags; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryCreateRequest.java
1
请完成以下Java代码
void append() { if ((_size % UNIT_SIZE) == 0) { _units.add(0); } ++_size; } /** * 构建 */ void build() { _ranks = new int[_units.size()]; _numOnes = 0; for (int i = 0; i < _units.size(); ++i) { _ranks[i] = _numOnes; _numOnes += popCount(_units.get(i)); } } /** * 清空 */ void clear() { _units.clear(); _ranks = null; } /** * 整型大小 */ private static final int UNIT_SIZE = 32; // sizeof(int) * 8
/** * 1的数量 * @param unit * @return */ private static int popCount(int unit) { unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555); unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333); unit = ((unit >>> 4) + unit) & 0x0F0F0F0F; unit += unit >>> 8; unit += unit >>> 16; return unit & 0xFF; } /** * 储存空间 */ private AutoIntPool _units = new AutoIntPool(); /** * 是每个元素的1的个数的累加 */ private int[] _ranks; /** * 1的数量 */ private int _numOnes; /** * 大小 */ private int _size; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
1
请完成以下Java代码
public int getCreatedLUsCount() { return _createdLUs.size(); } @Override public Quantity calculateTotalQtyCU() { final Capacity tuCapacity = getSingleCUPerTU(); return calculateTotalQtyCU(tuCapacity); } private Quantity calculateTotalQtyCU(final Capacity tuCapacity) { Check.assumeNotNull(tuCapacity, "tuCapacity not null"); final BigDecimal qtyCUsPerTU = tuCapacity.toBigDecimal(); final I_C_UOM cuUOM = tuCapacity.getC_UOM(); // If Qty CU/TU is infinite, we cannot calculate if (tuCapacity.isInfiniteCapacity()) { return Quantity.infinite(cuUOM); } Check.assume(qtyCUsPerTU != null && qtyCUsPerTU.signum() > 0, "Valid QtyCUsPerTU: {}", qtyCUsPerTU); // // Case: No LU if (isNoLU()) { // No LU and don't create TUs for remaining => QtyCU total is ZERO if (!isCreateTUsForRemainingQty()) { return Quantity.zero(cuUOM); } // Infinite TUs => QtyCU total is infinite if (isMaxTUsForRemainingQtyInfinite()) { return Quantity.infinite(cuUOM); } final int qtyTUs = getMaxTUsForRemainingQty(); if (qtyTUs <= 0) { return Quantity.zero(cuUOM); } final BigDecimal qtyCUsTotal = qtyCUsPerTU.multiply(BigDecimal.valueOf(qtyTUs)); return new Quantity(qtyCUsTotal, cuUOM); } // // Case: we have LU else { // Infinite LUs => QtyCU total is infinite if (isMaxLUsInfinite()) {
return Quantity.infinite(cuUOM); } final BigDecimal qtyLUs = BigDecimal.valueOf(getMaxLUs()); Check.assume(qtyLUs.signum() >= 0, "Valid QtyLUs: {}", qtyLUs); final BigDecimal qtyTUsPerLU = BigDecimal.valueOf(getMaxTUsPerLU_Effective()); Check.assume(qtyTUsPerLU.signum() >= 0, "Valid QtyTUsPerLU: {}", qtyTUsPerLU); final BigDecimal qtyCUsTotal = qtyCUsPerTU.multiply(qtyTUsPerLU).multiply(qtyLUs); return new Quantity(qtyCUsTotal, cuUOM); } } @Override public void setExistingHUs(final IHUAllocations existingHUs) { assertConfigurable(); this.existingHUs = existingHUs; } @Override public LUTUResult getResult() { final LUTUResult.LUTUResultBuilder result = LUTUResult.builder() .topLevelTUs(LUTUResult.TUsList.ofSingleTUsList(_createdTUsForRemainingQty)); for (final I_M_HU lu : _createdLUs) { final TUProducerDestination tuProducer = getTUProducerOrNull(lu); final List<LUTUResult.TU> tus = tuProducer != null ? tuProducer.getResult() : ImmutableList.of(); result.lu(LUTUResult.LU.of(lu, tus)); } if (_existingLU != null) { final TUProducerDestination tuProducer = getTUProducerOrNull(_existingLU); final List<LUTUResult.TU> tus = tuProducer != null ? tuProducer.getResult() : ImmutableList.of(); result.lu(LUTUResult.LU.of(_existingLU, tus).markedAsPreExistingLU()); } return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUProducerDestination.java
1
请完成以下Java代码
public class Http2ServerResponseHandler extends ChannelDuplexHandler { static final ByteBuf RESPONSE_BYTES = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8)); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { super.exceptionCaught(ctx, cause); cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof Http2HeadersFrame) { Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg; if (msgHeader.isEndStream()) { ByteBuf content = ctx.alloc() .buffer(); content.writeBytes(RESPONSE_BYTES.duplicate());
Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream())); ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream())); } } else { super.channelRead(ctx, msg); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\server\Http2ServerResponseHandler.java
1
请在Spring Boot框架中完成以下Java代码
class ConnectionFactoryBeanCreationFailureAnalyzer extends AbstractFailureAnalyzer<ConnectionFactoryBeanCreationException> { private final Environment environment; ConnectionFactoryBeanCreationFailureAnalyzer(Environment environment) { this.environment = environment; } @Override protected FailureAnalysis analyze(Throwable rootFailure, ConnectionFactoryBeanCreationException cause) { return getFailureAnalysis(cause); } private FailureAnalysis getFailureAnalysis(ConnectionFactoryBeanCreationException cause) { String description = getDescription(cause); String action = getAction(cause); return new FailureAnalysis(description, action, cause); } private String getDescription(ConnectionFactoryBeanCreationException cause) { StringBuilder description = new StringBuilder(); description.append("Failed to configure a ConnectionFactory: "); if (!StringUtils.hasText(cause.getUrl())) { description.append("'url' attribute is not specified and "); } description.append(String.format("no embedded database could be configured.%n")); description.append(String.format("%nReason: %s%n", cause.getMessage())); return description.toString(); } private String getAction(ConnectionFactoryBeanCreationException cause) { StringBuilder action = new StringBuilder(); action.append(String.format("Consider the following:%n")); if (EmbeddedDatabaseConnection.NONE == cause.getEmbeddedDatabaseConnection()) { action.append(String.format("\tIf you want an embedded database (H2), please put it on the classpath.%n"));
} else { action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection())); } action .append("\tIf you have database settings to be loaded from a particular " + "profile you may need to activate it") .append(getActiveProfiles()); return action.toString(); } private String getActiveProfiles() { StringBuilder message = new StringBuilder(); String[] profiles = this.environment.getActiveProfiles(); if (ObjectUtils.isEmpty(profiles)) { message.append(" (no profiles are currently active)."); } else { message.append(" (the profiles "); message.append(StringUtils.arrayToCommaDelimitedString(profiles)); message.append(" are currently active)."); } return message.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryBeanCreationFailureAnalyzer.java
2
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsAccommodationBooking (final boolean IsAccommodationBooking) { set_Value (COLUMNNAME_IsAccommodationBooking, IsAccommodationBooking); } @Override public boolean isAccommodationBooking() { return get_ValueAsBoolean(COLUMNNAME_IsAccommodationBooking); } @Override public org.compiere.model.I_R_Status getR_Status() { return get_ValueAsPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class);
} @Override public void setR_Status(final org.compiere.model.I_R_Status R_Status) { set_ValueFromPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class, R_Status); } @Override public void setR_Status_ID (final int R_Status_ID) { if (R_Status_ID < 1) set_Value (COLUMNNAME_R_Status_ID, null); else set_Value (COLUMNNAME_R_Status_ID, R_Status_ID); } @Override public int getR_Status_ID() { return get_ValueAsInt(COLUMNNAME_R_Status_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_User.java
1
请在Spring Boot框架中完成以下Java代码
public class InventoryJobWFActivityHandler implements WFActivityHandler { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("inventory.inventory"); public static final UIComponentType COMPONENT_TYPE = UIComponentType.ofString("inventory/inventory"); @NonNull private final Mappers mappers; @Override public WFActivityType getHandledActivityType() {return HANDLED_ACTIVITY_TYPE;} @Override public UIComponent getUIComponent(final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { final Inventory inventory = getInventory(wfProcess); final JsonInventoryJobMapper jsonMapper = mappers.newJsonInventoryJobMapper(jsonOpts); return UIComponent.builderFrom(COMPONENT_TYPE, wfActivity) .properties(Params.builder() .valueObj("job", jsonMapper.toJson(inventory))
.build()) .build(); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity) { return computeActivityState(getInventory(wfProcess)); } public static WFActivityStatus computeActivityState(final Inventory inventory) { return inventory.getDocStatus().isCompleted() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\InventoryJobWFActivityHandler.java
2
请完成以下Java代码
public ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("petId", petId); String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap formParams = new LinkedMultiValueMap(); if (additionalMetadata != null) formParams.add("additionalMetadata", additionalMetadata); if (file != null) formParams.add("file", new FileSystemResource(file));
final String[] accepts = { "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "multipart/form-data" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\api\PetApi.java
1
请在Spring Boot框架中完成以下Java代码
static BigDecimal computeRequiredQty( @NonNull final BigDecimal availableQuantityAfterDemandWasApplied, @NonNull final MinMaxDescriptor minMaxDescriptor) { if (availableQuantityAfterDemandWasApplied.compareTo(minMaxDescriptor.getMin()) >= 0) { return ZERO; } return minMaxDescriptor.getMax().subtract(availableQuantityAfterDemandWasApplied); } private void fireSupplyRequiredEventIfNeeded(@NonNull final Candidate demandCandidate, @NonNull final Candidate stockCandidate) { if (demandCandidate.isSimulated()) { fireSimulatedSupplyRequiredEvent(demandCandidate, stockCandidate); } else { fireSupplyRequiredEventIfQtyBelowZero(demandCandidate); } } private void fireSimulatedSupplyRequiredEvent(@NonNull final Candidate simulatedCandidate, @NonNull final Candidate stockCandidate) { Check.assume(simulatedCandidate.isSimulated(), "fireSimulatedSupplyRequiredEvent should only be called for simulated candidates!"); if (stockCandidate.getQuantity().signum() < 0) { postSupplyRequiredEvent(simulatedCandidate, stockCandidate.getQuantity().negate()); } } private void postSupplyRequiredEvent(@NonNull final Candidate demandCandidateWithId, @NonNull final BigDecimal requiredQty) { // create supply record now! otherwise final Candidate supplyCandidate = Candidate.builderForClientAndOrgId(demandCandidateWithId.getClientAndOrgId())
.type(CandidateType.SUPPLY) .businessCase(null) .businessCaseDetail(null) .materialDescriptor(demandCandidateWithId.getMaterialDescriptor().withQuantity(requiredQty)) //.groupId() // don't assign the new supply candidate to the demand candidate's groupId! it needs to "found" its own group .minMaxDescriptor(demandCandidateWithId.getMinMaxDescriptor()) .quantity(requiredQty) .simulated(demandCandidateWithId.isSimulated()) .build(); final CandidateId supplyCandidateId = supplyCandidateHandler.onCandidateNewOrChange(supplyCandidate, OnNewOrChangeAdvise.DONT_UPDATE).getId(); final SupplyRequiredEvent supplyRequiredEvent = SupplyRequiredEventCreator .createSupplyRequiredEvent(demandCandidateWithId, requiredQty, supplyCandidateId); materialEventService.enqueueEventAfterNextCommit(supplyRequiredEvent); Loggables.addLog("Fire supplyRequiredEvent after next commit; event={}", supplyRequiredEvent); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\DemandCandiateHandler.java
2
请完成以下Java代码
public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs, boolean smooth, boolean addOne) { return idf(new KeySetIterable<TERM, Double>(tfs), smooth, addOne); } /** * 从词频集合建立倒排频率(默认平滑词频,且加一平滑tf-idf) * * @param tfs 次品集合 * @param <TERM> 词语类型 * @return 一个词语->倒排文档的Map */ public static <TERM> Map<TERM, Double> idfFromTfs(Iterable<Map<TERM, Double>> tfs) { return idfFromTfs(tfs, true, true); } /** * Map的迭代器 * * @param <KEY> map 键类型 * @param <VALUE> map 值类型 */ static private class KeySetIterable<KEY, VALUE> implements Iterable<Iterable<KEY>> { final private Iterator<Map<KEY, VALUE>> maps; public KeySetIterable(Iterable<Map<KEY, VALUE>> maps) { this.maps = maps.iterator(); }
@Override public Iterator<Iterable<KEY>> iterator() { return new Iterator<Iterable<KEY>>() { @Override public boolean hasNext() { return maps.hasNext(); } @Override public Iterable<KEY> next() { return maps.next().keySet(); } @Override public void remove() { } }; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TfIdf.java
1
请在Spring Boot框架中完成以下Java代码
private void setResponsible() { final UserId previousResponsibleId = ManufacturingJobLoaderAndSaver.extractResponsibleId(ppOrder); if (UserId.equals(previousResponsibleId, responsibleId)) { //noinspection UnnecessaryReturnStatement return; } else if (previousResponsibleId != null) { throw new AdempiereException("Order is already assigned"); } else { ppOrder.setAD_User_Responsible_ID(responsibleId.getRepoId()); ppOrderBL.save(ppOrder); } } private PPOrderIssuePlan createIssuePlan() { return PPOrderIssuePlanCreateCommand.builder() .huReservationService(huReservationService) .ppOrderSourceHUService(ppOrderSourceHUService) .ppOrderId(ppOrderId) .build() .execute(); } private void createIssueSchedules(@NonNull final PPOrderIssuePlan plan) { final ArrayListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> allExistingSchedules = ppOrderIssueScheduleService.getByOrderId(plan.getOrderId()) .stream() .collect(GuavaCollectors.toArrayListMultimapByKey(PPOrderIssueSchedule::getPpOrderBOMLineId)); final ArrayList<PPOrderIssueSchedule> schedules = new ArrayList<>(); final SeqNoProvider seqNoProvider = SeqNoProvider.ofInt(10); for (final PPOrderIssuePlanStep planStep : plan.getSteps()) {
final PPOrderBOMLineId orderBOMLineId = planStep.getOrderBOMLineId(); final ArrayList<PPOrderIssueSchedule> bomLineExistingSchedules = new ArrayList<>(allExistingSchedules.removeAll(orderBOMLineId)); bomLineExistingSchedules.sort(Comparator.comparing(PPOrderIssueSchedule::getSeqNo)); for (final PPOrderIssueSchedule existingSchedule : bomLineExistingSchedules) { if (existingSchedule.isIssued()) { final PPOrderIssueSchedule existingScheduleChanged = ppOrderIssueScheduleService.changeSeqNo(existingSchedule, seqNoProvider.getAndIncrement()); schedules.add(existingScheduleChanged); } else { ppOrderIssueScheduleService.delete(existingSchedule); } } final PPOrderIssueSchedule schedule = ppOrderIssueScheduleService.createSchedule( PPOrderIssueScheduleCreateRequest.builder() .ppOrderId(ppOrderId) .ppOrderBOMLineId(orderBOMLineId) .seqNo(seqNoProvider.getAndIncrement()) .productId(planStep.getProductId()) .qtyToIssue(planStep.getQtyToIssue()) .issueFromHUId(planStep.getPickFromTopLevelHUId()) .issueFromLocatorId(planStep.getPickFromLocatorId()) .isAlternativeIssue(planStep.isAlternative()) .build()); schedules.add(schedule); } loader.addToCache(schedules); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\create_job\ManufacturingJobCreateCommand.java
2
请完成以下Java代码
public void completed(ActivityExecution execution) throws Exception { // only control flow. no sub instance data available leave(execution); } public CallableElement getCallableElement() { return callableElement; } public void setCallableElement(CallableElement callableElement) { this.callableElement = callableElement; } protected String getBusinessKey(ActivityExecution execution) { return getCallableElement().getBusinessKey(execution); } protected VariableMap getInputVariables(ActivityExecution callingExecution) { return getCallableElement().getInputVariables(callingExecution); } protected VariableMap getOutputVariables(VariableScope calledElementScope) { return getCallableElement().getOutputVariables(calledElementScope); } protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) { return getCallableElement().getOutputVariablesLocal(calledElementScope); } protected Integer getVersion(ActivityExecution execution) { return getCallableElement().getVersion(execution); } protected String getDeploymentId(ActivityExecution execution) { return getCallableElement().getDeploymentId(); }
protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding(); } protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java
1
请完成以下Java代码
public void setShipperId(@NonNull final I_C_Order order) { order.setM_Shipper_ID(ShipperId.toRepoId(findShipperId(order))); } private ShipperId findShipperId(@NonNull final I_C_Order orderRecord) { final Optional<ShipperId> dropShipShipperId = getDropShipAddressShipperId(orderRecord); return dropShipShipperId.orElse(getDeliveryAddressShipperId(orderRecord)); } private Optional<ShipperId> getDropShipAddressShipperId(final I_C_Order orderRecord) { if (orderRecord.getDropShip_BPartner_ID() <= 0 || orderRecord.getDropShip_Location_ID() <= 0) { return Optional.empty(); } final Optional<ShipperId> dropShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getDropShip_BPartner_ID(), orderRecord.getDropShip_Location_ID())); return Optional.ofNullable(dropShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getDropShip_BPartner_ID())))); } private ShipperId getDeliveryAddressShipperId(final I_C_Order orderRecord) { final Optional<ShipperId> deliveryShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getC_BPartner_ID(), orderRecord.getC_BPartner_Location_ID())); return deliveryShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID()))); } private ShipperId getPartnerShipperId(@NonNull final BPartnerId partnerId) { return partnerDAO.getShipperId(partnerId); } @Override public PaymentTermId getPaymentTermId(@NonNull final I_C_Order orderRecord) { return PaymentTermId.ofRepoId(orderRecord.getC_PaymentTerm_ID()); } @Override public Money getGrandTotal(@NonNull final I_C_Order order) {
final BigDecimal grandTotal = order.getGrandTotal(); return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID())); } @Override public void save(final I_C_Order order) { orderDAO.save(order); } @Override public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder) { final I_C_Order order = getById(orderId); order.setBLDate(transportOrder.getBLDate()); order.setETA(transportOrder.getETA()); save(order); } @Override public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice) { final I_C_Order order = getById(orderId); order.setInvoiceDate(invoice.getDateInvoiced()); save(order); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return orderDAO.getByQueryFilter(queryFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java
1
请完成以下Java代码
public String get() { return "get.html"; } @PostRoute("/route-example") public String post() { return "post.html"; } @PutRoute("/route-example") public String put() { return "put.html"; } @DeleteRoute("/route-example") public String delete() { return "delete.html"; } @Route(value = "/another-route-example", method = HttpMethod.GET) public String anotherGet() { return "get.html"; } @Route(value = "/allmatch-route-example") public String allmatch() { return "allmatch.html"; } @Route(value = "/triggerInternalServerError") public void triggerInternalServerError() { int x = 1 / 0; }
@Route(value = "/triggerBaeldungException") public void triggerBaeldungException() throws BaeldungException { throw new BaeldungException("Foobar Exception to threat differently"); } @Route(value = "/user/foo") public void urlCoveredByNarrowedWebhook(Response response) { response.text("Check out for the WebHook covering '/user/*' in the logs"); } @GetRoute("/load-configuration-in-a-route") public void loadConfigurationInARoute(Response response) { String authors = WebContext.blade() .env("app.authors", "Unknown authors"); log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors); response.render("index.html"); } @GetRoute("/template-output-test") public void templateOutputTest(Request request, Response response) { request.attribute("name", "Blade"); response.render("template-output-test.html"); } }
repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\RouteExampleController.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((symbol == null) ? 0 : symbol.hashCode()); result = prime * result + ((ts == null) ? 0 : ts.hashCode()); long temp; temp = Double.doubleToLongBits(value); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Quote other = (Quote) obj; if (symbol == null) { if (other.symbol != null)
return false; } else if (!symbol.equals(other.symbol)) return false; if (ts == null) { if (other.ts != null) return false; } else if (!ts.equals(other.ts)) return false; if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value)) return false; return true; } @Override public String toString() { return "Quote [ts=" + ts + ", symbol=" + symbol + ", value=" + value + "]"; } }
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\model\Quote.java
1
请完成以下Java代码
public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
1
请完成以下Java代码
public void process(Record<K, V> record) { Headers headers = record.headers(); Container<K, V> container = new Container<>(context(), record.key(), record.value(), record); this.headerExpressions.forEach((name, expression) -> { Object headerValue = expression.getValue(container); if (headerValue instanceof String) { headerValue = ((String) headerValue).getBytes(StandardCharsets.UTF_8); } else if (!(headerValue instanceof byte[])) { if (headerValue != null) { throw new IllegalStateException("Invalid header value type: " + headerValue.getClass()); } else { throw new IllegalStateException("headerValue is null"); } } headers.add(new RecordHeader(name, (byte[]) headerValue)); }); context().forward(record); } @Override public void close() { // NO-OP } /** * Container object for SpEL evaluation. * * @param <K> the key type. * @param <V> the value type. * */ public static final class Container<K, V> { private final ProcessorContext<K, V> context; private final K key; private final V value; private final Record<K, V> record; Container(ProcessorContext<K, V> context, K key, V value, Record<K, V> record) { this.context = context; this.key = key; this.value = value;
this.record = record; } public ProcessorContext<K, V> getContext() { return this.context; } public K getKey() { return this.key; } public V getValue() { return this.value; } public Record<K, V> getRecord() { return this.record; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\streams\HeaderEnricherProcessor.java
1
请完成以下Java代码
public int getQtyTU() { return qtyTU; } @Override public String getTUName() { return tuName; } @Override public IHandlingUnitsInfo add(@Nullable final IHandlingUnitsInfo infoToAdd) { if (infoToAdd == null) { return this; // shall not happen
} final String tuName = getTUName(); if (!tuName.equals(infoToAdd.getTUName())) { throw new AdempiereException("TU Names are not matching." + "\n This: " + this + "\n Other: " + infoToAdd); } final int qtyTU = getQtyTU(); final int qtyTU_ToAdd = infoToAdd.getQtyTU(); final int qtyTU_New = qtyTU + qtyTU_ToAdd; final PlainHandlingUnitsInfo infoNew = new PlainHandlingUnitsInfo(tuName, qtyTU_New); return infoNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\PlainHandlingUnitsInfo.java
1
请完成以下Java代码
protected final String formatObject(final Object obj) { final ITableRecordReference modelRef = extractTableRecordReferenceOrNull(obj); if (modelRef != null) { try { return formatTableRecordReference(modelRef); } catch (final Exception e) { logger.warn("Failed formatting: {}", modelRef, e); return "?"; } } // Default/fallback return super.formatObject(obj); } private static final ITableRecordReference extractTableRecordReferenceOrNull(final Object obj) { if(obj == null) { return null; } if (obj instanceof ITableRecordReference) { return (ITableRecordReference)obj; }
// Extract the TableRecordReference from Map. // Usually that's the case when the parameters were deserialized and the the TableRecordRefererence was deserialized as Map. if(obj instanceof Map) { final Map<?, ?> map = (Map<?, ?>)obj; return TableRecordReference.ofMapOrNull(map); } return null; } protected abstract String formatTableRecordReference(final ITableRecordReference recordRef); @Override protected String formatText(final String text) { if (text == null || text.isEmpty()) { return ""; } return StringUtils.maskHTML(text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\EventMessageFormatTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public class LiquibaseConfiguration { private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); private final Environment env; private final CacheManager cacheManager; public LiquibaseConfiguration(Environment env, CacheManager cacheManager) { this.env = env; this.cacheManager = cacheManager; } @Bean public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor, DataSource dataSource, LiquibaseProperties liquibaseProperties) { // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env); liquibase.setDataSource(dataSource); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE)) { liquibase.setShouldRun(false); } else { liquibase.setShouldRun(liquibaseProperties.isEnabled()); log.debug("Configuring Liquibase"); } return liquibase; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\LiquibaseConfiguration.java
2
请完成以下Java代码
public void setDescription(final java.lang.String Description) { set_Value(COLUMNNAME_Description, Description); } /** * Get Beschreibung. * * @return Beschreibung */ @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * Set DLM Partitionierungskonfiguration. * * @param DLM_Partition_Config_ID DLM Partitionierungskonfiguration */ @Override public void setDLM_Partition_Config_ID(final int DLM_Partition_Config_ID) { if (DLM_Partition_Config_ID < 1) { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_ID, null); } else { set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_ID, Integer.valueOf(DLM_Partition_Config_ID)); } } /** * Get DLM Partitionierungskonfiguration. * * @return DLM Partitionierungskonfiguration */ @Override public int getDLM_Partition_Config_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Standard. * * @param IsDefault
* Default value */ @Override public void setIsDefault(final boolean IsDefault) { set_Value(COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** * Get Standard. * * @return Default value */ @Override public boolean isDefault() { final Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** * Set Name. * * @param Name * Alphanumeric identifier of the entity */ @Override public void setName(final java.lang.String Name) { set_Value(COLUMNNAME_Name, Name); } /** * Get Name. * * @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config.java
1
请完成以下Java代码
class MariaDbR2dbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> { MariaDbR2dbcDockerComposeConnectionDetailsFactory() { super("mariadb", "io.r2dbc.spi.ConnectionFactoryOptions"); } @Override protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new MariaDbR2dbcDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link R2dbcConnectionDetails} backed by a {@code mariadb} {@link RunningService}. */ static class MariaDbR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements R2dbcConnectionDetails { private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder(
"mariadb", 3306); private final ConnectionFactoryOptions connectionFactoryOptions; MariaDbR2dbcDockerComposeConnectionDetails(RunningService service) { super(service); MariaDbEnvironment environment = new MariaDbEnvironment(service.env()); this.connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, environment.getDatabase(), environment.getUsername(), environment.getPassword()); } @Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return this.connectionFactoryOptions; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\MariaDbR2dbcDockerComposeConnectionDetailsFactory.java
1
请在Spring Boot框架中完成以下Java代码
public final class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository implements ServerOAuth2AuthorizedClientRepository { private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); private final ReactiveOAuth2AuthorizedClientService authorizedClientService; private ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository = new WebSessionServerOAuth2AuthorizedClientRepository(); /** * Creates an instance * @param authorizedClientService the authorized client service */ public AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository( ReactiveOAuth2AuthorizedClientService authorizedClientService) { Assert.notNull(authorizedClientService, "authorizedClientService cannot be null"); this.authorizedClientService = authorizedClientService; } /** * Sets the {@link ServerOAuth2AuthorizedClientRepository} used for requests that are * unauthenticated (or anonymous). The default is * {@link WebSessionServerOAuth2AuthorizedClientRepository}. * @param anonymousAuthorizedClientRepository the repository used for requests that * are unauthenticated (or anonymous) */ public void setAnonymousAuthorizedClientRepository( ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository) { Assert.notNull(anonymousAuthorizedClientRepository, "anonymousAuthorizedClientRepository cannot be null"); this.anonymousAuthorizedClientRepository = anonymousAuthorizedClientRepository; } @Override public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) { if (this.isPrincipalAuthenticated(principal)) { return this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName()); } return this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, exchange); } @Override public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, ServerWebExchange exchange) { if (this.isPrincipalAuthenticated(principal)) { return this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal); } return this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, exchange); } @Override public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal, ServerWebExchange exchange) { if (this.isPrincipalAuthenticated(principal)) { return this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName()); } return this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, exchange); } private boolean isPrincipalAuthenticated(Authentication authentication) { return this.authenticationTrustResolver.isAuthenticated(authentication); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.java
2
请完成以下Java代码
public static BigDecimal zeroToNull(@Nullable final BigDecimal value) { return value != null && value.signum() != 0 ? value : null; } public static boolean equalsByCompareTo(@Nullable final BigDecimal value1, @Nullable final BigDecimal value2) { //noinspection NumberEquality return (value1 == value2) || (value1 != null && value1.compareTo(value2) == 0); } @SafeVarargs public static int firstNonZero(final Supplier<Integer>... suppliers) { if (suppliers == null || suppliers.length == 0) { return 0; } for (final Supplier<Integer> supplier : suppliers) { if (supplier == null) { continue; } final Integer value = supplier.get(); if (value != null && value != 0)
{ return value; } } return 0; } @NonNull public static BigDecimal roundTo5Cent(@NonNull final BigDecimal initialValue) { final BigDecimal multiplyBy20 = initialValue.multiply(TWENTY); final BigDecimal intPart = multiplyBy20.setScale(0, RoundingMode.HALF_UP); return intPart.divide(TWENTY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\NumberUtils.java
1
请完成以下Java代码
public int getTimerJobCount() { return timerJobCount; } public void setTimerJobCount(int timerJobCount) { this.timerJobCount = timerJobCount; } public int getSuspendedJobCount() { return suspendedJobCount; } public void setSuspendedJobCount(int suspendedJobCount) { this.suspendedJobCount = suspendedJobCount; } public int getDeadLetterJobCount() { return deadLetterJobCount; } public void setDeadLetterJobCount(int deadLetterJobCount) { this.deadLetterJobCount = deadLetterJobCount; } public int getVariableCount() { return variableCount; } public void setVariableCount(int variableCount) { this.variableCount = variableCount; } public int getIdentityLinkCount() { return identityLinkCount; } public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; } @Override public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } @Override public Integer getAppVersion() { return appVersion; }
//toString ///////////////////////////////////////////////////////////////// public String toString() { if (isProcessInstanceType()) { return "ProcessInstance[" + getId() + "]"; } else { StringBuilder strb = new StringBuilder(); if (isScope) { strb.append("Scoped execution[ id '" + getId() + "' ]"); } else if (isMultiInstanceRoot) { strb.append("Multi instance root execution[ id '" + getId() + "' ]"); } else { strb.append("Execution[ id '" + getId() + "' ]"); } if (activityId != null) { strb.append(" - activity '" + activityId); } if (parentId != null) { strb.append(" - parent '" + parentId + "'"); } return strb.toString(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
static class CommonsDbcp2PoolDataSourceMetadataProviderConfiguration { @Bean DataSourcePoolMetadataProvider commonsDbcp2PoolDataSourceMetadataProvider() { return (dataSource) -> { BasicDataSource dbcpDataSource = DataSourceUnwrapper.unwrap(dataSource, BasicDataSourceMXBean.class, BasicDataSource.class); if (dbcpDataSource != null) { return new CommonsDbcp2DataSourcePoolMetadata(dbcpDataSource); } return null; }; } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ PoolDataSource.class, OracleConnection.class }) static class OracleUcpPoolDataSourceMetadataProviderConfiguration { @Bean DataSourcePoolMetadataProvider oracleUcpPoolDataSourceMetadataProvider() {
return (dataSource) -> { PoolDataSource ucpDataSource = DataSourceUnwrapper.unwrap(dataSource, PoolDataSource.class); if (ucpDataSource != null) { return new OracleUcpDataSourcePoolMetadata(ucpDataSource); } return null; }; } } static class HikariDataSourcePoolMetadataRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection().registerType(HikariDataSource.class, (builder) -> builder.withField("pool")); } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourcePoolMetadataProvidersConfiguration.java
2