instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ResponseEntity<JsonResponseManufacturingOrdersBulk> exportOrders( @Parameter(description = "Max number of items to be returned in one request.") // @RequestParam(name = "limit", required = false, defaultValue = "500") // @Nullable final Integer limit) { final Instant canBeExportedFrom = SystemTime.asInstant(); final QueryLimit limitEffective = QueryLimit.ofNullableOrNoLimit(limit).ifNoLimitUse(500); final String adLanguage = Env.getADLanguageOrBaseLanguage(); final JsonResponseManufacturingOrdersBulk result = manufacturingOrderAPIService.exportOrders( canBeExportedFrom, limitEffective, adLanguage); return ResponseEntity.ok(result); } @PostMapping("/exportStatus") public ResponseEntity<String> setExportStatus(@RequestBody @NonNull final JsonRequestSetOrdersExportStatusBulk request) { try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", request.getTransactionKey()))
{ manufacturingOrderAPIService.setExportStatus(request); return ResponseEntity.accepted().body("Manufacturing orders updated"); } } @PostMapping("/report") public ResponseEntity<JsonResponseManufacturingOrdersReport> report(@RequestBody @NonNull final JsonRequestManufacturingOrdersReport request) { final JsonResponseManufacturingOrdersReport response = manufacturingOrderAPIService.report(request); return response.isOK() ? ResponseEntity.ok(response) : ResponseEntity.unprocessableEntity().body(response); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrderRestController.java
1
请完成以下Java代码
public java.math.BigDecimal getQtyPromised_TU_ThisWeek () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised_TU_ThisWeek); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity to Order. @param QtyToOrder Quantity to Order */ @Override public void setQtyToOrder (java.math.BigDecimal QtyToOrder) { set_Value (COLUMNNAME_QtyToOrder, QtyToOrder); } /** Get Quantity to Order. @return Quantity to Order */ @Override public java.math.BigDecimal getQtyToOrder () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder); if (bd == null) return Env.ZERO; return bd; } /** Set Quantity to Order (TU). @param QtyToOrder_TU Quantity to Order (TU) */
@Override public void setQtyToOrder_TU (java.math.BigDecimal QtyToOrder_TU) { set_Value (COLUMNNAME_QtyToOrder_TU, QtyToOrder_TU); } /** Get Quantity to Order (TU). @return Quantity to Order (TU) */ @Override public java.math.BigDecimal getQtyToOrder_TU () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToOrder_TU); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate.java
1
请在Spring Boot框架中完成以下Java代码
private DruidDataSource initDruidDataSource(DruidConfig config) { DruidDataSource datasource = new DruidDataSource(); datasource.setUrl(config.getUrl()); datasource.setUsername(config.getUsername()); datasource.setPassword(config.getPassword()); datasource.setDriverClassName(config.getDriverClassName()); datasource.setInitialSize(config.getInitialSize()); datasource.setMinIdle(config.getMinIdle()); datasource.setMaxActive(config.getMaxActive()); // common config datasource.setMaxWait(druidConfig.getMaxWait()); datasource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis()); datasource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis()); datasource.setMaxEvictableIdleTimeMillis(druidConfig.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidConfig.getValidationQuery()); datasource.setTestWhileIdle(druidConfig.isTestWhileIdle()); datasource.setTestOnBorrow(druidConfig.isTestOnBorrow()); datasource.setTestOnReturn(druidConfig.isTestOnReturn()); datasource.setPoolPreparedStatements(druidConfig.isPoolPreparedStatements()); datasource.setMaxPoolPreparedStatementPerConnectionSize(druidConfig.getMaxPoolPreparedStatementPerConnectionSize()); try { datasource.setFilters(druidConfig.getFilters()); } catch (SQLException e) { logger.error("druid configuration initialization filter : {0}", e); } datasource.setConnectionProperties(druidConfig.getConnectionProperties()); return datasource; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidDBConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class LoginController { private static final String authorizationRequestBaseUri = "oauth2/authorize-client"; Map<String, String> oauth2AuthenticationUrls = new HashMap<>(); @Autowired private ClientRegistrationRepository clientRegistrationRepository; @Autowired private OAuth2AuthorizedClientService authorizedClientService; @GetMapping("/oauth_login") public String getLoginPage(Model model) { Iterable<ClientRegistration> clientRegistrations = null; ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository) .as(Iterable.class); if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) { clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository; } clientRegistrations.forEach(registration -> oauth2AuthenticationUrls.put(registration.getClientName(), authorizationRequestBaseUri + "/" + registration.getRegistrationId())); model.addAttribute("urls", oauth2AuthenticationUrls); return "oauth_login"; } @GetMapping("/loginSuccess") public String getLoginInfo(Model model, OAuth2AuthenticationToken authentication) { OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName()); String userInfoEndpointUri = client.getClientRegistration()
.getProviderDetails() .getUserInfoEndpoint() .getUri(); if (!StringUtils.isEmpty(userInfoEndpointUri)) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken() .getTokenValue()); HttpEntity<String> entity = new HttpEntity<String>("", headers); ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class); Map userAttributes = response.getBody(); model.addAttribute("name", userAttributes.get("name")); } return "loginSuccess"; } }
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\LoginController.java
2
请完成以下Java代码
public void setExplanation (java.lang.String Explanation) { set_Value (COLUMNNAME_Explanation, Explanation); } /** Get Erklärung. @return Erklärung */ @Override public java.lang.String getExplanation () { return (java.lang.String)get_Value(COLUMNNAME_Explanation); } /** Set Rechnung Nr. @param InvoiceNumber Rechnung Nr */ @Override public void setInvoiceNumber (java.lang.String InvoiceNumber) { set_Value (COLUMNNAME_InvoiceNumber, InvoiceNumber); } /** Get Rechnung Nr. @return Rechnung Nr */ @Override public java.lang.String getInvoiceNumber () { return (java.lang.String)get_Value(COLUMNNAME_InvoiceNumber); } /** Set Rechnungsempfänger. @param InvoiceRecipient Rechnungsempfänger */ @Override public void setInvoiceRecipient (java.lang.String InvoiceRecipient) { set_Value (COLUMNNAME_InvoiceRecipient, InvoiceRecipient); } /** Get Rechnungsempfänger. @return Rechnungsempfänger */ @Override public java.lang.String getInvoiceRecipient () { return (java.lang.String)get_Value(COLUMNNAME_InvoiceRecipient); } /** Set Erledigt. @param IsDone Erledigt */ @Override public void setIsDone (boolean IsDone) { set_Value (COLUMNNAME_IsDone, Boolean.valueOf(IsDone)); } /** Get Erledigt. @return Erledigt */ @Override public boolean isDone () { Object oo = get_Value(COLUMNNAME_IsDone); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone);
} /** Get Telefon. @return Beschreibt eine Telefon Nummer */ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Grund. @param Reason Grund */ @Override public void setReason (java.lang.String Reason) { set_Value (COLUMNNAME_Reason, Reason); } /** Get Grund. @return Grund */ @Override public java.lang.String getReason () { return (java.lang.String)get_Value(COLUMNNAME_Reason); } /** Set Sachbearbeiter. @param ResponsiblePerson Sachbearbeiter */ @Override public void setResponsiblePerson (java.lang.String ResponsiblePerson) { set_Value (COLUMNNAME_ResponsiblePerson, ResponsiblePerson); } /** Get Sachbearbeiter. @return Sachbearbeiter */ @Override public java.lang.String getResponsiblePerson () { return (java.lang.String)get_Value(COLUMNNAME_ResponsiblePerson); } /** Set Status. @param Status Status */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Rejection_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaNotificationTemplateDao extends JpaAbstractDao<NotificationTemplateEntity, NotificationTemplate> implements NotificationTemplateDao, TenantEntityDao<NotificationTemplate> { private final NotificationTemplateRepository notificationTemplateRepository; @Override protected Class<NotificationTemplateEntity> getEntityClass() { return NotificationTemplateEntity.class; } @Override public PageData<NotificationTemplate> findByTenantIdAndNotificationTypesAndPageLink(TenantId tenantId, List<NotificationType> notificationTypes, PageLink pageLink) { return DaoUtil.toPageData(notificationTemplateRepository.findByTenantIdAndNotificationTypesAndSearchText(tenantId.getId(), notificationTypes, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public int countByTenantIdAndNotificationTypes(TenantId tenantId, Collection<NotificationType> notificationTypes) { return notificationTemplateRepository.countByTenantIdAndNotificationTypes(tenantId.getId(), notificationTypes); } @Override public void removeByTenantId(TenantId tenantId) { notificationTemplateRepository.deleteByTenantId(tenantId.getId()); } @Override public NotificationTemplate findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public NotificationTemplate findByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndName(tenantId, name));
} @Override public PageData<NotificationTemplate> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(notificationTemplateRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override public NotificationTemplateId getExternalIdByInternal(NotificationTemplateId internalId) { return DaoUtil.toEntityId(notificationTemplateRepository.getExternalIdByInternal(internalId.getId()), NotificationTemplateId::new); } @Override public PageData<NotificationTemplate> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override protected JpaRepository<NotificationTemplateEntity, UUID> getRepository() { return notificationTemplateRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_TEMPLATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationTemplateDao.java
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getType() { return type; } public void setType(BigDecimal type) { this.type = type; } public PatientPrimaryDoctorInstitution description(String description) { this.description = description; return this; } /** * Name und Ort der Institution * @return description **/ @Schema(example = "Krankenhaus Martha-Maria, 90491 Nürnberg", description = "Name und Ort der Institution") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public PatientPrimaryDoctorInstitution institutionId(String institutionId) { this.institutionId = institutionId; return this; } /** * Alberta-Id des Institution (nur bei Pfelgeheim und Klinik) * @return institutionId **/ @Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Alberta-Id des Institution (nur bei Pfelgeheim und Klinik)") public String getInstitutionId() { return institutionId; } public void setInstitutionId(String institutionId) { this.institutionId = institutionId; } @Override
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientPrimaryDoctorInstitution patientPrimaryDoctorInstitution = (PatientPrimaryDoctorInstitution) o; return Objects.equals(this.type, patientPrimaryDoctorInstitution.type) && Objects.equals(this.description, patientPrimaryDoctorInstitution.description) && Objects.equals(this.institutionId, patientPrimaryDoctorInstitution.institutionId); } @Override public int hashCode() { return Objects.hash(type, description, institutionId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientPrimaryDoctorInstitution {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" institutionId: ").append(toIndentedString(institutionId)).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\PatientPrimaryDoctorInstitution.java
2
请完成以下Spring Boot application配置
server.port=8099 ms.db.driverClassName=com.mysql.jdbc.Driver ms.db.url=jdbc:mysql://localhost:3306/msm?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&characterEncoding=utf-8&a
llowMultiQueries=true ms.db.username=root ms.db.password=admin ms.db.maxActive=500
repos\springBoot-master\springboot-jpa\src\main\resources\application.properties
2
请完成以下Java代码
public CustomerId getCustomerId() { return this.customerId; } @Schema(description = "JSON object with Root Rule Chain Id. Use 'setEdgeRootRuleChain' to change the Root Rule Chain Id.", accessMode = Schema.AccessMode.READ_ONLY) public RuleChainId getRootRuleChainId() { return this.rootRuleChainId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge") @Override public String getName() { return this.name; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos") public String getType() { return this.type; } @Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field")
public String getLabel() { return this.label; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud") public String getRoutingKey() { return this.routingKey; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud") public String getSecret() { return this.secret; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java
1
请完成以下Java代码
public void setM_Inventory(final org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } @Override public void setM_Inventory_ID (final int M_Inventory_ID) { if (M_Inventory_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Inventory_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Inventory_ID, M_Inventory_ID); } @Override public int getM_Inventory_ID() { return get_ValueAsInt(COLUMNNAME_M_Inventory_ID); } @Override public void setM_InventoryLine_HU_ID (final int M_InventoryLine_HU_ID) { if (M_InventoryLine_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_HU_ID, M_InventoryLine_HU_ID); } @Override public int getM_InventoryLine_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_HU_ID); } @Override public org.compiere.model.I_M_InventoryLine getM_InventoryLine() { return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class); } @Override public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } @Override public void setM_InventoryLine_ID (final int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID); } @Override public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); } @Override public void setQtyBook (final @Nullable BigDecimal QtyBook)
{ set_Value (COLUMNNAME_QtyBook, QtyBook); } @Override public BigDecimal getQtyBook() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBook); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCount (final @Nullable BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInternalUse (final @Nullable BigDecimal QtyInternalUse) { set_Value (COLUMNNAME_QtyInternalUse, QtyInternalUse); } @Override public BigDecimal getQtyInternalUse() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInternalUse); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); } @Override public java.lang.String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_InventoryLine_HU.java
1
请完成以下Java代码
public void setSourceActivityType(String sourceActivityType) { this.sourceActivityType = sourceActivityType; } public String getTargetActivityId() { return targetActivityId; } public void setTargetActivityId(String targetActivityId) { this.targetActivityId = targetActivityId; } public String getTargetActivityName() { return targetActivityName; } public void setTargetActivityName(String targetActivityName) { this.targetActivityName = targetActivityName; } public String getTargetActivityType() { return targetActivityType; } public void setTargetActivityType(String targetActivityType) { this.targetActivityType = targetActivityType; }
public String getSourceActivityBehaviorClass() { return sourceActivityBehaviorClass; } public void setSourceActivityBehaviorClass(String sourceActivityBehaviorClass) { this.sourceActivityBehaviorClass = sourceActivityBehaviorClass; } public String getTargetActivityBehaviorClass() { return targetActivityBehaviorClass; } public void setTargetActivityBehaviorClass(String targetActivityBehaviorClass) { this.targetActivityBehaviorClass = targetActivityBehaviorClass; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiSequenceFlowTakenEventImpl.java
1
请完成以下Java代码
public int getOrder() { return this.order; } public void afterPropertiesSet() { Assert.notNull(this.beanClassLoader, "beanClassLoader must not be null"); Assert.notNull(this.beanFactory, "beanFactory must not be null"); } public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } public void setRegistry(ActivitiStateHandlerRegistry registry) { this.registry = registry; } public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { // first sift through and get all the methods // then get all the annotations // then build the metadata and register the metadata final Class<?> targetClass = AopUtils.getTargetClass(bean); final org.camunda.bpm.engine.spring.annotations.ProcessEngineComponent component = targetClass.getAnnotation(org.camunda.bpm.engine.spring.annotations.ProcessEngineComponent.class); ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() { @SuppressWarnings("unchecked") public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { State state = AnnotationUtils.getAnnotation(method, State.class); String processName = component.processKey(); if (StringUtils.hasText(state.process())) { processName = state.process(); } String stateName = state.state(); if (!StringUtils.hasText(stateName)) { stateName = state.value(); } Assert.notNull(stateName, "You must provide a stateName!"); Map<Integer, String> vars = new HashMap<Integer, String>(); Annotation[][] paramAnnotationsArray = method.getParameterAnnotations(); int ctr = 0; int pvMapIndex = -1; int procIdIndex = -1; for (Annotation[] paramAnnotations : paramAnnotationsArray) {
ctr += 1; for (Annotation pa : paramAnnotations) { if (pa instanceof ProcessVariable) { ProcessVariable pv = (ProcessVariable) pa; String pvName = pv.value(); vars.put(ctr, pvName); } else if (pa instanceof ProcessVariables) { pvMapIndex = ctr; } else if (pa instanceof ProcessId ) { procIdIndex = ctr; } } } ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method, bean, stateName, beanName, pvMapIndex, procIdIndex, processName); registry.registerActivitiStateHandler(registration); } }, new ReflectionUtils.MethodFilter() { public boolean matches(Method method) { return null != AnnotationUtils.getAnnotation(method, State.class); } }); return bean; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\ActivitiStateAnnotationBeanPostProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class KafkaConsumerDemo { ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1)); @PostConstruct public void startConsumer() { executor.submit(() -> { Properties properties = new Properties(); properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9093"); properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "groupId"); properties.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // 请求超时时间 properties.setProperty(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, "60000"); Deserializer<String> keyDeserializer = new StringDeserializer(); Deserializer<String> valueDeserializer = new StringDeserializer(); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties, keyDeserializer, valueDeserializer); consumer.subscribe(Arrays.asList("test_cluster_topic")); // KafkaConsumer的assignment()方法来判定是否分配到了相应的分区,如果为空表示没有分配到分区 Set<TopicPartition> assignment = consumer.assignment(); while (assignment.isEmpty()) { // 阻塞1秒 consumer.poll(1000); assignment = consumer.assignment(); } // KafkaConsumer 分配到了分区,开始消费 while (true) { // 拉取记录,如果没有记录则柱塞1000ms。 ConsumerRecords<String, String> records = consumer.poll(1000); for (ConsumerRecord<String, String> record : records) { String traceId = new String(record.headers().lastHeader("traceId").value()); System.out.printf("traceId = %s, offset = %d, key = %s, value = %s%n", traceId, record.offset(), record.key(), record.value());
} // 异步确认提交 consumer.commitAsync((offsets, exception) -> { if (Objects.isNull(exception)) { // TODO 告警、落盘、重试 } }); } }); } }
repos\spring-boot-student-master\spring-boot-student-kafka\src\main\java\com\xiaolyuh\consumer\KafkaConsumerDemo.java
2
请完成以下Java代码
public PageData<Customer> findCustomersByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(customerRepository.findByTenantId( tenantId, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public Optional<Customer> findCustomerByTenantIdAndTitle(UUID tenantId, String title) { return Optional.ofNullable(DaoUtil.getData(customerRepository.findByTenantIdAndTitle(tenantId, title))); } @Override public Optional<Customer> findPublicCustomerByTenantId(UUID tenantId) { return Optional.ofNullable(DaoUtil.getData(customerRepository.findPublicCustomerByTenantId(tenantId))); } @Override public Long countByTenantId(TenantId tenantId) { return customerRepository.countByTenantId(tenantId.getId()); } @Override public Customer findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(customerRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public Customer findByTenantIdAndName(UUID tenantId, String name) { return findCustomerByTenantIdAndTitle(tenantId, name).orElse(null); } @Override public PageData<Customer> findByTenantId(UUID tenantId, PageLink pageLink) { return findCustomersByTenantId(tenantId, pageLink); } @Override public CustomerId getExternalIdByInternal(CustomerId internalId) { return Optional.ofNullable(customerRepository.getExternalIdById(internalId.getId())) .map(CustomerId::new).orElse(null); } @Override public PageData<Customer> findCustomersWithTheSameTitle(PageLink pageLink) { return DaoUtil.toPageData( customerRepository.findCustomersWithTheSameTitle(DaoUtil.toPageable(pageLink)) );
} @Override public List<Customer> findCustomersByTenantIdAndIds(UUID tenantId, List<UUID> customerIds) { return DaoUtil.convertDataList(customerRepository.findCustomersByTenantIdAndIdIn(tenantId, customerIds)); } @Override public PageData<Customer> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<CustomerFields> findNextBatch(UUID id, int batchSize) { return customerRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) { return customerRepository.findEntityInfosByNamePrefix(tenantId.getId(), name); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\customer\JpaCustomerDao.java
1
请在Spring Boot框架中完成以下Java代码
public class AggregateConfiguration extends AbstractJdbcConfiguration { final AtomicInteger id = new AtomicInteger(0); @Bean public ApplicationListener<?> idSetting() { return (ApplicationListener<BeforeConvertEvent>) event -> { if (event.getEntity() instanceof LegoSet) { setIds((LegoSet) event.getEntity()); } }; } private void setIds(LegoSet legoSet) { if (legoSet.getId() == 0) { legoSet.setId(id.incrementAndGet()); } var manual = legoSet.getManual(); if (manual != null) { manual.setId((long) legoSet.getId()); } } @Override public JdbcCustomConversions jdbcCustomConversions() { return new JdbcCustomConversions(asList(new Converter<Clob, String>() { @Nullable @Override public String convert(Clob clob) { try { return Math.toIntExact(clob.length()) == 0 // ? "" // : clob.getSubString(1, Math.toIntExact(clob.length())); } catch (SQLException e) { throw new IllegalStateException("Failed to convert CLOB to String.", e);
} } })); } @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcOperations operations) { return new NamedParameterJdbcTemplate(operations); } @Bean DataSourceInitializer initializer(DataSource dataSource) { var initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); var script = new ClassPathResource("schema.sql"); var populator = new ResourceDatabasePopulator(script); initializer.setDatabasePopulator(populator); return initializer; } }
repos\spring-data-examples-main\jdbc\basics\src\main\java\example\springdata\jdbc\basics\aggregate\AggregateConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class Result<T> implements Serializable { /** 执行结果 */ private boolean isSuccess; /** 错误码 */ private String errorCode; /** 错误原因 */ private String message; /** 返回数据 */ private T data; /** * 返回成功的结果 * @param data 需返回的结果 * @param <T> * @return */ public static <T> Result<T> newSuccessResult(T data){ Result<T> result = new Result<>(); result.isSuccess = true; result.data = data; return result; } /** * 返回成功的结果 * @param <T> * @return */ public static <T> Result<T> newSuccessResult(){ Result<T> result = new Result<>(); result.isSuccess = true; return result; } /** * 返回失败的结果 * PS:返回"未知异常" * @param <T> * @return */ public static <T> Result<T> newFailureResult(){ Result<T> result = new Result<>(); result.isSuccess = false; result.errorCode = ExpCodeEnum.UNKNOW_ERROR.getCode(); result.message = ExpCodeEnum.UNKNOW_ERROR.getMessage(); return result; } /** * 返回失败的结果 * @param commonBizException 异常 * @param <T> * @return */ public static <T> Result<T> newFailureResult(CommonBizException commonBizException){ Result<T> result = new Result<>(); result.isSuccess = false; result.errorCode = commonBizException.getCodeEnum().getCode(); result.message = commonBizException.getCodeEnum().getMessage(); return result; } /** * 返回失败的结果 * @param commonBizException 异常 * @param data 需返回的数据 * @param <T> * @return */ public static <T> Result<T> newFailureResult(CommonBizException commonBizException, T data){ Result<T> result = new Result<>(); result.isSuccess = false; result.errorCode = commonBizException.getCodeEnum().getCode(); result.message = commonBizException.getCodeEnum().getMessage();
result.data = data; return result; } public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean success) { isSuccess = success; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" + "isSuccess=" + isSuccess + ", errorCode=" + errorCode + ", message='" + message + '\'' + ", data=" + data + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java
2
请完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getUpdateTime() {
return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysPermissionDataRuleModel.java
1
请完成以下Java代码
public class ApplicationServerDto { protected String vendor; protected String version; public ApplicationServerDto(String vendor, String version) { this.vendor = vendor; this.version = version; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor;
} public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public static ApplicationServerDto fromEngineDto(ApplicationServer other) { return new ApplicationServerDto( other.getVendor(), other.getVersion()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\ApplicationServerDto.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .passwordEncoder(passwordEncoder()) .dataSource(dataSource); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests()
.antMatchers("/anonymous*").anonymous() .antMatchers("/login*").permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .logout() .logoutUrl("/logout.do") .invalidateHttpSession(true) .clearAuthentication(true); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/themes/**"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\config\SecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class AlbertaBPartnerRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); public AlbertaBPartner save(@NonNull final AlbertaBPartner bPartner) { final I_C_BPartner_Alberta record = InterfaceWrapperHelper.loadOrNew(bPartner.getBPartnerAlbertaId(), I_C_BPartner_Alberta.class); record.setC_BPartner_ID(bPartner.getBPartnerId().getRepoId()); record.setTimestamp(TimeUtil.asTimestamp(bPartner.getTimestamp())); record.setTitle(bPartner.getTitle()); record.setTitleShort(bPartner.getTitleShort()); record.setIsArchived(bPartner.isArchived()); InterfaceWrapperHelper.save(record); return toAlbertaBPartner(record); } @NonNull public Optional<AlbertaBPartner> getByPartnerId(@NonNull final BPartnerId bPartnerId) { return queryBL.createQueryBuilder(I_C_BPartner_Alberta.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BPartner_Alberta.COLUMNNAME_C_BPartner_ID, bPartnerId) .create() .firstOnlyOptional(I_C_BPartner_Alberta.class) .map(this::toAlbertaBPartner); } @NonNull
public AlbertaBPartner toAlbertaBPartner(@NonNull final I_C_BPartner_Alberta record) { final BPartnerAlbertaId bPartnerAlbertaId = BPartnerAlbertaId.ofRepoId(record.getC_BPartner_Alberta_ID()); final BPartnerId bPartnerId = BPartnerId.ofRepoId(record.getC_BPartner_ID()); return AlbertaBPartner.builder() .bPartnerAlbertaId(bPartnerAlbertaId) .bPartnerId(bPartnerId) .title(record.getTitle()) .titleShort(record.getTitleShort()) .isArchived(record.isArchived()) .timestamp(TimeUtil.asInstant(record.getTimestamp())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\albertabpartner\AlbertaBPartnerRepository.java
2
请完成以下Java代码
public void setM_ProductMember_ID (int M_ProductMember_ID) { if (M_ProductMember_ID < 1) set_Value (COLUMNNAME_M_ProductMember_ID, null); else set_Value (COLUMNNAME_M_ProductMember_ID, Integer.valueOf(M_ProductMember_ID)); } /** Get Membership. @return Product used to deternine the price of the membership for the topic type */ public int getM_ProductMember_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductMember_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name)
{ set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicType.java
1
请完成以下Java代码
public class ReactivationEventListenerExport extends AbstractPlanItemDefinitionExport<ReactivateEventListener> { @Override protected Class<? extends ReactivateEventListener> getExportablePlanItemDefinitionClass() { return ReactivateEventListener.class; } @Override protected String getPlanItemDefinitionXmlElementValue(ReactivateEventListener reactivationEventListener) { return ELEMENT_GENERIC_EVENT_LISTENER; } @Override protected void writePlanItemDefinitionSpecificAttributes(ReactivateEventListener reactivationEventListener, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(reactivationEventListener, xtw); xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_TYPE, "reactivate"); if (StringUtils.isNotEmpty(reactivationEventListener.getAvailableConditionExpression())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION, reactivationEventListener.getAvailableConditionExpression()); } }
@Override protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, ReactivateEventListener reactivationEventListener, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws Exception { boolean extensionElementsWritten = super.writePlanItemDefinitionExtensionElements(model, reactivationEventListener, didWriteExtensionElement, xtw); ReactivationRule reactivationRule = reactivationEventListener.getDefaultReactivationRule(); if (reactivationRule != null) { if (!extensionElementsWritten) { xtw.writeStartElement(CmmnXmlConstants.ELEMENT_EXTENSION_ELEMENTS); extensionElementsWritten = true; } xtw.writeStartElement(FLOWABLE_EXTENSIONS_PREFIX, ELEMENT_DEFAULT_REACTIVATION_RULE, FLOWABLE_EXTENSIONS_NAMESPACE); PlanItemControlExport.writeReactivationRuleAttributes(reactivationRule, xtw); xtw.writeEndElement(); } return extensionElementsWritten; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\ReactivationEventListenerExport.java
1
请完成以下Java代码
public class TbDeleteKeysNode extends TbAbstractTransformNodeWithTbMsgSource { private TbMsgSource deleteFrom; private List<Pattern> compiledKeyPatterns; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbDeleteKeysNodeConfiguration.class); deleteFrom = config.getDeleteFrom(); if (deleteFrom == null) { throw new TbNodeException("DeleteFrom can't be null! Allowed values: " + Arrays.toString(TbMsgSource.values())); } compiledKeyPatterns = config.getKeys().stream().map(Pattern::compile).collect(Collectors.toList()); } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var metaDataCopy = msg.getMetaData().copy(); var msgDataStr = msg.getData(); boolean hasNoChanges = false; switch (deleteFrom) { case METADATA: var metaDataMap = metaDataCopy.getData(); var mdKeysToDelete = metaDataMap.keySet() .stream() .filter(this::matches) .toList(); mdKeysToDelete.forEach(metaDataMap::remove); metaDataCopy = new TbMsgMetaData(metaDataMap); hasNoChanges = mdKeysToDelete.isEmpty(); break; case DATA: JsonNode dataNode = JacksonUtil.toJsonNode(msgDataStr); if (dataNode.isObject()) { var msgDataObject = (ObjectNode) dataNode; var msgKeysToDelete = new ArrayList<String>(); dataNode.fieldNames().forEachRemaining(key -> { if (matches(key)) { msgKeysToDelete.add(key); } }); msgDataObject.remove(msgKeysToDelete); msgDataStr = JacksonUtil.toString(msgDataObject); hasNoChanges = msgKeysToDelete.isEmpty(); } break; default: log.debug("Unexpected DeleteFrom value: {}. Allowed values: {}", deleteFrom, TbMsgSource.values());
} ctx.tellSuccess(hasNoChanges ? msg : msg.transform() .metaData(metaDataCopy) .data(msgDataStr) .build()); } @Override protected String getNewKeyForUpgradeFromVersionZero() { return "deleteFrom"; } @Override protected String getKeyToUpgradeFromVersionOne() { return "dataToFetch"; } boolean matches(String key) { return compiledKeyPatterns.stream().anyMatch(pattern -> pattern.matcher(key).matches()); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\transform\TbDeleteKeysNode.java
1
请完成以下Java代码
public final class CurrencyPrecision { @JsonCreator public static CurrencyPrecision ofInt(final int precision) { if (precision >= 0 && precision < CACHED_VALUES.length) { return CACHED_VALUES[precision]; } else { return new CurrencyPrecision(precision); } } public static final CurrencyPrecision ZERO; public static final CurrencyPrecision TWO; public static final CurrencyPrecision TEN; private static final CurrencyPrecision[] CACHED_VALUES = new CurrencyPrecision[] { ZERO = new CurrencyPrecision(0), new CurrencyPrecision(1), TWO = new CurrencyPrecision(2), new CurrencyPrecision(3), new CurrencyPrecision(4), new CurrencyPrecision(5), new CurrencyPrecision(6), new CurrencyPrecision(7), new CurrencyPrecision(8), new CurrencyPrecision(9), TEN = new CurrencyPrecision(10), new CurrencyPrecision(11), new CurrencyPrecision(12), }; public static int toInt(@Nullable final CurrencyPrecision precision, final int defaultValue) { return precision != null ? precision.toInt() : defaultValue; } private final int precision; private CurrencyPrecision(final int precision) { Check.assumeGreaterOrEqualToZero(precision, "precision"); this.precision = precision; } @Override @Deprecated public String toString() {
return String.valueOf(precision); } @JsonValue public int toInt() { return precision; } public BigDecimal roundIfNeeded(@NonNull final BigDecimal amt) { if (amt.scale() > precision) { return amt.setScale(precision, getRoundingMode()); } else { return amt; } } public BigDecimal round(@NonNull final BigDecimal amt) { return amt.setScale(precision, getRoundingMode()); } public RoundingMode getRoundingMode() { return RoundingMode.HALF_UP; } public CurrencyPrecision min(final CurrencyPrecision other) { return this.precision <= other.precision ? this : other; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyPrecision.java
1
请完成以下Java代码
private void assertEquals(Boolean expectedResult, Boolean result, String input) { if (result != expectedResult) { throw new IllegalStateException("The output does not match the expected output, for input: " + input); } } private Map<String, Boolean> testPlan() { HashMap<String, Boolean> plan = new HashMap<>(); plan.put(Integer.toString(Integer.MAX_VALUE), true); if (MODE == TestMode.SIMPLE) { return plan; } plan.put("x0", false); plan.put("0..005", false); plan.put("--11", false); plan.put("test", false); plan.put(null, false); for (int i = 0; i < 94; i++) { plan.put(Integer.toString(i), true); } return plan; } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingCoreJava(ExecutionPlan plan) { plan.validate(subject::usingCoreJava); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingRegularExpressions(ExecutionPlan plan) { plan.validate(subject::usingPreCompiledRegularExpressions); } @Benchmark @BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isCreatable(ExecutionPlan plan) { plan.validate(subject::usingNumberUtils_isCreatable); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingNumberUtils_isParsable(ExecutionPlan plan) { plan.validate(subject::usingNumberUtils_isParsable); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumeric(ExecutionPlan plan) { plan.validate(subject::usingStringUtils_isNumeric); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void usingStringUtils_isNumericSpace(ExecutionPlan plan) { plan.validate(subject::usingStringUtils_isNumericSpace); } private enum TestMode { SIMPLE, DIVERS } }
repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\Benchmarking.java
1
请在Spring Boot框架中完成以下Java代码
public java.lang.String getPOSPaymentProcessing_TrxId() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessing_TrxId); } /** * POSPaymentProcessor AD_Reference_ID=541896 * Reference name: POSPaymentProcessor */ public static final int POSPAYMENTPROCESSOR_AD_Reference_ID=541896; /** SumUp = sumup */ public static final String POSPAYMENTPROCESSOR_SumUp = "sumup"; @Override public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); } @Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); }
@Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Payment.java
2
请在Spring Boot框架中完成以下Java代码
private boolean present(String className) { String resourcePath = ClassUtils.convertClassNameToResourcePath(className) + ".class"; return new ClassPathResource(resourcePath).exists(); } protected Collection<String> loadFactoryNames(Class<?> source) { return ImportCandidates.load(source, getBeanClassLoader()).getCandidates(); } @Override protected Set<String> getExclusions(AnnotationMetadata metadata, @Nullable AnnotationAttributes attributes) { Set<String> exclusions = new LinkedHashSet<>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader()); for (String annotationName : ANNOTATION_NAMES) { AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); Class<?>[] exclude = (merged != null) ? merged.getClassArray("exclude") : null; if (exclude != null) { for (Class<?> excludeClass : exclude) { exclusions.add(excludeClass.getName()); } } } for (List<Annotation> annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } } } exclusions.addAll(getExcludeAutoConfigurationsProperty()); return exclusions; }
protected final Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) { MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader()); collectAnnotations(source, annotations, new HashSet<>()); return Collections.unmodifiableMap(annotations); } private void collectAnnotations(@Nullable Class<?> source, MultiValueMap<Class<?>, Annotation> annotations, HashSet<Class<?>> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); } } collectAnnotations(source.getSuperclass(), annotations, seen); } } @Override public int getOrder() { return super.getOrder() - 1; } @Override protected void handleInvalidExcludes(List<String> invalidExcludes) { // Ignore for test } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ImportAutoConfigurationImportSelector.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("source", amtSource) .add("acct", amtAcct) .toString(); } public BigDecimal getAmtSource() { return amtSource; } public BigDecimal getAmtAcct() { return amtAcct; } public static final class Builder { private BigDecimal amtSource = BigDecimal.ZERO; private BigDecimal amtAcct = BigDecimal.ZERO; private Builder() { super(); } public final AmountSourceAndAcct build() { return new AmountSourceAndAcct(this); } public Builder setAmtSource(final BigDecimal amtSource) { this.amtSource = amtSource; return this; }
public Builder setAmtAcct(final BigDecimal amtAcct) { this.amtAcct = amtAcct; return this; } public Builder addAmtSource(final BigDecimal amtSourceToAdd) { amtSource = amtSource.add(amtSourceToAdd); return this; } public Builder addAmtAcct(final BigDecimal amtAcctToAdd) { amtAcct = amtAcct.add(amtAcctToAdd); return this; } public Builder add(final AmountSourceAndAcct amtSourceAndAcctToAdd) { // Optimization: do nothing if zero if (amtSourceAndAcctToAdd == ZERO) { return this; } addAmtSource(amtSourceAndAcctToAdd.getAmtSource()); addAmtAcct(amtSourceAndAcctToAdd.getAmtAcct()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\AmountSourceAndAcct.java
1
请在Spring Boot框架中完成以下Java代码
public class Dao<T, ID extends Serializable> implements GenericDao<T, ID> { private static final Logger logger = Logger.getLogger(Dao.class.getName()); @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}") private int batchSize; private final EntityManagerFactory entityManagerFactory; public Dao(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override public <S extends T> void saveInBatch(Iterable<S> entities) { if (entities == null) { throw new IllegalArgumentException("The given Iterable of entities not be null!"); } EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); try { entityTransaction.begin(); int i = 0; for (S entity: entities) { if (i % batchSize == 0 && i > 0) { logger.log(Level.INFO, "Flushing the EntityManager containing {0} entities ...", batchSize);
entityTransaction.commit(); entityTransaction.begin(); entityManager.clear(); } entityManager.persist(entity); i++; } logger.log(Level.INFO, "Flushing the remaining entities ..."); entityTransaction.commit(); } catch (RuntimeException e) { if (entityTransaction.isActive()) { entityTransaction.rollback(); } throw e; } finally { entityManager.close(); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsEntityManagerBatchPerTransaction\src\main\java\com\bookstore\dao\Dao.java
2
请在Spring Boot框架中完成以下Java代码
public InterchangeHeaderType getInterchangeHeader() { return interchangeHeader; } /** * Sets the value of the interchangeHeader property. * * @param value * allowed object is * {@link InterchangeHeaderType } * */ public void setInterchangeHeader(InterchangeHeaderType value) { this.interchangeHeader = value; } /** * The ID represents the unique number of the message. * * @return * possible object is * {@link String } * */ public String getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setID(String value) { this.id = value; } /** * This segment contains references related to the message. * * @return * possible object is * {@link String } * */ public String getReferences() { return references; } /** * Sets the value of the references property. * * @param value * allowed object is * {@link String } * */ public void setReferences(String value) { this.references = value;
} /** * Flag indicating whether the message is a test message or not. * * @return * possible object is * {@link Boolean } * */ public Boolean isTestIndicator() { return testIndicator; } /** * Sets the value of the testIndicator property. * * @param value * allowed object is * {@link Boolean } * */ public void setTestIndicator(Boolean value) { this.testIndicator = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\ErpelBusinessDocumentHeaderType.java
2
请完成以下Java代码
public DeploymentEntity getDeployment() { return deployment; } public void setDeployment(DeploymentEntity deployment) { this.deployment = deployment; } public ResourceEntity getResource() { return resource; } public void setResource(ResourceEntity resource) { this.resource = resource; } public DefaultCmmnElementHandlerRegistry getHandlerRegistry() { return handlerRegistry; } public void setHandlerRegistry(DefaultCmmnElementHandlerRegistry handlerRegistry) { this.handlerRegistry = handlerRegistry; } @SuppressWarnings("unchecked") protected <V extends CmmnElement> CmmnElementHandler<V, CmmnActivity> getDefinitionHandler(Class<V> cls) { return (CmmnElementHandler<V, CmmnActivity>) getHandlerRegistry().getDefinitionElementHandlers().get(cls); } protected ItemHandler getPlanItemHandler(Class<? extends PlanItemDefinition> cls) { return getHandlerRegistry().getPlanItemElementHandlers().get(cls); }
protected ItemHandler getDiscretionaryItemHandler(Class<? extends PlanItemDefinition> cls) { return getHandlerRegistry().getDiscretionaryElementHandlers().get(cls); } protected SentryHandler getSentryHandler() { return getHandlerRegistry().getSentryHandler(); } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransform.java
1
请完成以下Java代码
public final class RemoteSpringApplication { private RemoteSpringApplication() { } private void run(String[] args) { Restarter.initialize(args, RestartInitializer.NONE); SpringApplication application = new SpringApplication(RemoteClientConfiguration.class); application.setWebApplicationType(WebApplicationType.NONE); application.setBanner(getBanner()); application.setInitializers(getInitializers()); application.setListeners(getListeners()); application.run(args); waitIndefinitely(); } private Collection<ApplicationContextInitializer<?>> getInitializers() { List<ApplicationContextInitializer<?>> initializers = new ArrayList<>(); initializers.add(new RestartScopeInitializer()); return initializers; } private Collection<ApplicationListener<?>> getListeners() { List<ApplicationListener<?>> listeners = new ArrayList<>(); listeners.add(new AnsiOutputApplicationListener()); listeners.add(EnvironmentPostProcessorApplicationListener .with(EnvironmentPostProcessorsFactory.of(ConfigDataEnvironmentPostProcessor.class))); listeners.add(new LoggingApplicationListener()); listeners.add(new RemoteUrlPropertyExtractor()); return listeners; } private Banner getBanner() { ClassPathResource banner = new ClassPathResource("remote-banner.txt", RemoteSpringApplication.class); return new ResourceBanner(banner); } private void waitIndefinitely() { while (true) {
try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } /** * Run the {@link RemoteSpringApplication}. * @param args the program arguments (including the remote URL as a non-option * argument) */ public static void main(String[] args) { new RemoteSpringApplication().run(args); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\RemoteSpringApplication.java
1
请完成以下Java代码
private Iterator<ET> getBufferIterator() { // Buffer iterator was not initialized yet, loading first page if (bufferIterator == null) { loadNextPage(); return bufferIterator; } // Buffer iterator has reached the end. We load the next page only if current page was fully load. // Else, makes no sense to load next page because last page was a short one so we are sure that there are no more pages if (!bufferIterator.hasNext() && bufferFullyLoaded) { loadNextPage(); } return bufferIterator; } private void loadNextPage() { final TypedSqlQuery<T> queryToUse; query.setLimit(QueryLimit.ofInt(bufferSize)); if (Check.isEmpty(rowNumberColumn, true)) { query.setLimit(QueryLimit.ofInt(bufferSize), offset); queryToUse = query; } else { query.setLimit(QueryLimit.ofInt(bufferSize)); queryToUse = query.addWhereClause(true, rowNumberColumn + " > " + offset); } final List<ET> buffer = queryToUse.list(clazz); bufferIterator = buffer.iterator(); final int bufferSizeActual = buffer.size(); bufferFullyLoaded = bufferSizeActual >= bufferSize; if (logger.isDebugEnabled()) { logger.debug("Loaded next page: bufferSize=" + bufferSize + ", offset=" + offset + " -> " + bufferSizeActual + " records (fullyLoaded=" + bufferFullyLoaded + ")"); } offset += bufferSizeActual; } /** * Sets buffer/page size, i.e. the number of rows to be loaded by this iterator at a time.
* * @see IQuery#OPTION_GuaranteedIteratorRequired */ public void setBufferSize(final int bufferSize) { Check.assume(bufferSize > 0, "bufferSize > 0"); this.bufferSize = bufferSize; } public int getBufferSize() { return bufferSize; } @Override public String toString() { return "POBufferedIterator [clazz=" + clazz + ", bufferSize=" + bufferSize + ", offset=" + offset + ", query=" + query + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POBufferedIterator.java
1
请完成以下Java代码
public static Stream<String> filterUserNames() { return userNames().filter(i -> i.length() >= 4); } public static Stream<String> sortUserNames() { return userNames().sorted(); } public static Stream<String> limitUserNames() { return userNames().limit(3); } public static Stream<String> sortFilterLimitUserNames() { return filterUserNames().sorted().limit(3); } public static void printStream(Stream<String> stream) { stream.forEach(System.out::println); } public static void modifyList() { userNameSource.remove(2); } public static Map<String, String> modifyMap() { Map<String, String> userNameMap = userNameMap(); userNameMap.put("bob", "bob"); userNameMap.remove("alfred"); return userNameMap; } public static void tryStreamTraversal() { Stream<String> userNameStream = userNames(); userNameStream.forEach(System.out::println); try {
userNameStream.forEach(System.out::println); } catch(IllegalStateException e) { System.out.println("stream has already been operated upon or closed"); } } public static void main(String[] args) { System.out.println(userNameMap()); System.out.println(modifyMap()); tryStreamTraversal(); Set<String> set = userNames().collect(Collectors.toCollection(TreeSet::new)); set.forEach(val -> System.out.println(val)); } }
repos\tutorials-master\core-java-modules\core-java-streams-3\src\main\java\com\baeldung\streams\streamvscollection\StreamVsCollectionExample.java
1
请在Spring Boot框架中完成以下Java代码
private String getRelativePath(EntityType entityType, String entityId) { String path = entityType.name().toLowerCase(); if (entityId != null) { path += "/" + entityId + ".json"; } return path; } private Lock getRepoLock(TenantId tenantId) { return tenantRepoLocks.computeIfAbsent(tenantId, t -> new ReentrantLock(true)); } private void logTaskExecution(VersionControlRequestCtx ctx, ListenableFuture<Void> future, long startTs) { if (log.isTraceEnabled()) { Futures.addCallback(future, new FutureCallback<Object>() {
@Override public void onSuccess(@Nullable Object result) { log.trace("[{}][{}] Task processing took: {}ms", ctx.getTenantId(), ctx.getRequestId(), (System.currentTimeMillis() - startTs)); } @Override public void onFailure(Throwable t) { log.trace("[{}][{}] Task failed: ", ctx.getTenantId(), ctx.getRequestId(), t); } }, MoreExecutors.directExecutor()); } } }
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\vc\DefaultClusterVersionControlService.java
2
请在Spring Boot框架中完成以下Java代码
static class SimpleJsonpMapperConfiguration { @Bean SimpleJsonpMapper simpleJsonpMapper() { return new SimpleJsonpMapper(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(ElasticsearchTransport.class) static class ElasticsearchTransportConfiguration { @Bean Rest5ClientTransport restClientTransport(Rest5Client restClient, JsonpMapper jsonMapper, ObjectProvider<Rest5ClientOptions> restClientOptions) { return new Rest5ClientTransport(restClient, jsonMapper, restClientOptions.getIfAvailable()); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnBean(ElasticsearchTransport.class) static class ElasticsearchClientConfiguration { @Bean @ConditionalOnMissingBean ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) { return new ElasticsearchClient(transport); } } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchClientConfigurations.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomerType extends BusinessEntityType { @XmlElement(name = "SuppliersCustomerID") protected String suppliersCustomerID; @XmlElement(name = "AccountingArea") protected String accountingArea; @XmlElement(name = "SubOrganizationID") protected String subOrganizationID; @XmlElement(name = "CustomerExtension", namespace = "http://erpel.at/schemas/1p0/documents/ext") protected CustomerExtensionType customerExtension; /** * The customer ID issued by the supplier. * * @return * possible object is * {@link String } * */ public String getSuppliersCustomerID() { return suppliersCustomerID; } /** * Sets the value of the suppliersCustomerID property. * * @param value * allowed object is * {@link String } * */ public void setSuppliersCustomerID(String value) { this.suppliersCustomerID = value; } /** * The accounting area at the document recipient's side. Used to associate a given document to a certain accounting area. * * @return * possible object is * {@link String } * */ public String getAccountingArea() { return accountingArea; } /** * Sets the value of the accountingArea property. * * @param value * allowed object is * {@link String } * */ public void setAccountingArea(String value) { this.accountingArea = value; }
/** * The ID of an internal sub organization to which the document shall be associated to at the document recipient's side. * * @return * possible object is * {@link String } * */ public String getSubOrganizationID() { return subOrganizationID; } /** * Sets the value of the subOrganizationID property. * * @param value * allowed object is * {@link String } * */ public void setSubOrganizationID(String value) { this.subOrganizationID = value; } /** * Gets the value of the customerExtension property. * * @return * possible object is * {@link CustomerExtensionType } * */ public CustomerExtensionType getCustomerExtension() { return customerExtension; } /** * Sets the value of the customerExtension property. * * @param value * allowed object is * {@link CustomerExtensionType } * */ public void setCustomerExtension(CustomerExtensionType value) { this.customerExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\CustomerType.java
2
请在Spring Boot框架中完成以下Java代码
private List<IPrintingQueueSource> createPrintingQueueSource(@NonNull final I_C_Async_Batch asyncBatch) { final IQuery<I_C_Printing_Queue> query = queryBL.createQueryBuilder(I_C_Printing_Queue.class, Env.getCtx(), ITrx.TRXNAME_None) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, asyncBatch.getC_Async_Batch_ID()) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false) .create(); final PInstanceId pinstanceId = PInstanceId.ofRepoId(asyncBatch.getAD_PInstance_ID()); final int selectionLength = query.createSelection(pinstanceId); if (selectionLength <= 0) { logger.info("Nothing to print!"); return Collections.emptyList(); } final IPrintingQueueQuery printingQuery = printingQueueBL.createPrintingQueueQuery(); printingQuery.setFilterByProcessedQueueItems(false); printingQuery.setOnlyAD_PInstance_ID(pinstanceId);
final Properties ctx = Env.getCtx(); // we need to make sure exists AD_Session_ID in context; if not, a new session will be created sessionBL.getCurrentOrCreateNewSession(ctx); return printingQueueBL.createPrintingQueueSources(ctx, printingQuery); } private void print(@NonNull final IPrintingQueueSource source, @NonNull final I_C_Async_Batch asyncBatch) { final ContextForAsyncProcessing printJobContext = ContextForAsyncProcessing.builder() .adPInstanceId(PInstanceId.ofRepoIdOrNull(asyncBatch.getAD_PInstance_ID())) .parentAsyncBatchId(asyncBatch.getC_Async_Batch_ID()) .build(); printOutputFacade.print(source, printJobContext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\serialletter\src\main\java\de\metas\letter\service\SerialLetterService.java
2
请完成以下Java代码
private Iterator<I_AD_Table> retrieveTablesWithEntityType() { final StringBuilder whereClause = new StringBuilder(); final List<Object> params = new ArrayList<Object>(); whereClause.append(" EXISTS (select 1 from AD_Column c where c.AD_Table_ID=AD_Table.AD_Table_ID and c.ColumnName=?)"); params.add("EntityType"); whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_IsView).append("=?"); params.add(false); // whereClause.append(" AND ").append(I_AD_Table.COLUMNNAME_TableName).append("='AD_Menu'"); return new TypedSqlQuery<I_AD_Table>(getCtx(), I_AD_Table.class, whereClause.toString(), ITrx.TRXNAME_None) .setParameters(params) .setOrderBy(I_AD_Table.Table_Name) .list(I_AD_Table.class)
.iterator(); } private Iterator<PO> retrieveRecordsForEntityType(final I_AD_Table table, final String entityType) { final String whereClause = "EntityType=?"; final Iterator<PO> records = new Query(getCtx(), table.getTableName(), whereClause, ITrx.TRXNAME_None) .setParameters(entityType) .setOrderBy("Created") .iterate(null, false); return records; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\process\AD_Migration_CreateFromEntityType.java
1
请完成以下Java代码
public int getResourceCode() { return resourceCode; } public Long getSuccessQps() { return successQps; } public void setSuccessQps(Long successQps) { this.successQps = successQps; } @Override public String toString() { return "MetricEntity{" + "id=" + id +
", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", timestamp=" + timestamp + ", resource='" + resource + '\'' + ", passQps=" + passQps + ", blockQps=" + blockQps + ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + rt + ", count=" + count + ", resourceCode=" + resourceCode + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricEntity.java
1
请完成以下Java代码
public List<String> getTenantIdIn() { return tenantIdIn; } @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) public void setTenantIdIn(List<String> tenantIdIn) { this.tenantIdIn = tenantIdIn; } public Boolean getWithoutTenantId() { return withoutTenantId; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getIncludeEventSubscriptionsWithoutTenantId() { return includeEventSubscriptionsWithoutTenantId; } @CamundaQueryParam(value = "includeEventSubscriptionsWithoutTenantId", converter = BooleanConverter.class) public void setIncludeEventSubscriptionsWithoutTenantId(Boolean includeEventSubscriptionsWithoutTenantId) { this.includeEventSubscriptionsWithoutTenantId = includeEventSubscriptionsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) { return engine.getRuntimeService().createEventSubscriptionQuery(); } @Override protected void applyFilters(EventSubscriptionQuery query) { if (eventSubscriptionId != null) { query.eventSubscriptionId(eventSubscriptionId); } if (eventName != null) { query.eventName(eventName); } if (eventType != null) { query.eventType(eventType); } if (executionId != null) { query.executionId(executionId); } if (processInstanceId != null) {
query.processInstanceId(processInstanceId); } if (activityId != null) { query.activityId(activityId); } if (tenantIdIn != null && !tenantIdIn.isEmpty()) { query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) { query.includeEventSubscriptionsWithoutTenantId(); } } @Override protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CREATED)) { query.orderByCreated(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java
1
请完成以下Java代码
public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag) { _taggedWith = tag; return this; } @Override public InvoiceCandRecomputeTagger setTaggedWithNoTag() { return setTaggedWith(InvoiceCandRecomputeTag.NULL); } @Override public IInvoiceCandRecomputeTagger setTaggedWithAnyTag() { return setTaggedWith(null); } /* package */ @Nullable InvoiceCandRecomputeTag getTaggedWith() { return _taggedWith; } @Override public InvoiceCandRecomputeTagger setLimit(final int limit) { this._limit = limit; return this; }
/* package */int getLimit() { return _limit; } @Override public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds; } @Override @Nullable public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds() { return onlyInvoiceCandidateIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
1
请在Spring Boot框架中完成以下Java代码
public List<HRFAD1> getHRFAD1() { if (hrfad1 == null) { hrfad1 = new ArrayList<HRFAD1>(); } return this.hrfad1; } /** * Gets the value of the hctad1 property. * * @return * possible object is * {@link HCTAD1 } * */ public HCTAD1 getHCTAD1() {
return hctad1; } /** * Sets the value of the hctad1 property. * * @param value * allowed object is * {@link HCTAD1 } * */ public void setHCTAD1(HCTAD1 value) { this.hctad1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\HADRE1.java
2
请完成以下Java代码
private final String getText() { final Content content = getContent(); if (content == null) { return ""; } final int length = content.length(); if (length <= 0) { return ""; } String str = ""; try { str = content.getString(0, length - 1); // cr at end }
catch (BadLocationException e) { // ignore it, shall not happen log.debug("Error while getting the string content", e); } catch (Exception e) { log.debug("Error while getting the string content", e); } return str; } // getString private final void provideErrorFeedback() { UIManager.getLookAndFeel().provideErrorFeedback(m_tc); } } // MDocNumber
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocNumber.java
1
请完成以下Java代码
public FreightCost findBestMatchingFreightCost(final FreightCostContext context) { final BPartnerId shipToBPartnerId = context.getShipToBPartnerId(); if (shipToBPartnerId == null) { throw new AdempiereException("ShipToBPartner not set"); } final CountryId shipToCountryId = context.getShipToCountryId(); if (shipToCountryId == null) { throw new AdempiereException("ShipToCountryId not set"); } final ShipperId shipperId = context.getShipperId(); if (shipperId == null) { throw new AdempiereException(MSG_Order_No_Shipper); } // // final FreightCost freightCost = getFreightCostByBPartnerId(shipToBPartnerId); final FreightCostShipper shipper = freightCost.getShipper(shipperId, context.getDate()); if (!shipper.isShipToCountry(shipToCountryId)) { throw new AdempiereException("@NotFound@ @M_FreightCost_ID@ (@M_Shipper_ID@:" + shipperId + ", @C_Country_ID@:" + shipToCountryId + ")"); } return freightCost; } public FreightCost getFreightCostByBPartnerId(final BPartnerId bpartnerId)
{ final IBPartnerBL bpartnerBL = Services.get(IBPartnerBL.class); final FreightCostId bpFreightCostId = FreightCostId.ofRepoIdOrNull(bpartnerBL.getFreightCostIdByBPartnerId(bpartnerId)); if (bpFreightCostId != null) { return freightCostRepo.getById(bpFreightCostId); } final FreightCost defaultFreightCost = freightCostRepo.getDefaultFreightCost().orElse(null); if (defaultFreightCost != null) { return defaultFreightCost; } throw new AdempiereException("@NotFound@ @M_FreightCost_ID@: " + bpartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\freighcost\FreightCostService.java
1
请完成以下Java代码
public String getCamundaCaseBinding() { return camundaCaseBindingAttribute.getValue(this); } public void setCamundaCaseBinding(String camundaCaseBinding) { camundaCaseBindingAttribute.setValue(this, camundaCaseBinding); } public String getCamundaCaseVersion() { return camundaCaseVersionAttribute.getValue(this); } public void setCamundaCaseVersion(String camundaCaseVersion) { camundaCaseVersionAttribute.setValue(this, camundaCaseVersion); } public String getCamundaCaseTenantId() { return camundaCaseTenantIdAttribute.getValue(this); } public void setCamundaCaseTenantId(String camundaCaseTenantId) { camundaCaseTenantIdAttribute.setValue(this, camundaCaseTenantId); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseTask.class, CMMN_ELEMENT_CASE_TASK) .extendsType(Task.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<CaseTask>() { public CaseTask newInstance(ModelTypeInstanceContext instanceContext) { return new CaseTaskImpl(instanceContext); } }); caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF) .build();
/** camunda extensions */ camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING) .namespace(CAMUNDA_NS) .build(); camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION) .namespace(CAMUNDA_NS) .build(); camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricIdentityLinkLogRestServiceImpl implements HistoricIdentityLinkLogRestService{ protected ObjectMapper objectMapper; protected ProcessEngine processEngine; public HistoricIdentityLinkLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { this.objectMapper = objectMapper; this.processEngine = processEngine; } @Override public List<HistoricIdentityLinkLogDto> getHistoricIdentityLinks(UriInfo uriInfo, Integer firstResult, Integer maxResults) { HistoricIdentityLinkLogQueryDto queryDto = new HistoricIdentityLinkLogQueryDto(objectMapper, uriInfo.getQueryParameters()); HistoricIdentityLinkLogQuery query = queryDto.toQuery(processEngine); List<HistoricIdentityLinkLog> queryResult = QueryUtil.list(query, firstResult, maxResults); List<HistoricIdentityLinkLogDto> result = new ArrayList<HistoricIdentityLinkLogDto>(); for (HistoricIdentityLinkLog historicIdentityLink : queryResult) { HistoricIdentityLinkLogDto dto = HistoricIdentityLinkLogDto.fromHistoricIdentityLink(historicIdentityLink); result.add(dto); } return result; }
@Override public CountResultDto getHistoricIdentityLinksCount(UriInfo uriInfo) { HistoricIdentityLinkLogQueryDto queryDto = new HistoricIdentityLinkLogQueryDto(objectMapper, uriInfo.getQueryParameters()); HistoricIdentityLinkLogQuery query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricIdentityLinkLogRestServiceImpl.java
2
请完成以下Java代码
public static List<PredicateDefinition> initPredicates() { ArrayList<PredicateDefinition> definitions = new ArrayList<>(); // TODO: add a predicate that matches the url at /serviceId? // add a predicate that matches the url at /serviceId/** PredicateDefinition predicate = new PredicateDefinition(); predicate.setName(normalizeRoutePredicateName(PathRoutePredicateFactory.class)); predicate.addArg(PATTERN_KEY, "'/'+serviceId+'/**'"); definitions.add(predicate); return definitions; } public static List<FilterDefinition> initFilters() { ArrayList<FilterDefinition> definitions = new ArrayList<>(); // add a filter that removes /serviceId by default FilterDefinition filter = new FilterDefinition(); filter.setName(normalizeFilterFactoryName(RewritePathGatewayFilterFactory.class)); String regex = "'/' + serviceId + '/?(?<remaining>.*)'"; String replacement = "'/${remaining}'"; filter.addArg(REGEXP_KEY, regex); filter.addArg(REPLACEMENT_KEY, replacement); definitions.add(filter); return definitions; } @Bean public DiscoveryLocatorProperties discoveryLocatorProperties() { DiscoveryLocatorProperties properties = new DiscoveryLocatorProperties(); properties.setPredicates(initPredicates()); properties.setFilters(initFilters()); return properties; }
@Configuration(proxyBeanMethods = false) @ConditionalOnProperty(value = "spring.cloud.discovery.reactive.enabled", matchIfMissing = true) public static class ReactiveDiscoveryClientRouteDefinitionLocatorConfiguration { @Bean @ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.discovery.locator.enabled") public DiscoveryClientRouteDefinitionLocator discoveryClientRouteDefinitionLocator( ReactiveDiscoveryClient discoveryClient, DiscoveryLocatorProperties properties) { return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\GatewayDiscoveryClientAutoConfiguration.java
1
请完成以下Java代码
public void setCode(final String code) { this.code = code; this.codeSet = true; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setName(final String name) { this.name = name; this.nameSet = true; } public void setFirstName(final String firstName) { this.firstName = firstName; this.firstNameSet = true; } public void setLastName(final String lastName) { this.lastName = lastName; this.lastNameSet = true; } public void setEmail(final String email) { this.email = email; this.emailSet = true; } public void setPhone(final String phone) { this.phone = phone; this.phoneSet = true; } public void setFax(final String fax) { this.fax = fax; this.faxSet = true; } public void setMobilePhone(final String mobilePhone) { this.mobilePhone = mobilePhone; this.mobilePhoneSet = true; } public void setDefaultContact(final Boolean defaultContact) { this.defaultContact = defaultContact; this.defaultContactSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true; } public void setBillToDefault(final Boolean billToDefault) {
this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setNewsletter(final Boolean newsletter) { this.newsletter = newsletter; this.newsletterSet = true; } public void setDescription(final String description) { this.description = description; this.descriptionSet = true; } public void setSales(final Boolean sales) { this.sales = sales; this.salesSet = true; } public void setSalesDefault(final Boolean salesDefault) { this.salesDefault = salesDefault; this.salesDefaultSet = true; } public void setPurchase(final Boolean purchase) { this.purchase = purchase; this.purchaseSet = true; } public void setPurchaseDefault(final Boolean purchaseDefault) { this.purchaseDefault = purchaseDefault; this.purchaseDefaultSet = true; } public void setSubjectMatter(final Boolean subjectMatter) { this.subjectMatter = subjectMatter; this.subjectMatterSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestContact.java
1
请完成以下Java代码
public final boolean isDebugTrxCreateStacktrace() { return debugTrxCreateStacktrace; } @Override public final void setDebugTrxCreateStacktrace(final boolean debugTrxCreateStacktrace) { this.debugTrxCreateStacktrace = debugTrxCreateStacktrace; } @Override public final boolean isDebugTrxCloseStacktrace() { return debugTrxCloseStacktrace; } @Override public final void setDebugTrxCloseStacktrace(final boolean debugTrxCloseStacktrace) { this.debugTrxCloseStacktrace = debugTrxCloseStacktrace; } @Override public final void setDebugClosedTransactions(final boolean enabled) { trxName2trxLock.lock(); try { if (enabled) { if (debugClosedTransactionsList == null) { debugClosedTransactionsList = new ArrayList<>(); } } else { debugClosedTransactionsList = null; } } finally { trxName2trxLock.unlock(); } } @Override public final boolean isDebugClosedTransactions() { return debugClosedTransactionsList != null; } @Override public final List<ITrx> getDebugClosedTransactions()
{ trxName2trxLock.lock(); try { if (debugClosedTransactionsList == null) { return Collections.emptyList(); } return new ArrayList<>(debugClosedTransactionsList); } finally { trxName2trxLock.unlock(); } } @Override public void setDebugConnectionBackendId(boolean debugConnectionBackendId) { this.debugConnectionBackendId = debugConnectionBackendId; } @Override public boolean isDebugConnectionBackendId() { return debugConnectionBackendId; } @Override public String toString() { return "AbstractTrxManager [trxName2trx=" + trxName2trx + ", trxName2trxLock=" + trxName2trxLock + ", trxNameGenerator=" + trxNameGenerator + ", threadLocalTrx=" + threadLocalTrx + ", threadLocalOnRunnableFail=" + threadLocalOnRunnableFail + ", debugTrxCreateStacktrace=" + debugTrxCreateStacktrace + ", debugTrxCloseStacktrace=" + debugTrxCloseStacktrace + ", debugClosedTransactionsList=" + debugClosedTransactionsList + ", debugConnectionBackendId=" + debugConnectionBackendId + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrxManager.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.jpa.open-in-view=false spring.datasource.initialization-mode=always spring.datasource.platform=mysql # Activating this setting will report HHH000104 warning an exception of type: # org.hibernate.HibernateException: firstResult/maxResults spec
ified with collection fetch. # In memory pagination was about to be applied. Failing because 'Fail on pagination over # collection fetch' is enabled. spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true
repos\Hibernate-SpringBoot-master\HibernateSpringBootHHH000104\src\main\resources\application.properties
2
请完成以下Java代码
public int getC_DunningLevel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Notiz. @param Note Optional weitere Information */ @Override public void setNote (java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Notiz. @return Optional weitere Information */ @Override public java.lang.String getNote () { return (java.lang.String)get_Value(COLUMNNAME_Note); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo);
} return false; } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line.java
1
请在Spring Boot框架中完成以下Java代码
private Map<StatisticMetric, BigDecimal> createStatisticMetrics(Set<ItemMetric> incomes, Set<ItemMetric> expenses, Saving saving) { BigDecimal savingAmount = ratesService.convert(saving.getCurrency(), Currency.getBase(), saving.getAmount()); BigDecimal expensesAmount = expenses.stream() .map(ItemMetric::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal incomesAmount = incomes.stream() .map(ItemMetric::getAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); return ImmutableMap.of( StatisticMetric.EXPENSES_AMOUNT, expensesAmount, StatisticMetric.INCOMES_AMOUNT, incomesAmount, StatisticMetric.SAVING_AMOUNT, savingAmount
); } /** * Normalizes given item amount to {@link Currency#getBase()} currency with * {@link TimePeriod#getBase()} time period */ private ItemMetric createItemMetric(Item item) { BigDecimal amount = ratesService .convert(item.getCurrency(), Currency.getBase(), item.getAmount()) .divide(item.getPeriod().getBaseRatio(), 4, RoundingMode.HALF_UP); return new ItemMetric(item.getTitle(), amount); } }
repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\service\StatisticsServiceImpl.java
2
请完成以下Java代码
private final Properties getCtx() { return Env.getCtx(); } @Override public void vetoableChange(final PropertyChangeEvent evt) throws PropertyVetoException { // Try apply UOM conversion doConvert("" + evt.getPropertyName() + " field changed"); } private I_M_Product getM_Product() { return toModel(I_M_Product.class, fieldProduct.getValue()); } private I_C_UOM getC_UOM() { return toModel(I_C_UOM.class, fieldUOM.getValue()); } private I_C_UOM getC_UOM_To() { return toModel(I_C_UOM.class, fieldUOMTo.getValue()); } private BigDecimal getQty() { final BigDecimal qty = (BigDecimal)fieldQty.getValue(); return qty == null ? BigDecimal.ZERO : qty; } private void setQtyConv(final BigDecimal qtyConv) { fieldQtyConv.setValue(qtyConv, true); } private void setDescription(final String description) { fieldDescription.setValue(description, true); } private <T> T toModel(final Class<T> modelClass, final Object idObj) { final int id = toID(idObj); if (id <= 0) { return null; } return InterfaceWrapperHelper.create(getCtx(), id, modelClass, ITrx.TRXNAME_None); } private static final int toID(final Object idObj) { if (idObj == null) { return -1; } else if (idObj instanceof Number) { return ((Number)idObj).intValue(); }
else { return -1; } } private void doConvert(final String reason) { // Reset setDescription(null); setQtyConv(null); final I_C_UOM uomFrom = getC_UOM(); final I_C_UOM uomTo = getC_UOM_To(); if (uomFrom == null || uomTo == null) { return; } final I_M_Product product = getM_Product(); final BigDecimal qty = getQty(); try { final BigDecimal qtyConv; if (product != null) { final UOMConversionContext conversionCtx = UOMConversionContext.of(product); qtyConv = uomConversionBL.convertQty(conversionCtx, qty, uomFrom, uomTo); } else { qtyConv = uomConversionBL.convert(uomFrom, uomTo, qty).orElse(null); } setQtyConv(qtyConv); setDescription("Converted " + NumberUtils.stripTrailingDecimalZeros(qty) + " " + uomFrom.getUOMSymbol() + " to " + NumberUtils.stripTrailingDecimalZeros(qtyConv) + " " + uomTo.getUOMSymbol() + "<br>Product: " + (product == null ? "-" : product.getName()) + "<br>Reason: " + reason); } catch (final Exception e) { setDescription(e.getLocalizedMessage()); // because this is a test form, printing the exception directly to console it's totally fine. // More, if we would log it as WARNING/SEVERE, an AD_Issue would be created, but we don't want that. e.printStackTrace(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\uom\form\UOMConversionCheckFormPanel.java
1
请完成以下Java代码
protected boolean beforeSave(boolean newRecord) { final IConnector connector = Util.getInstance(IConnector.class, getClassname()); if (connector instanceof IImportConnector) { if (!DIRECTION_Import.equals(getDirection())) { throw new AdempiereException("This in an export type, but the implementation is for import"); } } else if (connector instanceof IExportConnector) { if (!DIRECTION_Export.equals(getDirection())) { throw new AdempiereException("This in an import type, but the implementation is for export"); } } else { throw new AdempiereException("Connector must be an import or export connector"); } return true; }
/** * */ private static final long serialVersionUID = 6990832919448186931L; public MImpExConnectorType(Properties ctx, int C_ImpExConnectorType_ID, String trxName) { super(ctx, C_ImpExConnectorType_ID, trxName); } public MImpExConnectorType(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\model\MImpExConnectorType.java
1
请完成以下Java代码
public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } @Override public void setMovementQty (final BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } @Override public BigDecimal getMovementQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerLU (final @Nullable BigDecimal QtyCUsPerLU) { set_Value (COLUMNNAME_QtyCUsPerLU, QtyCUsPerLU); } @Override public BigDecimal getQtyCUsPerLU() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerLU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerLU_InInvoiceUOM) { set_Value (COLUMNNAME_QtyCUsPerLU_InInvoiceUOM, QtyCUsPerLU_InInvoiceUOM); } @Override public BigDecimal getQtyCUsPerLU_InInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU_InInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerTU (final @Nullable BigDecimal QtyCUsPerTU) { set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU); } @Override public BigDecimal getQtyCUsPerTU() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCUsPerTU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerTU_InInvoiceUOM) { set_Value (COLUMNNAME_QtyCUsPerTU_InInvoiceUOM, QtyCUsPerTU_InInvoiceUOM); } @Override public BigDecimal getQtyCUsPerTU_InInvoiceUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU_InInvoiceUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity) { set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity); } @Override public BigDecimal getQtyItemCapacity() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyTU (final int QtyTU) { set_Value (COLUMNNAME_QtyTU, QtyTU); } @Override public int getQtyTU() { return get_ValueAsInt(COLUMNNAME_QtyTU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack_Item.java
1
请在Spring Boot框架中完成以下Java代码
public DataSource dataSource() { return DataSourceBuilder.create().build(); } /** * 创建 MyBatis SqlSessionFactory */ @Bean(name = "ordersSqlSessionFactory") public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 设置 orders 数据源 bean.setDataSource(this.dataSource()); // 设置 entity 所在包 bean.setTypeAliasesPackage("cn.iocoder.springboot.lab17.dynamicdatasource.dataobject"); // 设置 config 路径 bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml")); // 设置 mapper 路径 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/orders/*.xml")); return bean.getObject(); } /**
* 创建 MyBatis SqlSessionTemplate */ @Bean(name = "ordersSqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(this.sqlSessionFactory()); } /** * 创建 orders 数据源的 TransactionManager 事务管理器 */ @Bean(name = DBConstants.TX_MANAGER_ORDERS) public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(this.dataSource()); } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-mybatis\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\config\MyBatisOrdersConfig.java
2
请完成以下Java代码
public JobDefinitionQuery includeJobDefinitionsWithoutTenantId() { this.includeJobDefinitionsWithoutTenantId = true; return this; } // order by /////////////////////////////////////////// public JobDefinitionQuery orderByJobDefinitionId() { return orderBy(JobDefinitionQueryProperty.JOB_DEFINITION_ID); } public JobDefinitionQuery orderByActivityId() { return orderBy(JobDefinitionQueryProperty.ACTIVITY_ID); } public JobDefinitionQuery orderByProcessDefinitionId() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_ID); } public JobDefinitionQuery orderByProcessDefinitionKey() { return orderBy(JobDefinitionQueryProperty.PROCESS_DEFINITION_KEY); } public JobDefinitionQuery orderByJobType() { return orderBy(JobDefinitionQueryProperty.JOB_TYPE); } public JobDefinitionQuery orderByJobConfiguration() { return orderBy(JobDefinitionQueryProperty.JOB_CONFIGURATION); } public JobDefinitionQuery orderByTenantId() { return orderBy(JobDefinitionQueryProperty.TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefinitionCountByQueryCriteria(this); } @Override public List<JobDefinition> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobDefinitionManager() .findJobDefnitionByQueryCriteria(this, page);
} // getters ///////////////////////////////////////////// public String getId() { return id; } public String[] getActivityIds() { return activityIds; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getJobType() { return jobType; } public String getJobConfiguration() { return jobConfiguration; } public SuspensionState getSuspensionState() { return suspensionState; } public Boolean getWithOverridingJobPriority() { return withOverridingJobPriority; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java
1
请完成以下Java代码
public InOutGenerateResult createEmptyInOutGenerateResult(final boolean storeReceipts) { return new DefaultInOutGenerateResult(storeReceipts); } @Override public ReceiptQty getQtyAndQuality(final org.compiere.model.I_M_InOutLine inoutLine0) { I_M_InOutLine inoutLine = InterfaceWrapperHelper.create(inoutLine0, I_M_InOutLine.class); final ProductId productId = ProductId.ofRepoId(inoutLine.getM_Product_ID()); // note: QtyEnetered and MovementQty are currently the same, but that's just because we are in the habit of setting M_InOutLine.C_UOM to the respective prodcuts stocking UOM. // therefore, we need to use MovementQty, unless we decide to add the UOM to this game, too (but currently i don't see the point). final BigDecimal qtyInUOM; final UomId uomId; final ReceiptQty qtys; if (InterfaceWrapperHelper.isNull(inoutLine, I_M_InOutLine.COLUMNNAME_QtyDeliveredCatch)) { qtyInUOM = null; uomId = null; qtys = ReceiptQty.newWithoutCatchWeight(productId); } else { qtyInUOM = inoutLine.getQtyDeliveredCatch(); uomId = UomId.ofRepoId(inoutLine.getCatch_UOM_ID()); qtys = ReceiptQty.newWithCatchWeight(productId, uomId); }
final StockQtyAndUOMQty qtyMoved = StockQtyAndUOMQtys.create(inoutLine.getMovementQty(), productId, qtyInUOM, uomId); final StockQtyAndUOMQty qtyMovedWithIssues; if (inoutLine.isInDispute()) { qtyMovedWithIssues = qtyMoved; } else { qtyMovedWithIssues = qtyMoved.toZero(); } qtys.addQtyAndQtyWithIssues(qtyMoved, qtyMovedWithIssues); qtys.addQualityNotices(QualityNoticesCollection.valueOfQualityNoticesString(inoutLine.getQualityNote())); return qtys; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\InOutCandidateBL.java
1
请完成以下Java代码
public HUEditorRowFilter andOnlyRowIds(final DocumentIdsSelection rowIds) { if (rowIds.isAll()) { // nothing to do return this; } else { return toBuilder().onlyRowIdsFromSelection(rowIds).build(); } } public static final class Builder { public Builder onlyActiveHUs() { onlyHUStatus(X_M_HU.HUSTATUS_Active); return this; }
public Builder onlyRowIdsFromSelection(DocumentIdsSelection rowIds) { if (rowIds.isAll()) { // nothing } else if (rowIds.isEmpty()) { throw new AdempiereException("Empty rowIds is not allowed"); } else { onlyRowIds(rowIds.toSet(HUEditorRowId::ofDocumentId)); } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowFilter.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<? extends Boolean> apply(UserDO usernameUserDO) { // 如果用户名已经使用(该用户名对应的 id 不是自己,说明就已经被使用了) if (usernameUserDO != USER_NULL && !Objects.equals(updateDTO.getId(), usernameUserDO.getId())) { return Mono.just(false); } // 执行更新 userDO.setUsername(updateDTO.getUsername()); userDO.setPassword(updateDTO.getPassword()); return userRepository.save(userDO).map(userDO -> true); // 返回 true 成功 } }); } }); } /** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE public Mono<Boolean> delete(@RequestParam("id") Integer id) { // 查询用户 Mono<UserDO> user = userRepository.findById(id); // 执行删除。这里仅仅是示例,项目中不要物理删除,而是标记删除 return user.defaultIfEmpty(USER_NULL) // 设置 USER_NULL 作为 null 的情况,否则 flatMap 不会往下走
.flatMap(new Function<UserDO, Mono<Boolean>>() { @Override public Mono<Boolean> apply(UserDO userDO) { // 如果不存在该用户,则直接返回 false 失败 if (userDO == USER_NULL) { return Mono.just(false); } // 执行删除 return userRepository.deleteById(id).map(aVoid -> true); // 返回 true 成功 } }); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-elasticsearch\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isRfq() { return rfq_uuid != null; } public List<ContractLine> getContractLines() { return Collections.unmodifiableList(contractLines); } @Nullable public ContractLine getContractLineForProductOrNull(final Product product) { for (final ContractLine contractLine : getContractLines()) { if (Product.COMPARATOR_Id.compare(contractLine.getProduct(), product) != 0) { continue; } return contractLine; } return null; } public Collection<Product> getProducts() { final Set<Product> products = new TreeSet<>(Product.COMPARATOR_Id); for (final ContractLine contractLine : getContractLines()) {
if (contractLine.isDeleted()) { continue; } final Product product = contractLine.getProduct(); if (product.isDeleted()) { continue; } products.add(product); } return products; } public boolean matchesDate(final LocalDate date) { return DateUtils.between(date, getDateFrom(), getDateTo()); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Contract.java
2
请完成以下Java代码
public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @Override public Resource[] getDeploymentResources() { return deploymentResources; } @Override public void setDeploymentResources(Resource[] deploymentResources) { this.deploymentResources = deploymentResources; } @Override public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public String getDeploymentMode() { return deploymentMode; } @Override public void setDeploymentMode(String deploymentMode) { this.deploymentMode = deploymentMode; } /** * Gets the {@link AutoDeploymentStrategy} for the provided mode. This method may be overridden to implement custom deployment strategies if required, but implementors should take care not to * return <code>null</code>. * * @param mode * the mode to get the strategy for * @return the deployment strategy to use for the mode. Never <code>null</code> */ protected AutoDeploymentStrategy<AppEngine> getAutoDeploymentStrategy(final String mode) { AutoDeploymentStrategy<AppEngine> result = new DefaultAutoDeploymentStrategy(); for (final AutoDeploymentStrategy<AppEngine> strategy : deploymentStrategies) { if (strategy.handlesMode(mode)) { result = strategy; break; } } return result;
} @Override public void start() { synchronized (lifeCycleMonitor) { if (!isRunning()) { enginesBuild.forEach(name -> autoDeployResources(AppEngines.getAppEngine(name))); running = true; } } } public Collection<AutoDeploymentStrategy<AppEngine>> getDeploymentStrategies() { return deploymentStrategies; } public void setDeploymentStrategies(Collection<AutoDeploymentStrategy<AppEngine>> deploymentStrategies) { this.deploymentStrategies = deploymentStrategies; } @Override public void stop() { synchronized (lifeCycleMonitor) { running = false; } } @Override public boolean isRunning() { return running; } @Override public String getDeploymentName() { return null; } @Override public void setDeploymentName(String deploymentName) { // not supported throw new FlowableException("Setting a deployment name is not supported for apps"); } }
repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\SpringAppEngineConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getTradeCount() { return tradeCount; } public void setTradeCount(Integer tradeCount) { this.tradeCount = tradeCount; } public Integer getBankTradeCount() { return bankTradeCount; } public void setBankTradeCount(Integer bankTradeCount) { this.bankTradeCount = bankTradeCount; } public BigDecimal getTradeAmount() { return tradeAmount; } public void setTradeAmount(BigDecimal tradeAmount) { this.tradeAmount = tradeAmount; } public BigDecimal getBankTradeAmount() { return bankTradeAmount; } public void setBankTradeAmount(BigDecimal bankTradeAmount) { this.bankTradeAmount = bankTradeAmount; } public BigDecimal getRefundAmount() { return refundAmount; } public void setRefundAmount(BigDecimal refundAmount) { this.refundAmount = refundAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; }
public String getOrgCheckFilePath() { return orgCheckFilePath; } public void setOrgCheckFilePath(String orgCheckFilePath) { this.orgCheckFilePath = orgCheckFilePath == null ? null : orgCheckFilePath.trim(); } public String getReleaseCheckFilePath() { return releaseCheckFilePath; } public void setReleaseCheckFilePath(String releaseCheckFilePath) { this.releaseCheckFilePath = releaseCheckFilePath == null ? null : releaseCheckFilePath.trim(); } public String getReleaseStatus() { return releaseStatus; } public void setReleaseStatus(String releaseStatus) { this.releaseStatus = releaseStatus == null ? null : releaseStatus.trim(); } public BigDecimal getFee() { return fee; } public void setFee(BigDecimal fee) { this.fee = fee; } public String getCheckFailMsg() { return checkFailMsg; } public void setCheckFailMsg(String checkFailMsg) { this.checkFailMsg = checkFailMsg; } public String getBankErrMsg() { return bankErrMsg; } public void setBankErrMsg(String bankErrMsg) { this.bankErrMsg = bankErrMsg; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckBatch.java
2
请完成以下Java代码
public void setC_OLCandProcessor(final de.metas.ordercandidate.model.I_C_OLCandProcessor C_OLCandProcessor) { set_ValueFromPO(COLUMNNAME_C_OLCandProcessor_ID, de.metas.ordercandidate.model.I_C_OLCandProcessor.class, C_OLCandProcessor); } @Override public void setC_OLCandProcessor_ID (final int C_OLCandProcessor_ID) { if (C_OLCandProcessor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, C_OLCandProcessor_ID); } @Override public int getC_OLCandProcessor_ID() { return get_ValueAsInt(COLUMNNAME_C_OLCandProcessor_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * Granularity AD_Reference_ID=540141 * Reference name: Granularity OLCandAggAndOrder */ public static final int GRANULARITY_AD_Reference_ID=540141; /** Tag = D */ public static final String GRANULARITY_Tag = "D"; /** Woche = W */ public static final String GRANULARITY_Woche = "W"; /** Monat = M */ public static final String GRANULARITY_Monat = "M"; @Override public void setGranularity (final @Nullable java.lang.String Granularity) { set_Value (COLUMNNAME_Granularity, Granularity); } @Override public java.lang.String getGranularity() { return get_ValueAsString(COLUMNNAME_Granularity); } @Override public void setGroupBy (final boolean GroupBy) { set_Value (COLUMNNAME_GroupBy, GroupBy);
} @Override public boolean isGroupBy() { return get_ValueAsBoolean(COLUMNNAME_GroupBy); } @Override public void setOrderBySeqNo (final int OrderBySeqNo) { set_Value (COLUMNNAME_OrderBySeqNo, OrderBySeqNo); } @Override public int getOrderBySeqNo() { return get_ValueAsInt(COLUMNNAME_OrderBySeqNo); } @Override public void setSplitOrder (final boolean SplitOrder) { set_Value (COLUMNNAME_SplitOrder, SplitOrder); } @Override public boolean isSplitOrder() { return get_ValueAsBoolean(COLUMNNAME_SplitOrder); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandAggAndOrder.java
1
请完成以下Java代码
public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType) { if (actionType == CopyPasteActionType.Copy) { return hasTextToCopy(); } else if (actionType == CopyPasteActionType.Cut) { return isEditable() && hasTextToCopy(); } else if (actionType == CopyPasteActionType.Paste) { return isEditable(); } else if (actionType == CopyPasteActionType.SelectAll) { return !isEmpty(); } else { return false; } } private final boolean isEditable() {
final JTextComponent textComponent = getTextComponent(); return textComponent.isEditable() && textComponent.isEnabled(); } private final boolean hasTextToCopy() { final JTextComponent textComponent = getTextComponent(); final String selectedText = textComponent.getSelectedText(); return selectedText != null && !selectedText.isEmpty(); } private final boolean isEmpty() { final JTextComponent textComponent = getTextComponent(); final String text = textComponent.getText(); return Check.isEmpty(text, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JTextComponentCopyPasteSupportEditor.java
1
请完成以下Java代码
public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID) { if (M_HU_PI_Attribute_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID); } @Override public int getM_HU_PI_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_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); } @Override public void setValueDate (final @Nullable java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } @Override public java.sql.Timestamp getValueDate() { return get_ValueAsTimestamp(COLUMNNAME_ValueDate); } @Override public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial) { set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial); } @Override public java.sql.Timestamp getValueDateInitial() { return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial); } @Override public void setValueInitial (final @Nullable java.lang.String ValueInitial) { set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial); } @Override
public java.lang.String getValueInitial() { return get_ValueAsString(COLUMNNAME_ValueInitial); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial) { set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial); } @Override public BigDecimal getValueNumberInitial() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public BPartnerId getBPartnerId() { return getBPartnerLocationId().getBpartnerId(); } @Override public BPartnerLocationId getBPartnerLocationId() { return groupingKey.getBpartnerLocationId(); } @Override public HUPIItemProductId getPackingMaterialId() { return groupingKey.getPackingMaterialId(); } @Override public Set<WarehouseId> getWarehouseIds() { return parts.map(PackingItemPart::getWarehouseId).collect(ImmutableSet.toImmutableSet()); } @Override public Set<ShipmentScheduleId> getShipmentScheduleIds() { return parts.map(PackingItemPart::getShipmentScheduleId).collect(ImmutableSet.toImmutableSet()); }
@Override public IPackingItem subtractToPackingItem( @NonNull final Quantity subtrahent, @Nullable final Predicate<PackingItemPart> acceptPartPredicate) { final PackingItemParts subtractedParts = subtract(subtrahent, acceptPartPredicate); return PackingItems.newPackingItem(subtractedParts); } @Override public PackingItem copy() { return new PackingItem(this); } @Override public String toString() { return "FreshPackingItem [" + "qtySum=" + getQtySum() + ", productId=" + getProductId() + ", uom=" + getC_UOM() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItem.java
2
请完成以下Java代码
class PreAuthenticatedAuthenticationTokenDeserializer extends JsonDeserializer<PreAuthenticatedAuthenticationToken> { private static final TypeReference<List<GrantedAuthority>> GRANTED_AUTHORITY_LIST = new TypeReference<>() { }; /** * This method construct {@link PreAuthenticatedAuthenticationToken} object from * serialized json. * @param jp the JsonParser * @param ctxt the DeserializationContext * @return the user * @throws IOException if a exception during IO occurs * @throws JsonProcessingException if an error during JSON processing occurs */ @Override public PreAuthenticatedAuthenticationToken deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) jp.getCodec(); JsonNode jsonNode = mapper.readTree(jp); Boolean authenticated = readJsonNode(jsonNode, "authenticated").asBoolean(); JsonNode principalNode = readJsonNode(jsonNode, "principal"); Object principal = (!principalNode.isObject()) ? principalNode.asText() : mapper.readValue(principalNode.traverse(mapper), Object.class);
Object credentials = readJsonNode(jsonNode, "credentials").asText(); List<GrantedAuthority> authorities = mapper.readValue(readJsonNode(jsonNode, "authorities").traverse(mapper), GRANTED_AUTHORITY_LIST); PreAuthenticatedAuthenticationToken token = (!authenticated) ? new PreAuthenticatedAuthenticationToken(principal, credentials) : new PreAuthenticatedAuthenticationToken(principal, credentials, authorities); token.setDetails(readJsonNode(jsonNode, "details")); return token; } private JsonNode readJsonNode(JsonNode jsonNode, String field) { return jsonNode.has(field) ? jsonNode.get(field) : MissingNode.getInstance(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\jackson2\PreAuthenticatedAuthenticationTokenDeserializer.java
1
请完成以下Java代码
public AppDefinitionCacheEntry getAppDefinitionCacheEntry(String appDefinitionId) { return appDefinitionCache.get(appDefinitionId); } // getters and setters //////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources;
} @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; } @Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "AppDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java
1
请完成以下Java代码
public static ProductHUInventory of(@NonNull final ProductId productId, @NonNull final List<HuForInventoryLine> huForInventoryLineList) { final boolean notAllLinesMatchTheProduct = huForInventoryLineList.stream() .anyMatch(huForInventoryLine -> !huForInventoryLine.getProductId().equals(productId)); if (notAllLinesMatchTheProduct) { throw new AdempiereException("Not all huForInventoryLineList match the given product!") .appendParametersToMessage() .setParameter("huForInventoryLineList", huForInventoryLineList) .setParameter("productId", productId); } return new ProductHUInventory(productId, ImmutableList.copyOf(huForInventoryLineList)); } @NonNull public Quantity getTotalQtyBooked( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final I_C_UOM uom) { return huForInventoryLineList.stream() .map(HuForInventoryLine::getQuantityBooked) .map(qty -> uomConversionBL.convertQuantityTo(qty, productId, UomId.ofRepoId(uom.getC_UOM_ID()))) .reduce(Quantity::add) .orElseGet(() -> Quantity.zero(uom)); } @NonNull public Map<LocatorId, ProductHUInventory> mapByLocatorId() { return mapByKey(HuForInventoryLine::getLocatorId); } @NonNull public Map<WarehouseId, ProductHUInventory> mapByWarehouseId() { return mapByKey(huForInventoryLine -> huForInventoryLine.getLocatorId().getWarehouseId()); } @NonNull public List<InventoryLineHU> toInventoryLineHUs( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final UomId targetUomId) { final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId); return huForInventoryLineList.stream()
.map(DraftInventoryLinesCreateCommand::toInventoryLineHU) .map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter)) .collect(ImmutableList.toImmutableList()); } @NonNull public Set<HuId> getHuIds() { return huForInventoryLineList.stream() .map(HuForInventoryLine::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } @NonNull private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider) { final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>(); huForInventoryLineList.forEach(hu -> { final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>(); husFromTargetWarehouse.add(hu); key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> { oldList.addAll(newList); return oldList; }); }); return key2Hus.keySet() .stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId)))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
1
请完成以下Java代码
public class TimerEventListener extends EventListener { protected String timerExpression; protected String timerStartTriggerSourceRef; protected PlanItem timerStartTriggerPlanItem; protected String timerStartTriggerStandardEvent; public String getTimerExpression() { return timerExpression; } public void setTimerExpression(String timerExpression) { this.timerExpression = timerExpression; } public String getTimerStartTriggerSourceRef() { return timerStartTriggerSourceRef; } public void setTimerStartTriggerSourceRef(String timerStartTriggerSourceRef) {
this.timerStartTriggerSourceRef = timerStartTriggerSourceRef; } public PlanItem getTimerStartTriggerPlanItem() { return timerStartTriggerPlanItem; } public void setTimerStartTriggerPlanItem(PlanItem timerStartTriggerPlanItem) { this.timerStartTriggerPlanItem = timerStartTriggerPlanItem; } public String getTimerStartTriggerStandardEvent() { return timerStartTriggerStandardEvent; } public void setTimerStartTriggerStandardEvent(String timerStartTriggerStandardEvent) { this.timerStartTriggerStandardEvent = timerStartTriggerStandardEvent; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\TimerEventListener.java
1
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public Date getJoinDate() { return joinDate; } public void setJoinDate(Date joinDate) { this.joinDate = joinDate; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-annotations-2\src\main\java\com\baeldung\queryhint\Employee.java
1
请完成以下Java代码
public void setM_Material_Tracking_Report_ID (int M_Material_Tracking_Report_ID) { if (M_Material_Tracking_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, Integer.valueOf(M_Material_Tracking_Report_ID)); } /** Get M_Material_Tracking_Report. @return M_Material_Tracking_Report */ @Override public int getM_Material_Tracking_Report_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setGLN (final @Nullable java.lang.String GLN) { set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() {
return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setLookup_Label (final @Nullable java.lang.String Lookup_Label) { set_ValueNoCheck (COLUMNNAME_Lookup_Label, Lookup_Label); } @Override public java.lang.String getLookup_Label() { return get_ValueAsString(COLUMNNAME_Lookup_Label); } @Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_Value (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Lookup_BPL_GLN_v.java
1
请完成以下Java代码
private static long getStep() { // 30 seconds StepSize (ID TOTP) return SystemTime.millis() / 30000; } private static OTP computeOTP(final long step, @NonNull final SecretKey secretKey) { String steps = Long.toHexString(step).toUpperCase(); while (steps.length() < 16) { steps = "0" + steps; } // Get the HEX in a Byte[] final byte[] msg = hexStr2Bytes(steps); final byte[] k = hexStr2Bytes(secretKey.toHexString()); final byte[] hash = hmac_sha1(k, msg); // put selected bytes into result int final int offset = hash[hash.length - 1] & 0xf; final int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); final int otp = binary % 1000000; String result = Integer.toString(otp); while (result.length() < 6) { result = "0" + result; } return OTP.ofString(result); } /** * @return hex string converted to byte array */ private static byte[] hexStr2Bytes(final CharSequence hex) { // Adding one byte to get the right conversion // values starting with "0" can be converted final byte[] bArray = new BigInteger("10" + hex, 16).toByteArray(); final byte[] ret = new byte[bArray.length - 1]; // Copy all the REAL bytes, not the "first" System.arraycopy(bArray, 1, ret, 0, ret.length); return ret; }
/** * This method uses the JCE to provide the crypto algorithm. HMAC computes a Hashed Message Authentication Code with the crypto hash * algorithm as a parameter. * * @param keyBytes the bytes to use for the HMAC key * @param text the message or text to be authenticated. */ private static byte[] hmac_sha1(final byte[] keyBytes, final byte[] text) { try { final Mac hmac = Mac.getInstance("HmacSHA1"); final SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); hmac.init(macKey); return hmac.doFinal(text); } catch (final GeneralSecurityException gse) { throw new UndeclaredThrowableException(gse); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\TOTPUtils.java
1
请完成以下Java代码
public class Authentication { protected String authenticatedUserId; protected List<String> authenticatedGroupIds; protected List<String> authenticatedTenantIds; public Authentication() { } public Authentication(String authenticatedUserId, List<String> groupIds) { this(authenticatedUserId, groupIds, null); } public Authentication(String authenticatedUserId, List<String> authenticatedGroupIds, List<String> authenticatedTenantIds) { this.authenticatedUserId = authenticatedUserId; if (authenticatedGroupIds != null) { this.authenticatedGroupIds = new ArrayList<String>(authenticatedGroupIds); } if (authenticatedTenantIds != null) { this.authenticatedTenantIds = new ArrayList<String>(authenticatedTenantIds);
} } public List<String> getGroupIds() { return authenticatedGroupIds; } public String getUserId() { return authenticatedUserId; } public List<String> getTenantIds() { return authenticatedTenantIds; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\Authentication.java
1
请完成以下Java代码
public Object retry(ProceedingJoinPoint joinPoint) throws Exception { // 获取注解 Retryable retryable = AnnotationUtils.findAnnotation(getSpecificmethod(joinPoint), Retryable.class); // 声明Callable Callable<Object> task = () -> getTask(joinPoint); // 声明guava retry对象 Retryer<Object> retryer = null; try { retryer = RetryerBuilder.newBuilder() // 指定触发重试的条件 .retryIfResult(Predicates.isNull()) // 指定触发重试的异常 .retryIfExceptionOfType(retryable.exception())// 抛出Exception异常时重试 // 尝试次数 .withStopStrategy(StopStrategies.stopAfterAttempt(retryable.attemptNumber())) // 重调策略 .withWaitStrategy(WaitStrategies.fixedWait(retryable.sleepTime(), retryable.timeUnit()))// 等待300毫秒 // 指定监听器RetryListener .withRetryListener(retryable.retryListener().newInstance()) .build(); } catch (Exception e) { logger.error(e.getMessage(), e); throw e; } try { // 执行方法 return retryer.call(task); } catch (ExecutionException e) { logger.error(e.getMessage(), e); } catch (RetryException e) { logger.error(e.getMessage(), e); }
return null; } private Object getTask(ProceedingJoinPoint joinPoint) { // 执行方法,并获取返回值 try { return joinPoint.proceed(); } catch (Throwable throwable) { logger.error(throwable.getMessage(), throwable); throw new RuntimeException("执行任务异常"); } } private Method getSpecificmethod(ProceedingJoinPoint pjp) { MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // The method may be on an interface, but we need attributes from the // target class. If the target class is null, the method will be // unchanged. Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget()); if (targetClass == null && pjp.getTarget() != null) { targetClass = pjp.getTarget().getClass(); } Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the // original method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); return specificMethod; } }
repos\spring-boot-student-master\spring-boot-student-guava-retrying\src\main\java\com\xiaolyuh\aspect\RetryAspect.java
1
请完成以下Java代码
public RT getResult() { return processor.getResult(); } /** * @return always return <code>false</code>. Each item is a separated chunk */ @Override public boolean isSameChunk(final IT item) { return false; } @Override public void newChunk(final IT item)
{ // nothing } @Override public void completeChunk() { // nothing } @Override public void cancelChunk() { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemProcessor2TrxItemChunkProcessorWrapper.java
1
请完成以下Java代码
class TableReferenceInfo { private final String refTableName; private final int refDisplayType; private final String entityType; private final boolean isKey; private final int keyReferenceValueId; public TableReferenceInfo(final String refTableName , final int refDisplayType , final String entityType , final boolean isKey , final int keyReferenceValueId) { super(); this.refTableName = refTableName; this.refDisplayType = refDisplayType; this.entityType = entityType; this.isKey = isKey; this.keyReferenceValueId = keyReferenceValueId; } @Override public String toString() { return ObjectUtils.toString(this); } /** * @return AD_Ref_Table.AD_Table_ID.TableName */ public String getRefTableName() { return refTableName; } /** * * @return AD_Ref_Table.AD_Key.AD_Reference_ID */ public int getRefDisplayType() {
return refDisplayType; } /** * * @return AD_Ref_Table.AD_Table_ID.EntityType */ public String getEntityType() { return entityType; } /** * * @return AD_Ref_Table.AD_Key.IsKey */ public boolean isKey() { return isKey; } /** * * @return AD_Ref_Table.AD_Key.AD_Reference_Value_ID */ public int getKeyReferenceValueId() { return keyReferenceValueId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\TableReferenceInfo.java
1
请完成以下Java代码
public class VaadinFlowBasics extends VerticalLayout { public VaadinFlowBasics() { // Add components to the layout with the add method add(new H1("Vaadin Flow Basics")); // Components are Java objects var textField = new TextField("Name"); var button = new Button("Click me"); // Layouts define the structure of the UI var verticalLayout = new VerticalLayout( new Button("Top"), new Button("Middle"), new Button("Bottom") ); add(verticalLayout); var horizontalLayout = new HorizontalLayout( new Button("Left"), new Button("Center"), new Button("Right") ); add(horizontalLayout); // Layouts can be nested for more complex structures
var nestedLayout = new VerticalLayout( new HorizontalLayout(new Button("Top Left"), new Button("Top Right")), new HorizontalLayout(new Button("Bottom Left"), new Button("Bottom Right")) ); add(nestedLayout); add(new RouterLink("Example layout", ExampleLayout.class)); // Use RouterLink to navigate to other views var link = new RouterLink("Hello world view", HelloWorldView.class); add(link); // Use events to react to user input var nameField = new TextField("Your name"); var helloButton = new Button("Say hello"); helloButton.addClickListener(e -> { Notification.show("Hello, " + nameField.getValue()); }); add(nameField, helloButton); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\introduction\basics\VaadinFlowBasics.java
1
请在Spring Boot框架中完成以下Java代码
protected void ensurePreviousCaseDefinitionIdInitialized() { if (previousCaseDefinitionId == null && !firstVersion) { previousCaseDefinitionId = Context .getCommandContext() .getCaseDefinitionManager() .findPreviousCaseDefinitionId(key, version, tenantId); if (previousCaseDefinitionId == null) { firstVersion = true; } } } @Override protected CmmnExecution newCaseInstance() { CaseExecutionEntity caseInstance = new CaseExecutionEntity(); if (tenantId != null) { caseInstance.setTenantId(tenantId); } Context .getCommandContext() .getCaseExecutionManager() .insertCaseExecution(caseInstance); return caseInstance; } public Object getPersistentState() { Map<String, Object> persistentState = new HashMap<String, Object>(); persistentState.put("historyTimeToLive", this.historyTimeToLive); return persistentState; } @Override
public String toString() { return "CaseDefinitionEntity["+id+"]"; } /** * Updates all modifiable fields from another case definition entity. * @param updatingCaseDefinition */ @Override public void updateModifiableFieldsFromEntity(CaseDefinitionEntity updatingCaseDefinition) { if (this.key.equals(updatingCaseDefinition.key) && this.deploymentId.equals(updatingCaseDefinition.deploymentId)) { this.revision = updatingCaseDefinition.revision; this.historyTimeToLive = updatingCaseDefinition.historyTimeToLive; } else { LOG.logUpdateUnrelatedCaseDefinitionEntity(this.key, updatingCaseDefinition.key, this.deploymentId, updatingCaseDefinition.deploymentId); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionEntity.java
2
请在Spring Boot框架中完成以下Java代码
public class Company { private String name; private String contact; private String type; public Company() { } public Company(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
repos\tutorials-master\spring-boot-modules\spring-boot-groovy\src\main\java\com\baeldung\springgroovyconfig\Company.java
2
请完成以下Java代码
public class PerformanceDetail extends CFrame implements ActionListener { /** * */ private static final long serialVersionUID = -5994488373513922522L; /** * Constructor. * Called from PAPanel, ViewPI (Performance Indicator) * @param goal goal */ public PerformanceDetail (MGoal goal) { super (goal.getName()); setIconImage(Adempiere.getProductIconSmall()); barPanel = new Graph(goal, true); init(); AEnv.addToWindowManager(this); AEnv.showCenterScreen(this); } // PerformanceDetail Graph barPanel = null; ConfirmPanel confirmPanel = ConfirmPanel.newWithOK(); /** * Static init */ private void init() { getContentPane().add(barPanel, BorderLayout.CENTER);
getContentPane().add(confirmPanel, BorderLayout.SOUTH); confirmPanel.setActionListener(this); } // init /** * Action Listener * @param e event */ @Override public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_OK)) dispose(); } // actionPerformed } // PerformanceDetail
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\PerformanceDetail.java
1
请完成以下Java代码
public String getInfo() { return "CharacterFilter"; } /** Register things to be filtered. */ public Filter addAttribute(String name,Object attribute) { this.put(name,attribute); return this; } /** Remove things to be filtered. */ public Filter removeAttribute(String name) { try { this.remove(name); } catch ( Exception e ) { } return this; } /** Check to see if something is going to be filtered. */ public boolean hasAttribute(String key) { return(this.containsKey(key)); } /** Perform the filtering operation. */ public String process(String to_process) { if ( to_process == null || to_process.length() == 0 ) return "";
StringBuffer bs = new StringBuffer(to_process.length() + 50); StringCharacterIterator sci = new StringCharacterIterator(to_process); String tmp = null; for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next()) { tmp = String.valueOf(c); if (hasAttribute(tmp)) tmp = (String) this.get(tmp); int ii = c; if (ii > 255) tmp = "&#" + ii + ";"; bs.append(tmp); } return(bs.toString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\CharacterFilter.java
1
请完成以下Java代码
public PublicKeyCredentialRequestOptionsBuilder extensions(AuthenticationExtensionsClientInputs extensions) { this.extensions = extensions; return this; } /** * Allows customizing the {@link PublicKeyCredentialRequestOptionsBuilder} * @param customizer the {@link Consumer} used to customize the builder * @return the {@link PublicKeyCredentialRequestOptionsBuilder} */ public PublicKeyCredentialRequestOptionsBuilder customize( Consumer<PublicKeyCredentialRequestOptionsBuilder> customizer) { customizer.accept(this); return this; }
/** * Builds a new {@link PublicKeyCredentialRequestOptions} * @return a new {@link PublicKeyCredentialRequestOptions} */ public PublicKeyCredentialRequestOptions build() { if (this.challenge == null) { this.challenge = Bytes.random(); } return new PublicKeyCredentialRequestOptions(this.challenge, this.timeout, this.rpId, this.allowCredentials, this.userVerification, this.extensions); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialRequestOptions.java
1
请完成以下Java代码
public class MaterialCockpitRowCache { @NonNull private final ProductRepository productRepository; @NonNull private final WarehouseRepository warehouseRepository; @NonNull private final IUOMDAO uomDAO; private final HashMap<ProductId, Product> productsCache = new HashMap<>(); private final HashMap<UomId, I_C_UOM> uomsCache = new HashMap<>(); public void warmUpProducts(final Set<ProductId> productIds) { final Collection<Product> products = CollectionUtils.getAllOrLoad(productsCache, productIds, this::retrieveProductsByIds); final ImmutableSet<UomId> uomIds = products.stream().map(Product::getUomId).collect(ImmutableSet.toImmutableSet()); warmUpUOMs(uomIds); } public Product getProductById(final ProductId productId) { return productsCache.computeIfAbsent(productId, this::retrieveProductById); } public Product retrieveProductById(@NonNull final ProductId productId) { return productRepository.getById(productId); } public Map<ProductId, Product> retrieveProductsByIds(final Set<ProductId> productIds) { final ImmutableList<Product> products = productRepository.getByIds(productIds); return Maps.uniqueIndex(products, Product::getId); } public I_C_UOM getUomById(final UomId uomId) { return uomsCache.computeIfAbsent(uomId, uomDAO::getById); } public I_C_UOM getUomByProductId(final ProductId productId) { final UomId uomId = getProductById(productId).getUomId(); return getUomById(uomId); }
private void warmUpUOMs(final Collection<UomId> uomIds) { if (uomIds.isEmpty()) { return; } CollectionUtils.getAllOrLoad(uomsCache, uomIds, this::retrieveUOMsByIds); } private Map<UomId, I_C_UOM> retrieveUOMsByIds(final Collection<UomId> uomIds) { final List<I_C_UOM> uoms = uomDAO.getByIds(uomIds); return Maps.uniqueIndex(uoms, uom -> UomId.ofRepoId(uom.getC_UOM_ID())); } public ImmutableSet<WarehouseId> getAllActiveWarehouseIds() { return warehouseRepository.getAllActiveIds(); } public Warehouse getWarehouseById(@NonNull final WarehouseId warehouseId) { return warehouseRepository.getById(warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowCache.java
1
请完成以下Java代码
private List<IConnectionCustomizer> getRegisteredCustomizers() { return new ImmutableList.Builder<IConnectionCustomizer>() .addAll(permanentCustomizers) .addAll(temporaryCustomizers.get()) .build(); } /** * Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish. * So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}. * * @param customizer * @param connection */ private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection)
{ try { if (currentlyInvokedCustomizers.get().add(customizer)) { customizer.customizeConnection(connection); currentlyInvokedCustomizers.get().remove(customizer); } } finally { currentlyInvokedCustomizers.get().remove(customizer); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
1
请完成以下Java代码
public void setTableName (final java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } @Override public java.lang.String getTableName() { return get_ValueAsString(COLUMNNAME_TableName); } @Override public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } /** * TooltipType AD_Reference_ID=541141 * Reference name: TooltipType */ public static final int TOOLTIPTYPE_AD_Reference_ID=541141; /** DescriptionFallbackToTableIdentifier = DTI */ public static final String TOOLTIPTYPE_DescriptionFallbackToTableIdentifier = "DTI"; /** TableIdentifier = T */ public static final String TOOLTIPTYPE_TableIdentifier = "T"; /** Description = D */ public static final String TOOLTIPTYPE_Description = "D"; @Override public void setTooltipType (final java.lang.String TooltipType) { set_Value (COLUMNNAME_TooltipType, TooltipType); } @Override public java.lang.String getTooltipType() { return get_ValueAsString(COLUMNNAME_TooltipType); }
@Override public void setWEBUI_View_PageLength (final int WEBUI_View_PageLength) { set_Value (COLUMNNAME_WEBUI_View_PageLength, WEBUI_View_PageLength); } @Override public int getWEBUI_View_PageLength() { return get_ValueAsInt(COLUMNNAME_WEBUI_View_PageLength); } /** * WhenChildCloningStrategy AD_Reference_ID=541756 * Reference name: AD_Table_CloningStrategy */ public static final int WHENCHILDCLONINGSTRATEGY_AD_Reference_ID=541756; /** Skip = S */ public static final String WHENCHILDCLONINGSTRATEGY_Skip = "S"; /** AllowCloning = A */ public static final String WHENCHILDCLONINGSTRATEGY_AllowCloning = "A"; /** AlwaysInclude = I */ public static final String WHENCHILDCLONINGSTRATEGY_AlwaysInclude = "I"; @Override public void setWhenChildCloningStrategy (final java.lang.String WhenChildCloningStrategy) { set_Value (COLUMNNAME_WhenChildCloningStrategy, WhenChildCloningStrategy); } @Override public java.lang.String getWhenChildCloningStrategy() { return get_ValueAsString(COLUMNNAME_WhenChildCloningStrategy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table.java
1
请完成以下Java代码
private boolean isAtLeastOneTopLevelTUSelected() { if (!isSingleSelectedPickingSlotRow()) { return false; } final PickingSlotRow selectedPickingSlot = getSingleSelectedPickingSlotRow(); return selectedPickingSlot.isTopLevelTU() || (selectedPickingSlot.isPickingSlotRow() && selectedPickingSlot.getIncludedRows().stream().anyMatch(PickingSlotRow::isTopLevelTU)); } private boolean isPackToLuAllowed(final I_M_HU hu) { final I_M_HU_PI_Version mHuPiVersion = hu.getM_HU_PI_Version(); if (mHuPiVersion == null || mHuPiVersion.getHU_UnitType() != null && !mHuPiVersion.getHU_UnitType().equals(X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit)) { return false; } final BPartnerId bPartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu); final I_M_HU_PI_Item actualLUItem = handlingUnitsDAO.retrieveDefaultParentPIItem(mHuPiVersion.getM_HU_PI(), X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit, bPartnerId);
return actualLUItem != null; } @Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutTUsAndAddToNewLUs.java
1
请完成以下Java代码
public boolean isChanged() { return m_changed; } private DataNewCopyMode _dataNewCopyMode = null; /** variable for retaining the old po'ID for copy with details */ private int m_oldPO_id = -1; private void setDataNewCopyMode(final DataNewCopyMode copyMode) { Check.assumeNotNull(copyMode, "copyMode not null"); this._dataNewCopyMode = copyMode; } public void resetDataNewCopyMode() { this._dataNewCopyMode = null; // // Make sure the suggested child tables to be copied list is reset // if (m_gridTab != null) // { // m_gridTab.resetSuggestedCopyWithDetailsList(); // }
} /** * Checks if we are currenty copying the current row <b>with details</b>. * <p> * NOTE: this information will be available even after {@link #dataNew(int, DataNewCopyMode)} until the record is saved or discarded. * * @return true if we are currenty copying the current row <b>with details</b> */ public boolean isCopyWithDetails() { return DataNewCopyMode.isCopyWithDetails(_dataNewCopyMode); } /** * @return true if we are currenty copying the current row (with or without details) */ public boolean isRecordCopyingMode() { return DataNewCopyMode.isCopy(_dataNewCopyMode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTable.java
1
请在Spring Boot框架中完成以下Java代码
public PaymentDirection getPaymentDirection() { return PaymentDirection.ofSOTrx(creditMemoPayableDoc.getSoTrx()); } @Override public CurrencyId getCurrencyId() { return creditMemoPayableDoc.getCurrencyId(); } @Override public LocalDate getDate() { return creditMemoPayableDoc.getDate(); }
@Override public PaymentCurrencyContext getPaymentCurrencyContext() { return PaymentCurrencyContext.builder() .paymentCurrencyId(creditMemoPayableDoc.getCurrencyId()) .currencyConversionTypeId(creditMemoPayableDoc.getCurrencyConversionTypeId()) .build(); } @Override public Money getPaymentDiscountAmt() { return creditMemoPayableDoc.getAmountsToAllocate().getDiscountAmt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\CreditMemoInvoiceAsPaymentDocumentWrapper.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setC_Workplace_ID (final int C_Workplace_ID) { if (C_Workplace_ID < 1) set_Value (COLUMNNAME_C_Workplace_ID, null); else set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID); } @Override public int getC_Workplace_ID() { return get_ValueAsInt(COLUMNNAME_C_Workplace_ID); } @Override public void setM_Picking_Job_Schedule_ID (final int M_Picking_Job_Schedule_ID) { if (M_Picking_Job_Schedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Job_Schedule_ID, M_Picking_Job_Schedule_ID); } @Override public int getM_Picking_Job_Schedule_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Schedule_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID)
{ if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Picking_Job_Schedule.java
1
请完成以下Java代码
public class BaseAppModel implements AppModel { protected String key; protected String name; protected String description; protected String theme; protected String icon; protected String usersAccess; protected String groupsAccess; @Override public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTheme() { return theme;
} public void setTheme(String theme) { this.theme = theme; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getUsersAccess() { return usersAccess; } public void setUsersAccess(String usersAccess) { this.usersAccess = usersAccess; } public String getGroupsAccess() { return groupsAccess; } public void setGroupsAccess(String groupsAccess) { this.groupsAccess = groupsAccess; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\BaseAppModel.java
1
请在Spring Boot框架中完成以下Java代码
public class IndexController { @Resource private CommentService commentService; @Resource private NewsService newsService; /** * 详情页 * * @return */ @GetMapping({"/news/{newsId}"}) public String detail(HttpServletRequest request, @PathVariable("newsId") Long newsId) { News newsDetail = newsService.queryNewsById(newsId); if (newsDetail != null) { request.setAttribute("newsDetail", newsDetail); request.setAttribute("pageName", "详情"); return "index/detail"; } else { return "error/error_404"; } } /** * 评论操作 */ @PostMapping(value = "/news/comment") @ResponseBody public Result comment(HttpServletRequest request, HttpSession session, @RequestParam Long newsId, @RequestParam String verifyCode, @RequestParam String commentator, @RequestParam String commentBody) { if (!StringUtils.hasText(verifyCode)) { return ResultGenerator.genFailResult("验证码不能为空"); } ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode"); if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) { return ResultGenerator.genFailResult("验证码错误"); } String ref = request.getHeader("Referer"); if (!StringUtils.hasText(ref)) {
return ResultGenerator.genFailResult("非法请求"); } if (null == newsId || newsId < 0) { return ResultGenerator.genFailResult("非法请求"); } if (!StringUtils.hasText(commentator)) { return ResultGenerator.genFailResult("请输入称呼"); } if (!StringUtils.hasText(commentBody)) { return ResultGenerator.genFailResult("请输入评论内容"); } if (commentBody.trim().length() > 200) { return ResultGenerator.genFailResult("评论内容过长"); } NewsComment comment = new NewsComment(); comment.setNewsId(newsId); comment.setCommentator(AntiXssUtils.cleanString(commentator)); comment.setCommentBody(AntiXssUtils.cleanString(commentBody)); session.removeAttribute("verifyCode");//留言成功后删除session中的验证码信息 return ResultGenerator.genSuccessResult(commentService.addComment(comment)); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\index\IndexController.java
2
请完成以下Java代码
public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID) { if (ImportedPartientBP_Group_ID < 1) set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null); else set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID); } @Override public int getImportedPartientBP_Group_ID() { return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID); } @Override public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory) { set_Value (COLUMNNAME_StoreDirectory, StoreDirectory); } @Override
public java.lang.String getStoreDirectory() { return get_ValueAsString(COLUMNNAME_StoreDirectory); } @Override public void setVia_EAN (final java.lang.String Via_EAN) { set_Value (COLUMNNAME_Via_EAN, Via_EAN); } @Override public java.lang.String getVia_EAN() { return get_ValueAsString(COLUMNNAME_Via_EAN); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java
1
请完成以下Java代码
public String toStringX() { StringBuffer sb = new StringBuffer("MLocation=["); sb.append(get_ID()) .append(",C_Country_ID=").append(getC_Country_ID()) .append(",C_Region_ID=").append(getC_Region_ID()) .append(",Postal=").append(getPostal()) .append ("]"); return sb.toString(); } // toStringX /** * Before Save * @param newRecord new * @return true */ @Override protected boolean beforeSave (boolean newRecord) { if (getAD_Org_ID() != 0) setAD_Org_ID(0); // Region Check if (getC_Region_ID() != 0) { if (m_c == null || m_c.getC_Country_ID() != getC_Country_ID()) getCountry(); if (!m_c.isHasRegion()) setC_Region_ID(0); } if (getC_City_ID() <= 0 && getCity() != null && getCity().length() > 0) { int city_id = DB.getSQLValue( get_TrxName(), "SELECT C_City_ID FROM C_City WHERE C_Country_ID=? AND COALESCE(C_Region_ID,0)=? AND Name=?", new Object[] {getC_Country_ID(), getC_Region_ID(), getCity()}); if (city_id > 0) setC_City_ID(city_id); } //check city if (m_c != null && !m_c.isAllowCitiesOutOfList() && getC_City_ID()<=0) { throw new AdempiereException("@CityNotFound@"); } return true; } // beforeSave /** * After Save * @param newRecord new * @param success success * @return success */ @Override
protected boolean afterSave (boolean newRecord, boolean success) { // Value/Name change in Account if (!newRecord && ("Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.LocationFrom.getCode())) || "Y".equals(Env.getContext(getCtx(), Env.CTXNAME_AcctSchemaElementPrefix + AcctSchemaElementType.LocationTo.getCode()))) && (is_ValueChanged("Postal") || is_ValueChanged("City")) ) MAccount.updateValueDescription(getCtx(), "(C_LocFrom_ID=" + getC_Location_ID() + " OR C_LocTo_ID=" + getC_Location_ID() + ")", get_TrxName()); return success; } // afterSave @Override public void setC_City_ID(int C_City_ID) { if (C_City_ID <= 0) set_Value(COLUMNNAME_C_City_ID, null); else super.setC_City_ID(C_City_ID); } } // MLocation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocation.java
1
请完成以下Java代码
public String getHost() { return this.host; } @Override public void setHost(String host) { this.host = host; } @Override public boolean isRememberMe() { return this.rememberMe; } @Override public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe;
} public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public void clear() { super.clear(); this.accessToken = null; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\credentials\ThirdPartySupportedToken.java
1
请在Spring Boot框架中完成以下Java代码
BeanDefinition getSaml2WebSsoAuthenticationRequestFilter() { return this.saml2WebSsoAuthenticationRequestFilter; } BeanDefinition getSaml2AuthenticationUrlToProviderName() { return this.saml2AuthenticationUrlToProviderName; } /** * Wrapper bean class to provide configuration from applicationContext */ public static class Saml2LoginBeanConfig implements ApplicationContextAware { private ApplicationContext context; @SuppressWarnings({ "unchecked", "unused" }) Map<String, String> getAuthenticationUrlToProviderName() { Iterable<RelyingPartyRegistration> relyingPartyRegistrations = null; RelyingPartyRegistrationRepository relyingPartyRegistrationRepository = this.context .getBean(RelyingPartyRegistrationRepository.class); ResolvableType type = ResolvableType.forInstance(relyingPartyRegistrationRepository).as(Iterable.class); if (type != ResolvableType.NONE
&& RelyingPartyRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) { relyingPartyRegistrations = (Iterable<RelyingPartyRegistration>) relyingPartyRegistrationRepository; } if (relyingPartyRegistrations == null) { return Collections.emptyMap(); } String authenticationRequestProcessingUrl = DEFAULT_AUTHENTICATION_REQUEST_PROCESSING_URL; Map<String, String> saml2AuthenticationUrlToProviderName = new HashMap<>(); relyingPartyRegistrations.forEach((registration) -> saml2AuthenticationUrlToProviderName.put( authenticationRequestProcessingUrl.replace("{registrationId}", registration.getRegistrationId()), registration.getRegistrationId())); return saml2AuthenticationUrlToProviderName; } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LoginBeanDefinitionParser.java
2
请完成以下Java代码
public abstract class RabbitMQReceiveFromEndpointTemplate { private final Logger logger = LogManager.getLogger(getClass()); public static final String HEADER_SenderId = "metasfresh-events.SenderId"; public static final String HEADER_TopicName = "metasfresh-events.TopicName"; public static final String HEADER_TopicType = "metasfresh-events.TopicType"; @NonNull private final String senderId = EventBusConfig.getSenderId(); @NonNull private final IEventBusFactory eventBusFactory; @NonNull private final EventBusMonitoringService eventBusMonitoringService; protected final void onRemoteEvent( final Event event, final String senderId, final String topicName, final Type topicType) { final Topic topic = Topic.of(topicName, topicType); if (topic.getType() != topicType) { logger.debug("onEvent - different local topicType for topicName:[{}], remote type:[{}] local type=[{}]; -> ignoring event", topicName, topicType, topic.getType()); return; } final IEventBus localEventBus = eventBusFactory.getEventBus(topic); if (Type.LOCAL == topic.getType() && !Objects.equals(getSenderId(), senderId)) { logger.debug("onEvent - type LOCAL but event's senderId={} is not equal to the *local* senderId={}; -> ignoring event", senderId, getSenderId()); return; } final boolean monitorIncomingEvents = eventBusMonitoringService.isMonitorIncomingEvents(); final boolean localEventBusAsync = localEventBus.isAsync(); final Topic localEventBusTopic = localEventBus.getTopic(); try { if (monitorIncomingEvents && !localEventBusAsync) { logger.debug("onEvent - localEventBus is not async and isMonitorIncomingEvents=true; -> monitoring event processing; localEventBus={}", localEventBus); eventBusMonitoringService.extractInfosAndMonitor(event, localEventBusTopic, () -> onRemoteEvent0(localEventBus, event, localEventBusTopic.getName())); } else { logger.debug("onEvent - localEventBus.isAsync={} and isMonitorIncomingEvents={}; -> cannot monitor event processing; localEventBus={}", localEventBusAsync, monitorIncomingEvents, localEventBus); onRemoteEvent0(localEventBus, event, localEventBusTopic.getName());
} } catch (final Exception ex) { logger.warn("onEvent - Failed forwarding event to topic {}: {}", localEventBusTopic.getName(), event, ex); } } private void onRemoteEvent0( @NonNull final IEventBus localEventBus, @NonNull final Event event, @NonNull final String topicName) { localEventBus.processEvent(event); logger.debug("Received and processed event in {}ms, topic={}: {}", computeElapsedDuration(event), topicName, event); } private static long computeElapsedDuration(@NonNull final Event event) { final Instant eventTime = event.getWhen(); if (eventTime == null) { return -1; } else { return System.currentTimeMillis() - eventTime.toEpochMilli(); } } @NonNull private String getSenderId() {return senderId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQReceiveFromEndpointTemplate.java
1