instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Issue Recommendation. @param R_IssueRecommendation_ID Recommendations how to fix an Issue */ public void setR_IssueRecommendation_ID (int R_IssueRecommendation_ID) {
if (R_IssueRecommendation_ID < 1) set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, null); else set_ValueNoCheck (COLUMNNAME_R_IssueRecommendation_ID, Integer.valueOf(R_IssueRecommendation_ID)); } /** Get Issue Recommendation. @return Recommendations how to fix an Issue */ public int getR_IssueRecommendation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueRecommendation_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueRecommendation.java
1
请完成以下Java代码
public class SessionEvent { public enum SessionEventType { ESTABLISHED, CLOSED, ERROR }; @Getter private final SessionEventType eventType; @Getter private final Optional<Throwable> error; private SessionEvent(SessionEventType eventType, Throwable error) { super(); this.eventType = eventType; this.error = Optional.ofNullable(error);
} public static SessionEvent onEstablished() { return new SessionEvent(SessionEventType.ESTABLISHED, null); } public static SessionEvent onClosed() { return new SessionEvent(SessionEventType.CLOSED, null); } public static SessionEvent onError(Throwable t) { return new SessionEvent(SessionEventType.ERROR, t); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\SessionEvent.java
1
请完成以下Java代码
public void setR_Status_ID (int R_Status_ID) { if (R_Status_ID < 1) set_Value (COLUMNNAME_R_Status_ID, null); else set_Value (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID)); } /** Get Status. @return Request Status */ @Override public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Anfrageart. @param RequestType Anfrageart */ @Override public void setRequestType (java.lang.String RequestType) { set_Value (COLUMNNAME_RequestType, RequestType); } /** Get Anfrageart. @return Anfrageart */ @Override public java.lang.String getRequestType () { return (java.lang.String)get_Value(COLUMNNAME_RequestType); } /** Set Ergebnis. @param Result Result of the action taken */ @Override public void setResult (java.lang.String Result) { set_Value (COLUMNNAME_Result, Result); } /** Get Ergebnis. @return Result of the action taken */ @Override public java.lang.String getResult () { return (java.lang.String)get_Value(COLUMNNAME_Result); } /** 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); } /** Set Summary. @param Summary
Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ @Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java
1
请完成以下Java代码
public Object eval(Bindings bindings, ELContext context) { return invoke(bindings, context, null, null, null); } public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues) { Object base = property.getPrefix().eval(bindings, context); if (base == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", property.getPrefix())); } Object method = property.getProperty(bindings, context); if (method == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base)); } String name = bindings.convert(method, String.class); paramValues = params.eval(bindings, context); context.setPropertyResolved(false); Object result = context.getELResolver().invoke(context, base, name, paramTypes, paramValues); if (!context.isPropertyResolved()) { throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, base.getClass())); } // if (returnType != null && !returnType.isInstance(result)) { // should we check returnType for method invocations? // throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, base.getClass())); // }
return result; } public int getCardinality() { return 2; } public Node getChild(int i) { return i == 0 ? property : i == 1 ? params : null; } @Override public String toString() { return "<method>"; } }
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstMethod.java
1
请完成以下Java代码
public void setOwner(String owner) { this.owner = owner; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected FilterQuery createNewQuery(ProcessEngine engine) { return engine.getFilterService().createFilterQuery(); } protected void applyFilters(FilterQuery query) { if (filterId != null) { query.filterId(filterId); } if (resourceType != null) { query.filterResourceType(resourceType); } if (name != null) { query.filterName(name); } if (nameLike != null) { query.filterNameLike(nameLike);
} if (owner != null) { query.filterOwner(owner); } } protected void applySortBy(FilterQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByFilterId(); } else if (sortBy.equals(SORT_BY_RESOURCE_TYPE_VALUE)) { query.orderByFilterResourceType(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByFilterName(); } else if (sortBy.equals(SORT_BY_OWNER_VALUE)) { query.orderByFilterOwner(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\FilterQueryDto.java
1
请完成以下Java代码
public DeploymentStatisticsQuery includeFailedJobs() { includeFailedJobs = true; return this; } public DeploymentStatisticsQuery includeIncidents() { includeIncidents = true; return this; } public DeploymentStatisticsQuery includeIncidentsForType(String incidentType) { this.includeIncidentsForType = incidentType; return this; } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsCountGroupedByDeployment(this); } @Override public List<DeploymentStatistics> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getStatisticsManager() .getStatisticsGroupedByDeployment(this, page); } public boolean isFailedJobsToInclude() { return includeFailedJobs; } public boolean isIncidentsToInclude() { return includeIncidents || includeIncidentsForType != null; } protected void checkQueryOk() { super.checkQueryOk(); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } } // getter/setter for authorization check public List<PermissionCheck> getProcessInstancePermissionChecks() { return processInstancePermissionChecks; } public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) { this.processInstancePermissionChecks = processInstancePermissionChecks; } public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) { processInstancePermissionChecks.addAll(permissionChecks);
} public List<PermissionCheck> getJobPermissionChecks() { return jobPermissionChecks; } public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) { this.jobPermissionChecks = jobPermissionChecks; } public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) { jobPermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getIncidentPermissionChecks() { return incidentPermissionChecks; } public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) { this.incidentPermissionChecks = incidentPermissionChecks; } public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) { incidentPermissionChecks.addAll(permissionChecks); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DeploymentStatisticsQueryImpl.java
1
请完成以下Spring Boot application配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/sang?useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=sang logging.level.org.springframework.security=info spring.thymeleaf.
cache=false spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=true
repos\JavaEETest-master\Test26-Security\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } @ConditionalOnResource(resources = "classpath:mysql.properties") @Conditional(HibernateCondition.class) final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false"); return hibernateProperties; }
static class HibernateCondition extends SpringBootCondition { private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" }; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate"); return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny() .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES)))); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-autoconfiguration\src\main\java\com\baeldung\autoconfiguration\MySQLAutoconfiguration.java
2
请完成以下Java代码
public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public boolean isNew() { return isNew; } public void setNew(boolean isNew) { this.isNew = isNew; } public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; }
public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getProjectReleaseVersion() { return projectReleaseVersion; } public void setProjectReleaseVersion(String projectReleaseVersion) { this.projectReleaseVersion = projectReleaseVersion; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getMobileNo() { return mobileNo; } /** 手机号码 **/ public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } /** 银行名称 **/ public String getBankName() { return bankName; } /** 银行名称 **/ public void setBankName(String bankName) { this.bankName = bankName; } /** 用户编号 **/ public String getUserNo() { return userNo; }
/** 用户编号 **/ public void setUserNo(String userNo) { this.userNo = userNo; } /** 是否默认 **/ public String getIsDefault() { return isDefault; } /** 是否默认 **/ public void setIsDefault(String isDefault) { this.isDefault = isDefault; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java
2
请在Spring Boot框架中完成以下Java代码
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) { // 处理缓存删除错误 log.error("Cache Evict Error: {}",exception.getMessage()); } @Override public void handleCacheClearError(RuntimeException exception, Cache cache) { // 处理缓存清除错误 log.error("Cache Clear Error: {}",exception.getMessage()); } }; } /** * Value 序列化 * * @param <T> * @author / */ static class FastJsonRedisSerializer<T> implements RedisSerializer<T> { private final Class<T> clazz; FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; }
@Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } String str = new String(bytes, StandardCharsets.UTF_8); return JSON.parseObject(str, clazz); } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedisConfiguration.java
2
请完成以下Java代码
public POSPaymentProcessorType getType() {return POSPaymentProcessorType.SumUp;} @Override public POSPaymentProcessResponse process(@NonNull final POSPaymentProcessRequest request) { try { final SumUpConfig sumUpConfig = getSumUpConfig(request.getPaymentProcessorConfig()); final SumUpTransaction sumUpTrx = sumUpService.cardReaderCheckout( SumUpCardReaderCheckoutRequest.builder() .configId(sumUpConfig.getId()) .cardReaderId(sumUpConfig.getDefaultCardReaderExternalIdNotNull()) .amount(request.getAmount()) .callbackUrl(getCallbackUrl()) .clientAndOrgId(request.getClientAndOrgId()) .posRef(SumUpUtils.toPOSRef(request.getPosOrderAndPaymentId())) .build() ); return SumUpUtils.extractProcessResponse(sumUpTrx); } catch (final Exception ex) { final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex); return POSPaymentProcessResponse.error( request.getPaymentProcessorConfig(), AdempiereException.extractMessage(metasfreshException), errorManager.createIssue(metasfreshException) ); } } private SumUpConfig getSumUpConfig(@NonNull final POSTerminalPaymentProcessorConfig paymentProcessorConfig)
{ Check.assumeEquals(paymentProcessorConfig.getType(), POSPaymentProcessorType.SumUp, "payment processor type is SumUp: {}", paymentProcessorConfig); final SumUpConfigId sumUpConfigId = Check.assumeNotNull(paymentProcessorConfig.getSumUpConfigId(), "sumUpConfigId is set for {}", paymentProcessorConfig); return sumUpService.getConfig(sumUpConfigId); } @Nullable private String getCallbackUrl() { final String appApiUrl = webuiURLs.getAppApiUrl(); if (appApiUrl == null) { return null; } return appApiUrl + SumUp.ENDPOINT_PaymentCheckoutCallback; } @Override public POSPaymentProcessResponse refund(@NonNull final POSRefundRequest request) { final SumUpPOSRef posRef = SumUpUtils.toPOSRef(request.getPosOrderAndPaymentId()); final SumUpTransaction trx = sumUpService.refundTransaction(posRef); return SumUpUtils.extractProcessResponse(trx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpPaymentProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public static class EventRegistryRabbitConfiguration { @Bean("rabbitChannelDefinitionProcessor") @ConditionalOnMissingBean(name = "rabbitChannelDefinitionProcessor") public RabbitChannelDefinitionProcessor rabbitChannelDefinitionProcessor(RabbitListenerEndpointRegistry endpointRegistry, RabbitOperations rabbitOperations, ObjectMapper objectMapper) { RabbitChannelDefinitionProcessor rabbitChannelDefinitionProcessor = new RabbitChannelDefinitionProcessor(objectMapper); rabbitChannelDefinitionProcessor.setEndpointRegistry(endpointRegistry); rabbitChannelDefinitionProcessor.setRabbitOperations(rabbitOperations); return rabbitChannelDefinitionProcessor; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(KafkaOperations.class) public static class EventRegistryKafkaConfiguration { @Bean("kafkaChannelDefinitionProcessor") @ConditionalOnMissingBean(name = "kafkaChannelDefinitionProcessor") public KafkaChannelDefinitionProcessor kafkaChannelDefinitionProcessor(KafkaListenerEndpointRegistry endpointRegistry, KafkaOperations<Object, Object> kafkaOperations, ObjectMapper objectMapper, ObjectProvider<KafkaConsumerBackoffManager> kafkaConsumerBackoffManager, ObjectProvider<KafkaAdminOperations> kafkaAdminOperations) {
KafkaChannelDefinitionProcessor kafkaChannelDefinitionProcessor = new KafkaChannelDefinitionProcessor(objectMapper); kafkaChannelDefinitionProcessor.setEndpointRegistry(endpointRegistry); kafkaChannelDefinitionProcessor.setKafkaOperations(kafkaOperations); kafkaChannelDefinitionProcessor.setKafkaConsumerBackoffManager(kafkaConsumerBackoffManager.getIfAvailable()); kafkaChannelDefinitionProcessor.setKafkaAdminOperations(kafkaAdminOperations.getIfAvailable()); return kafkaChannelDefinitionProcessor; } @Bean("kafkaEventRegistryEngineConfigurer") @ConditionalOnMissingBean(name = "kafkaEventRegistryEngineConfigurer") public EngineConfigurationConfigurer<SpringEventRegistryEngineConfiguration> kafkaEventRegistryEngineConfigurer() { return engineConfiguration -> { engineConfiguration.registerInboundEventPayloadExtractor("kafka", new KafkaConsumerRecordInformationPayloadExtractor<>()); }; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\EventRegistryAutoConfiguration.java
2
请完成以下Java代码
public String getElementText() { return elementText; } public void setElementText(String elementText) { this.elementText = elementText; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNamespacePrefix() { return namespacePrefix; } public void setNamespacePrefix(String namespacePrefix) { this.namespacePrefix = namespacePrefix; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Map<String, List<DmnExtensionElement>> getChildElements() { return childElements; } public void addChildElement(DmnExtensionElement childElement) { if (childElement != null && childElement.getName() != null && !childElement.getName().trim().isEmpty()) { List<DmnExtensionElement> elementList = null; if (!this.childElements.containsKey(childElement.getName())) { elementList = new ArrayList<>(); this.childElements.put(childElement.getName(), elementList); } this.childElements.get(childElement.getName()).add(childElement); } } public void setChildElements(Map<String, List<DmnExtensionElement>> childElements) { this.childElements = childElements;
} @Override public DmnExtensionElement clone() { DmnExtensionElement clone = new DmnExtensionElement(); clone.setValues(this); return clone; } public void setValues(DmnExtensionElement otherElement) { setName(otherElement.getName()); setNamespacePrefix(otherElement.getNamespacePrefix()); setNamespace(otherElement.getNamespace()); setElementText(otherElement.getElementText()); setAttributes(otherElement.getAttributes()); childElements = new LinkedHashMap<>(); if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) { for (String key : otherElement.getChildElements().keySet()) { List<DmnExtensionElement> otherElementList = otherElement.getChildElements().get(key); if (otherElementList != null && !otherElementList.isEmpty()) { List<DmnExtensionElement> elementList = new ArrayList<>(); for (DmnExtensionElement dmnExtensionElement : otherElementList) { elementList.add(dmnExtensionElement.clone()); } childElements.put(key, elementList); } } } } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionElement.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String isbn; private YearMonth releaseDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public YearMonth getReleaseDate() { return releaseDate; } public void setReleaseDate(YearMonth releaseDate) { this.releaseDate = releaseDate; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", releaseDate=" + releaseDate + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootYearMonth\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
private static void unregisterMBean(Class<?> interfaceClass, IMBeanAwareService service) { final String jmxName = createJMXName(interfaceClass, service); final ObjectName jmxObjectName; try { jmxObjectName = new ObjectName(jmxName); } catch (Exception e) { logger.warn("Cannot create JMX Name: " + jmxName + ". Skip unregistering MBean.", e); return; } final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.unregisterMBean(jmxObjectName); } catch (MBeanRegistrationException e) { logger.warn("Cannot unregister MBean Name: " + jmxName + ".", e); } catch (InstanceNotFoundException e) { // nothing } } public static long getLoadedServicesCount() { return services.size();
} private static <T extends IService> Constructor<T> getDefaultConstructor(final Class<T> serviceInstanceClass) { @SuppressWarnings({ "rawtypes", "unchecked" }) final Set<Constructor> defaultConstructors = ReflectionUtils.getConstructors(serviceInstanceClass, ReflectionUtils.withParametersCount(0)); final boolean hasNoDefaultConstructor = defaultConstructors.isEmpty(); Check.errorIf(hasNoDefaultConstructor, "Param 'serviceInstanceClass' = {} has no default constructor", serviceInstanceClass); @SuppressWarnings("unchecked") final Constructor<T> defaultConstructor = defaultConstructors.iterator().next(); return defaultConstructor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Services.java
1
请在Spring Boot框架中完成以下Java代码
protected void handleNotification(UUID id, TbProtoQueueMsg<ToCalculatedFieldNotificationMsg> msg, TbCallback callback) { ToCalculatedFieldNotificationMsg toCfNotification = msg.getValue(); if (toCfNotification.hasLinkedTelemetryMsg()) { forwardToActorSystem(toCfNotification.getLinkedTelemetryMsg(), callback); } } @EventListener public void handleComponentLifecycleEvent(ComponentLifecycleMsg event) { if (event.getEntityId().getEntityType() == EntityType.TENANT) { if (event.getEvent() == ComponentLifecycleEvent.DELETED) { Set<TopicPartitionInfo> partitions = stateService.getPartitions(); if (CollectionUtils.isEmpty(partitions)) { return; } stateService.delete(partitions.stream() .filter(tpi -> tpi.getTenantId().isPresent() && tpi.getTenantId().get().equals(event.getTenantId())) .collect(Collectors.toSet())); } } } private void forwardToActorSystem(CalculatedFieldTelemetryMsgProto msg, TbCallback callback) {
var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldTelemetryMsg(tenantId, entityId, msg, callback)); } private void forwardToActorSystem(CalculatedFieldLinkedTelemetryMsgProto linkedMsg, TbCallback callback) { var msg = linkedMsg.getMsg(); var tenantId = toTenantId(msg.getTenantIdMSB(), msg.getTenantIdLSB()); var entityId = EntityIdFactory.getByTypeAndUuid(msg.getEntityType(), new UUID(msg.getEntityIdMSB(), msg.getEntityIdLSB())); actorContext.tell(new CalculatedFieldLinkedTelemetryMsg(tenantId, entityId, linkedMsg, callback)); } private TenantId toTenantId(long tenantIdMSB, long tenantIdLSB) { return TenantId.fromUUID(new UUID(tenantIdMSB, tenantIdLSB)); } @Override protected void stopConsumers() { super.stopConsumers(); stateService.stop(); // eventConsumer will be stopped by stateService } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\DefaultTbCalculatedFieldConsumerService.java
2
请完成以下Java代码
public String getRideId() { return rideId; } public void setRideId(String rideId) { this.rideId = rideId; } public RideRequest getRideRequest() { return rideRequest; } public void setRideRequest(RideRequest rideRequest) { this.rideRequest = rideRequest; } public String getDriverId() { return driverId; }
public void setDriverId(String driverId) { this.driverId = driverId; } public String getWorkflowInstanceId() { return workflowInstanceId; } public void setWorkflowInstanceId(String workflowInstanceId) { this.workflowInstanceId = workflowInstanceId; } @Override public String toString() { return "RideWorkflowRequest{" + "rideId='" + rideId + '\'' + ", rideRequest=" + rideRequest + ", driverId='" + driverId + '\'' + ", workflowInstanceId='" + workflowInstanceId + '\'' + '}'; } }
repos\tutorials-master\messaging-modules\dapr\dapr-workflows\src\main\java\com\baeldung\dapr\workflow\model\RideWorkflowRequest.java
1
请在Spring Boot框架中完成以下Java代码
public Job skipExceptionJob() { return jobBuilderFactory.get("skipExceptionJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<String, String>chunk(2) .reader(listItemReader()) .processor(myProcessor()) .writer(list -> list.forEach(System.out::println)) .faultTolerant() // 配置错误容忍 .skip(MyJobExecutionException.class) // 配置跳过的异常类型 .skipLimit(1) // 最多跳过1次,1次过后还是异常的话,则任务会结束, // 异常的次数为reader,processor和writer中的总数,这里仅在processor里演示异常跳过 .listener(mySkipListener) .build(); }
private ListItemReader<String> listItemReader() { ArrayList<String> datas = new ArrayList<>(); IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i))); return new ListItemReader<>(datas); } private ItemProcessor<String, String> myProcessor() { return item -> { System.out.println("当前处理的数据:" + item); if ("2".equals(item)) { throw new MyJobExecutionException("任务处理出错"); } else { return item; } }; } }
repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\SkipExceptionJobDemo.java
2
请完成以下Java代码
public TotalsPerBankTransactionCode3 createTotalsPerBankTransactionCode3() { return new TotalsPerBankTransactionCode3(); } /** * Create an instance of {@link TrackData1 } * */ public TrackData1 createTrackData1() { return new TrackData1(); } /** * Create an instance of {@link TransactionAgents3 } * */ public TransactionAgents3 createTransactionAgents3() { return new TransactionAgents3(); } /** * Create an instance of {@link TransactionDates2 } * */ public TransactionDates2 createTransactionDates2() { return new TransactionDates2(); } /** * Create an instance of {@link TransactionIdentifier1 } * */ public TransactionIdentifier1 createTransactionIdentifier1() { return new TransactionIdentifier1(); } /** * Create an instance of {@link TransactionInterest3 } * */ public TransactionInterest3 createTransactionInterest3() { return new TransactionInterest3(); } /** * Create an instance of {@link TransactionParties3 } * */ public TransactionParties3 createTransactionParties3() { return new TransactionParties3(); } /** * Create an instance of {@link TransactionPrice3Choice } * */ public TransactionPrice3Choice createTransactionPrice3Choice() { return new TransactionPrice3Choice(); } /** * Create an instance of {@link TransactionQuantities2Choice } * */ public TransactionQuantities2Choice createTransactionQuantities2Choice() {
return new TransactionQuantities2Choice(); } /** * Create an instance of {@link TransactionReferences3 } * */ public TransactionReferences3 createTransactionReferences3() { return new TransactionReferences3(); } /** * Create an instance of {@link YieldedOrValueType1Choice } * */ public YieldedOrValueType1Choice createYieldedOrValueType1Choice() { return new YieldedOrValueType1Choice(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:camt.053.001.04", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\ObjectFactory.java
1
请完成以下Java代码
private void setDefault_Locator_ID() { // teo_sarca, FR [ 1661546 ] Mandatory locator fields should use defaults if (!isMandatory() || m_mLocator == null) { return; } final WarehouseId warehouseId = getOnly_Warehouse_ID(); if (warehouseId == null) { return; } final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId); if (locatorId == null) { return; } setValue(locatorId.getRepoId()); }
// metas @Override public boolean isAutoCommit() { return true; } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VLocator /*****************************************************************************/
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocator.java
1
请完成以下Java代码
public void setEventType (final java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } @Override public java.lang.String getEventType() { return get_ValueAsString(COLUMNNAME_EventType); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessingTag (final @Nullable java.lang.String ProcessingTag) { set_Value (COLUMNNAME_ProcessingTag, ProcessingTag); }
@Override public java.lang.String getProcessingTag() { return get_ValueAsString(COLUMNNAME_ProcessingTag); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java
1
请完成以下Java代码
private static ImmutableSet<Label> getLabels() { final String labelsStr = getMandatoryProperty("labels", WorkspaceMigrateConfig.PROP_LABELS_DEFAULT); return Label.ofCommaSeparatedString(labelsStr); } /** * Note that the property may contain a "." (dot) or a "_" (unterscore) to be found! */ private static String getMandatoryProperty(final String name, final String defaultValue) { final String systemPropertyValue = System.getProperty(name); if (isNotBlank(systemPropertyValue)) { return systemPropertyValue; } final String envVarValue = System.getenv(name); if (isNotBlank(envVarValue)) { return envVarValue; } final String envVarValueWithUnderscore = System.getenv(name.replace('.', '_')); if (isNotBlank(envVarValueWithUnderscore)) { return envVarValueWithUnderscore; } if (isNotBlank(defaultValue)) { logger.info("Considering default config: {}={}. To override it start JVM with '-D{}=...' OR set environment-variable '{}=...'.", name, defaultValue, name, name); return defaultValue; } throw new RuntimeException("Property '" + name + "' was not set. "
+ "\n Please start JVM with '-D" + name + "=...'" + " OR set environment-variable '" + name + "=...'."); } private static boolean getBooleanProperty(final String name, final boolean defaultValue) { final String systemPropertyValue = System.getProperty(name); if (isNotBlank(systemPropertyValue)) { return Boolean.parseBoolean(systemPropertyValue.trim()); } final String evnVarValue = System.getenv(name); if (isNotBlank(evnVarValue)) { return Boolean.parseBoolean(evnVarValue); } final String envVarValueWithUnderscore = System.getenv(name.replace('.', '_')); if (isNotBlank(envVarValueWithUnderscore)) { return Boolean.parseBoolean(envVarValueWithUnderscore); } logger.info("Considering default config: {}={}. To override it start JVM with '-D{}=...' OR set environment-variable '{}=...'.", name, defaultValue, name, name); return defaultValue; } private static boolean isNotBlank(@Nullable final String str) { return str != null && !str.trim().isEmpty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\Main.java
1
请完成以下Java代码
public Long getAvgRt() { return avgRt; } public void setAvgRt(Long avgRt) { this.avgRt = avgRt; } public Long getMaxThread() { return maxThread; } public void setMaxThread(Long maxThread) { this.maxThread = maxThread; } public Double getQps() { return qps; } public void setQps(Double qps) { this.qps = qps; } public Double getHighestCpuUsage() { return highestCpuUsage; } public void setHighestCpuUsage(Double highestCpuUsage) { this.highestCpuUsage = highestCpuUsage; } @Override public Date getGmtCreate() { return gmtCreate; }
public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public SystemRule toRule() { SystemRule rule = new SystemRule(); rule.setHighestSystemLoad(highestSystemLoad); rule.setAvgRt(avgRt); rule.setMaxThread(maxThread); rule.setQps(qps); rule.setHighestCpuUsage(highestCpuUsage); return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\SystemRuleEntity.java
1
请完成以下Java代码
public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link Long } * */ public Long getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link Long } * */ public void setVersion(Long value) { this.version = value; } /**
* Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public long getId() { if (id == null) { return 0L; } else { return id; } } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DependsOnType.java
1
请完成以下Java代码
public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow) { this.allowTrxAfterThreadEnd = allow; return this; } @Override public int getMaxTrx() { return maxTrx; } @Override public ITrxConstraints setMaxSavepoints(int maxSavepoints) { this.maxSavepoints = maxSavepoints; return this; } @Override public int getMaxSavepoints() { return maxSavepoints; } @Override public ITrxConstraints setActive(boolean active) { this.active = active; return this; } @Override public boolean isActive() { return active; } @Override public boolean isOnlyAllowedTrxNamePrefixes() { return onlyAllowedTrxNamePrefixes; } @Override public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes) { this.onlyAllowedTrxNamePrefixes = onlyAllowedTrxNamePrefixes; return this; } @Override public ITrxConstraints addAllowedTrxNamePrefix(final String trxNamePrefix) { allowedTrxNamePrefixes.add(trxNamePrefix); return this; } @Override
public ITrxConstraints removeAllowedTrxNamePrefix(final String trxNamePrefix) { allowedTrxNamePrefixes.remove(trxNamePrefix); return this; } @Override public Set<String> getAllowedTrxNamePrefixes() { return allowedTrxNamePrefixesRO; } @Override public boolean isAllowTrxAfterThreadEnd() { return allowTrxAfterThreadEnd; } @Override public void reset() { setActive(DEFAULT_ACTIVE); setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END); setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS); setMaxTrx(DEFAULT_MAX_TRX); setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY); setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES); allowedTrxNamePrefixes.clear(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TrxConstraints["); sb.append("active=" + this.active); sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes()); sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd()); sb.append(", maxSavepoints=" + getMaxSavepoints()); sb.append(", maxTrx=" + getMaxTrx()); sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes()); sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly()); sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs()); sb.append("]"); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java
1
请完成以下Java代码
public static String yyyyMMddForMat(Date date) { return yyyyMMdd.format(date); } public static int getRanDom() { return new Random().nextInt(); } public static int round(int num) { return Math.round(num); } public static void printMap(Map<?, ?> map) { if (map != null && map.size() > 0) { for (Object key : map.keySet()) { System.out.println("key--->" + key); System.out.println("value--->" + map.get(key));
} } } public static String trimString(String str) { str.trim(); return str; } @Override public boolean equals(Object obj) { return super.equals(obj); } }
repos\springboot-demo-master\findbug\src\main\java\com\et\findbug\FindBugsDemo.java
1
请完成以下Java代码
private List<JsonWorkPackageStatus> retrieveWorkPackageInfo(final PurchaseCandidateId purchaseCandidateId) { final List<I_C_Queue_WorkPackage> workPackageRecords = queueDAO.retrieveUnprocessedWorkPackagesByEnqueuedRecord( C_PurchaseCandidates_GeneratePurchaseOrders.class, TableRecordReference.of(I_C_PurchaseCandidate.Table_Name, purchaseCandidateId)); if (workPackageRecords.isEmpty()) { return ImmutableList.of(); } return workPackageRecords.stream() .map(PurchaseCandidatesStatusService::toJsonForWorkPackage) .collect(ImmutableList.toImmutableList()); } private static JsonWorkPackageStatus toJsonForWorkPackage(final I_C_Queue_WorkPackage workPackageRecord) { return JsonWorkPackageStatus.builder() .error(workPackageRecord.getErrorMsg()) .enqueued(TimeUtil.asInstant(workPackageRecord.getCreated())) .readyForProcessing(workPackageRecord.isReadyForProcessing()) .metasfreshId(JsonMetasfreshId.of(workPackageRecord.getC_Queue_WorkPackage_ID())) .build(); } private List<JsonPurchaseOrder> retrievePurchaseOrderInfo(final PurchaseCandidateId candidate) { final Collection<OrderId> orderIds = purchaseCandidateRepo.getOrderIdsForPurchaseCandidates(candidate); return Services.get(IOrderDAO.class).getByIds(orderIds) .stream() .map(this::toJsonOrder) .collect(ImmutableList.toImmutableList()); } @NonNull private JsonPurchaseCandidate.JsonPurchaseCandidateBuilder preparePurchaseCandidateStatus(@NonNull final PurchaseCandidate candidate) { return JsonPurchaseCandidate.builder() .externalSystemCode(poJsonConverters.getExternalSystemTypeById(candidate)) .externalHeaderId(JsonExternalIds.ofOrNull(candidate.getExternalHeaderId())) .externalLineId(JsonExternalIds.ofOrNull(candidate.getExternalLineId())) .purchaseDateOrdered(candidate.getPurchaseDateOrdered()) .purchaseDatePromised(candidate.getPurchaseDatePromised()) .metasfreshId(JsonMetasfreshId.of(candidate.getId().getRepoId())) .externalPurchaseOrderUrl(candidate.getExternalPurchaseOrderUrl())
.processed(candidate.isProcessed()); } private JsonPurchaseOrder toJsonOrder(@NonNull final I_C_Order order) { final boolean hasArchive = hasArchive(order); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); return JsonPurchaseOrder.builder() .dateOrdered(TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone)) .datePromised(TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone)) .docStatus(order.getDocStatus()) .documentNo(order.getDocumentNo()) .metasfreshId(JsonMetasfreshId.of(order.getC_Order_ID())) .pdfAvailable(hasArchive) .build(); } private boolean hasArchive(final I_C_Order order) { return archiveBL.getLastArchive(TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID())).isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidatesStatusService.java
1
请在Spring Boot框架中完成以下Java代码
GroovyMarkupConfigurer groovyMarkupConfigurer(ObjectProvider<MarkupTemplateEngine> templateEngine, Environment environment) { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); PropertyMapper map = PropertyMapper.get(); map.from(this.properties::isAutoEscape).to(configurer::setAutoEscape); map.from(this.properties::isAutoIndent).to(configurer::setAutoIndent); map.from(this.properties::getAutoIndentString).to(configurer::setAutoIndentString); map.from(this.properties::isAutoNewLine).to(configurer::setAutoNewLine); map.from(this.properties::getBaseTemplateClass).to(configurer::setBaseTemplateClass); map.from(this.properties::isCache).to(configurer::setCacheTemplates); map.from(this.properties::getDeclarationEncoding).to(configurer::setDeclarationEncoding); map.from(this.properties::isExpandEmptyElements).to(configurer::setExpandEmptyElements); map.from(this.properties::getLocale).to(configurer::setLocale); map.from(this.properties::getNewLineString).to(configurer::setNewLineString); map.from(this.properties::getResourceLoaderPath).to(configurer::setResourceLoaderPath); map.from(this.properties::isUseDoubleQuotes).to(configurer::setUseDoubleQuotes); Binder.get(environment).bind("spring.groovy.template.configuration", Bindable.ofInstance(configurer)); templateEngine.ifAvailable(configurer::setTemplateEngine); return configurer;
} } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ Servlet.class, LocaleContextHolder.class, UrlBasedViewResolver.class }) @ConditionalOnWebApplication(type = Type.SERVLET) static class GroovyWebConfiguration { @Bean @ConditionalOnMissingBean(name = "groovyMarkupViewResolver") GroovyMarkupViewResolver groovyMarkupViewResolver(GroovyTemplateProperties properties) { GroovyMarkupViewResolver resolver = new GroovyMarkupViewResolver(); properties.applyToMvcViewResolver(resolver); return resolver; } } }
repos\spring-boot-4.0.1\module\spring-boot-groovy-templates\src\main\java\org\springframework\boot\groovy\template\autoconfigure\GroovyTemplateAutoConfiguration.java
2
请完成以下Java代码
public WorkflowLaunchersFacetGroup toWorkflowLaunchersFacetGroup(@NonNull final PickingJobFacets facets) { return WorkflowLaunchersFacetGroup.builder() .id(PickingJobFacetGroup.CUSTOMER.getWorkflowGroupFacetId()) .caption(TranslatableStrings.adRefList(PickingJobFacetGroup.PICKING_JOB_FILTER_OPTION_REFERENCE_ID, PickingJobFacetGroup.CUSTOMER)) .facets(facets.toList(CustomerFacet.class, CustomerFacetHandler::toWorkflowLaunchersFacet)) .build(); } @NonNull private static WorkflowLaunchersFacet toWorkflowLaunchersFacet(@NonNull final CustomerFacet facet) { return WorkflowLaunchersFacet.builder() .facetId(WorkflowLaunchersFacetId.ofId(PickingJobFacetGroup.CUSTOMER.getWorkflowGroupFacetId(), facet.getBpartnerId())) .caption(TranslatableStrings.anyLanguage(facet.getCustomerBPValue() + " " + facet.getCustomerName()))
.isActive(facet.isActive()) .build(); } @Override public List<CustomerFacet> extractFacets(@NonNull final Packageable packageable, @NonNull final CollectingParameters parameters) { return ImmutableList.of( CustomerFacet.of( false, packageable.getCustomerId(), packageable.getCustomerBPValue(), packageable.getCustomerName()) ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\customer\CustomerFacetHandler.java
1
请完成以下Java代码
public int getPartitionSize() { final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Ziel-DLM-Level. * * @param Target_DLM_Level Ziel-DLM-Level */ @Override public void setTarget_DLM_Level(final int Target_DLM_Level) { set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level)); } /**
* Get Ziel-DLM-Level. * * @return Ziel-DLM-Level */ @Override public int getTarget_DLM_Level() { final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java
1
请完成以下Java代码
public String getTopicName() { return topicName; } public String getWorkerId() { return workerId; } public long getPriority() { return priority; } public Integer getRetries() { return retries; } public String getErrorMessage() { return errorMessage; } public String getActivityId() { return activityId; } public String getActivityInstanceId() { return activityInstanceId; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getTenantId() { return tenantId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog;
} public boolean isDeletionLog() { return deletionLog; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId(); result.timestamp = historicExternalTaskLog.getTimestamp(); result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries(); result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请完成以下Java代码
public MigrationPlanReportDto validateMigrationPlan(MigrationPlanDto migrationPlanDto) { try { createMigrationPlan(migrationPlanDto); // return an empty report if not errors are found return MigrationPlanReportDto.emptyReport(); } catch (MigrationPlanValidationException e) { return MigrationPlanReportDto.form(e.getValidationReport()); } } public void executeMigrationPlan(MigrationExecutionDto migrationExecution) { createMigrationPlanExecutionBuilder(migrationExecution).execute(); } public BatchDto executeMigrationPlanAsync(MigrationExecutionDto migrationExecution) { Batch batch = createMigrationPlanExecutionBuilder(migrationExecution).executeAsync(); return BatchDto.fromBatch(batch); } protected MigrationPlanExecutionBuilder createMigrationPlanExecutionBuilder(MigrationExecutionDto migrationExecution) { MigrationPlan migrationPlan = createMigrationPlan(migrationExecution.getMigrationPlan()); List<String> processInstanceIds = migrationExecution.getProcessInstanceIds(); MigrationPlanExecutionBuilder executionBuilder = getProcessEngine().getRuntimeService() .newMigration(migrationPlan).processInstanceIds(processInstanceIds); ProcessInstanceQueryDto processInstanceQueryDto = migrationExecution.getProcessInstanceQuery(); if (processInstanceQueryDto != null) { ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine()); executionBuilder.processInstanceQuery(processInstanceQuery); } if (migrationExecution.isSkipCustomListeners()) { executionBuilder.skipCustomListeners(); } if (migrationExecution.isSkipIoMappings()) {
executionBuilder.skipIoMappings(); } return executionBuilder; } protected MigrationPlan createMigrationPlan(MigrationPlanDto migrationPlanDto) { try { return MigrationPlanDto.toMigrationPlan(getProcessEngine(), objectMapper, migrationPlanDto); } catch (MigrationPlanValidationException e) { throw e; } catch (BadUserRequestException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MigrationRestServiceImpl.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Link. @param Link Contains URL to a target */ public void setLink (String Link) { set_Value (COLUMNNAME_Link, Link); } /** Get Link. @return Contains URL to a target */ public String getLink () { return (String)get_Value(COLUMNNAME_Link); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsChannel.java
1
请完成以下Java代码
private static List<ClientRegistration> toList(ClientRegistration... registrations) { Assert.notEmpty(registrations, "registrations cannot be null or empty"); return Arrays.asList(registrations); } /** * Constructs an {@code InMemoryReactiveClientRegistrationRepository} using the * provided parameters. * @param registrations the client registration(s) */ public InMemoryReactiveClientRegistrationRepository(List<ClientRegistration> registrations) { this.clientIdToClientRegistration = toUnmodifiableConcurrentMap(registrations); } @Override public Mono<ClientRegistration> findByRegistrationId(String registrationId) { return Mono.justOrEmpty(this.clientIdToClientRegistration.get(registrationId)); } /** * Returns an {@code Iterator} of {@link ClientRegistration}. * @return an {@code Iterator<ClientRegistration>}
*/ @Override public Iterator<ClientRegistration> iterator() { return this.clientIdToClientRegistration.values().iterator(); } private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { Assert.notEmpty(registrations, "registrations cannot be null or empty"); ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { Assert.notNull(registration, "no registration can be null"); if (result.containsKey(registration.getRegistrationId())) { throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId())); } result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\InMemoryReactiveClientRegistrationRepository.java
1
请在Spring Boot框架中完成以下Java代码
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .headers() .frameOptions().sameOrigin() .and() .authorizeRequests() .antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .failureUrl("/login?error") .permitAll() .and()
.logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login?logout") .deleteCookies("my-remember-me-cookie") .permitAll() .and() .rememberMe() //.key("my-secure-key") .rememberMeCookieName("my-remember-me-cookie") .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(24 * 60 * 60) .and() .exceptionHandling() ; } PersistentTokenRepository persistentTokenRepository(){ JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-thymeleaf-security-demo\src\main\java\net\alanbinu\springbootsecurity\config\WebSecurityConfig.java
2
请在Spring Boot框架中完成以下Java代码
private void warmUpById(final DDOrderId ddOrderId) { final I_DD_Order ddOrder = loadingSupportServices.getDDOrderById(ddOrderId); addToCache(ddOrder); } private void addToCache(@NonNull final I_DD_Order ddOrder) { addToCache(ImmutableList.of(ddOrder)); } private void addToCache(@NonNull final List<I_DD_Order> ddOrders) { ddOrders.forEach(ddOrder -> ddOrdersCache.put(DDOrderId.ofRepoId(ddOrder.getDD_Order_ID()), ddOrder)); CollectionUtils.getAllOrLoad(ddOrderLinesCache, ddOrdersCache.keySet(), loadingSupportServices::getLinesByDDOrderIds); final ImmutableSet<DDOrderLineId> ddOrderLineIds = ddOrderLinesCache.values() .stream() .flatMap(Collection::stream) .map(ddOrderLine -> DDOrderLineId.ofRepoId(ddOrderLine.getDD_OrderLine_ID()))
.collect(ImmutableSet.toImmutableSet()); CollectionUtils.getAllOrLoad(schedulesCache, ddOrderLineIds, loadingSupportServices::getSchedulesByDDOrderLineIds); } I_DD_Order getDDOrder(final DDOrderId ddOrderId) { return ddOrdersCache.computeIfAbsent(ddOrderId, loadingSupportServices::getDDOrderById); } private List<I_DD_OrderLine> getDDOrderLines(final DDOrderId ddOrderId) { return CollectionUtils.getOrLoad(ddOrderLinesCache, ddOrderId, loadingSupportServices::getLinesByDDOrderIds); } private List<DDOrderMoveSchedule> getSchedules(final DDOrderLineId ddOrderLineId) { return CollectionUtils.getOrLoad(schedulesCache, ddOrderLineId, loadingSupportServices::getSchedulesByDDOrderLineIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoader.java
2
请完成以下Java代码
private boolean isNotDuplicateDocumentFilter(@NonNull final DocumentFilter filterToAdd) { return _addedFiltersNoDuplicates.add(filterToAdd.withId("AvoidDuplicateFiltersThatOnlyDifferInTheirId")); } public Builder addStickyFilters(final DocumentFilterList stickyFilters) { if (stickyFilters == null || stickyFilters.isEmpty()) { return this; } stickyFilters.forEach(this::addStickyFilterSkipDuplicates); return this; } private DocumentFilterList getStickyFilters() { return _stickyFiltersById == null ? DocumentFilterList.EMPTY : DocumentFilterList.ofList(_stickyFiltersById.values()); } public Builder setFilters(final DocumentFilterList filters) { _filtersById.clear(); filters.forEach(filter -> { final boolean notDuplicate = isNotDuplicateDocumentFilter(filter); if (notDuplicate) { _filtersById.put(filter.getFilterId(), filter); } }); return this; } private DocumentFilterList getFilters() { return _filtersById.isEmpty() ? DocumentFilterList.EMPTY : DocumentFilterList.ofList(_filtersById.values()); } public Builder addFiltersIfAbsent(final Collection<DocumentFilter> filters) { filters.forEach(filter -> { final boolean notDuplicate = isNotDuplicateDocumentFilter(filter); if (notDuplicate) { _filtersById.putIfAbsent(filter.getFilterId(), filter); } }); return this; } public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this.refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this; } private boolean isRefreshViewOnChangeEvents() {
return refreshViewOnChangeEvents; } public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor) { this.viewInvalidationAdvisor = viewInvalidationAdvisor; return this; } private IViewInvalidationAdvisor getViewInvalidationAdvisor() { return viewInvalidationAdvisor; } public Builder applySecurityRestrictions(final boolean applySecurityRestrictions) { this.applySecurityRestrictions = applySecurityRestrictions; return this; } private boolean isApplySecurityRestrictions() { return applySecurityRestrictions; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\DefaultView.java
1
请完成以下Java代码
public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public void setDeploymentIds(List<String> deploymentIds) { this.deploymentIds = deploymentIds; } public String getActiveActivityId() { return activeActivityId; } public void setActiveActivityId(String activeActivityId) { this.activeActivityId = activeActivityId; } public Set<String> getActiveActivityIds() { return activeActivityIds; } public void setActiveActivityIds(Set<String> activeActivityIds) { this.activeActivityIds = activeActivityIds; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public String getCallbackId() { return callbackId; } public Set<String> getCallBackIds() { return callbackIds; }
public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public List<ExecutionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return null; } public String getParentScopeId() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
protected void init(AtomicOperation operation, ExecutionEntity execution, boolean performAsync) { this.operation = operation; this.execution = execution; this.performAsync = performAsync; } public void execute(BpmnStackTrace stackTrace, ProcessDataContext processDataContext) { if(operation != PvmAtomicOperation.ACTIVITY_START_CANCEL_SCOPE && operation != PvmAtomicOperation.ACTIVITY_START_INTERRUPT_SCOPE && operation != PvmAtomicOperation.ACTIVITY_START_CONCURRENT && operation != PvmAtomicOperation.DELETE_CASCADE) { // execution might be replaced in the meantime: ExecutionEntity replacedBy = execution.getReplacedBy(); if(replacedBy != null) { execution = replacedBy; } } //execution was canceled for example via terminate end event if (execution.isCanceled() && (operation == PvmAtomicOperation.TRANSITION_NOTIFY_LISTENER_END || operation == PvmAtomicOperation.ACTIVITY_NOTIFY_LISTENER_END)) { return; } // execution might have ended in the meanwhile if(execution.isEnded() && (operation == PvmAtomicOperation.TRANSITION_NOTIFY_LISTENER_TAKE || operation == PvmAtomicOperation.ACTIVITY_START_CREATE_SCOPE)) { return; } ProcessApplicationReference currentPa = Context.getCurrentProcessApplication(); if(currentPa != null) { applicationContextName = currentPa.getName(); } activityId = execution.getActivityId(); activityName = execution.getCurrentActivityName(); stackTrace.add(this); boolean popProcessDataContextSection = processDataContext.pushSection(execution); try { Context.setExecutionContext(execution);
if(!performAsync) { LOG.debugExecutingAtomicOperation(operation, execution); operation.execute(execution); } else { execution.scheduleAtomicOperationAsync(this); } if (popProcessDataContextSection) { processDataContext.popSection(); } } finally { Context.removeExecutionContext(); } } // getters / setters //////////////////////////////////// public AtomicOperation getOperation() { return operation; } public ExecutionEntity getExecution() { return execution; } public boolean isPerformAsync() { return performAsync; } public String getApplicationContextName() { return applicationContextName; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\AtomicOperationInvocation.java
1
请完成以下Java代码
protected void prepare() { // Display process logs only if the process failed. // NOTE: we do that because this process is called from window Gear and user shall only see the status line, and no popup shall be displayed. // gh #755 new note: this process is run manually from gear only rarely. So an (admin-) user who runs this should see what went on. // particularly if there were problems (and this process would still return "OK" in that case). setShowProcessLogs(ShowProcessLogs.Always); } @Override protected String doIt() throws Exception { Check.assume(olCandProcessorId > 0, "olCandProcessorId > 0"); // IMPORTANT: we shall create the selection out of transaction because // else the selection (T_Selection) won't be available when creating the main lock for records of this selection. final PInstanceId userSelectionId = queryBL.createQueryBuilderOutOfTrx(I_C_OLCand.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OLCand.COLUMNNAME_Processed, false) .filter(getProcessInfo().getQueryFilterOrElseTrue())
.create() .createSelection(); if (userSelectionId == null) { throw new AdempiereException(MSG_OL_CANDENQUEUE_FOR_SALES_ORDER_CREATION_NO_VALID_RECORD_SELECTED).markAsUserValidationError(); } final C_OLCandToOrderEnqueuer olCandToOrderEnqueuer = SpringContextHolder.instance.getBean(C_OLCandToOrderEnqueuer.class); final OlCandEnqueueResult result = olCandToOrderEnqueuer.enqueueSelection(userSelectionId); addLog("OlCandEnqueueResult: {}", result); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\process\C_OLCandEnqueueForSalesOrderCreation.java
1
请完成以下Java代码
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 String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @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 "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java
1
请完成以下Java代码
public void ignoreHeader(String field, String value) { logInfo("002", "Ignoring header with name '{}' and value '{}'", field, value); } public void payloadIgnoredForHttpMethod(String method) { logInfo("003", "Ignoring payload for HTTP '{}' method", method); } public ConnectorResponseException unableToReadResponse(Exception cause) { return new ConnectorResponseException(exceptionMessage("004", "Unable to read connectorResponse: {}", cause.getMessage()), cause); } public ConnectorRequestException requestUrlRequired() { return new ConnectorRequestException(exceptionMessage("005", "Request url required.")); } public ConnectorRequestException unknownHttpMethod(String method) { return new ConnectorRequestException(exceptionMessage("006", "Unknown or unsupported HTTP method '{}'", method)); }
public ConnectorRequestException unableToExecuteRequest(Exception cause) { return new ConnectorRequestException(exceptionMessage("007", "Unable to execute HTTP request"), cause); } public ConnectorRequestException invalidConfigurationOption(String optionName, Exception cause) { return new ConnectorRequestException(exceptionMessage("008", "Invalid value for request configuration option: {}", optionName), cause); } public void ignoreConfig(String field, Object value) { logInfo("009", "Ignoring request configuration option with name '{}' and value '{}'", field, value); } public ConnectorRequestException httpRequestError(int statusCode , String connectorResponse) { return new ConnectorRequestException(exceptionMessage("010", "HTTP request failed with Status Code: {} ," + " Response: {}", statusCode, connectorResponse)); } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\HttpConnectorLogger.java
1
请完成以下Java代码
protected List<ExecutionEntity> loadFromDb(final String processInstanceId, final CommandContext commandContext) { List<ExecutionEntity> executions = commandContext.getExecutionManager().findExecutionsByProcessInstanceId(processInstanceId); ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId); // initialize parent/child sets if (processInstance != null) { processInstance.restoreProcessInstance(executions, null, null, null, null, null, null); } return executions; } /** * Loads all executions that are part of this process instance tree from the dbSqlSession cache. * (optionally querying the db if a child is not already loaded. * * @param execution the current root execution (already contained in childExecutions) * @param childExecutions the list in which all child executions should be collected */ protected void loadChildExecutionsFromCache(ExecutionEntity execution, List<ExecutionEntity> childExecutions) { List<ExecutionEntity> childrenOfThisExecution = execution.getExecutions(); if(childrenOfThisExecution != null) { childExecutions.addAll(childrenOfThisExecution); for (ExecutionEntity child : childrenOfThisExecution) { loadChildExecutionsFromCache(child, childExecutions); } } } protected Map<String, List<Incident>> groupIncidentIdsByExecutionId(CommandContext commandContext) { List<IncidentEntity> incidents = commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId); Map<String, List<Incident>> result = new HashMap<>(); for (IncidentEntity incidentEntity : incidents) { CollectionUtil.addToMapOfLists(result, incidentEntity.getExecutionId(), incidentEntity); } return result; } protected List<String> getIncidentIds(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<String> incidentIds = new ArrayList<>(); List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { for (Incident incident : incidentList) { incidentIds.add(incident.getId());
} return incidentIds; } else { return Collections.emptyList(); } } protected List<Incident> getIncidents(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { return incidentList; } else { return Collections.emptyList(); } } public static class ExecutionIdComparator implements Comparator<ExecutionEntity> { public static final ExecutionIdComparator INSTANCE = new ExecutionIdComparator(); @Override public int compare(ExecutionEntity o1, ExecutionEntity o2) { return o1.getId().compareTo(o2.getId()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetActivityInstanceCmd.java
1
请在Spring Boot框架中完成以下Java代码
private IPricingRule createPricingRuleNoFail(final PricingRuleDescriptor ruleDef) { try { return ruleDef.getPricingRuleClass().getReferencedClass().newInstance(); } catch (final Exception ex) { logger.warn("Cannot load rule for {}", ruleDef, ex); return null; } } private CurrencyPrecision getPricePrecision(@NonNull final PriceListId priceListId) { return Services.get(IPriceListBL.class).getPricePrecision(priceListId); } @Override
public void registerPriceLimitRule(@NonNull final IPriceLimitRule rule) { priceLimitRules.addEnforcer(rule); } @Override public PriceLimitRuleResult computePriceLimit(@NonNull final PriceLimitRuleContext context) { return priceLimitRules.compute(context); } @Override public Set<CountryId> getPriceLimitCountryIds() { return priceLimitRules.getPriceCountryIds(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingBL.java
2
请在Spring Boot框架中完成以下Java代码
private <T> ResponseEntity<T> performWithRetry(final URI resourceURI, final HttpMethod httpMethod, final HttpEntity<String> request, final Class<T> responseType) { ResponseEntity<T> response = null; boolean retry = true; while (retry) { try { log.debug("Performing [{}] on [{}] for request [{}]", httpMethod.name(), resourceURI, request); retry = false; response = restTemplate().exchange(resourceURI, httpMethod, request, responseType); } catch (final RateLimitExceededException rateLimitEx) { Loggables.withLogger(log, Level.ERROR) .addLog("*** ERROR: RateLimit reached on Github side! ErrorMsg: {}, rateLimitInfo: {}", rateLimitEx.getErrorMessage(), rateLimitEx); rateLimitService.waitForLimitReset(rateLimitEx.getRateLimit()); retry = true; } catch (final Throwable t) {
log.error("ERROR while trying to fetch from URI: {}, Error message: {}", resourceURI, t.getMessage(), t); throw t; } } return response; } private RestTemplate restTemplate() { return new RestTemplateBuilder() .errorHandler(responseErrorHandler) .setConnectTimeout(Duration.ofMillis(sysConfigBL.getIntValue(CONNECTION_TIMEOUT.getName(), CONNECTION_TIMEOUT.getDefaultValue()))) .setReadTimeout(Duration.ofMillis(sysConfigBL.getIntValue(READ_TIMEOUT.getName(),READ_TIMEOUT.getDefaultValue()))) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.github\src\main\java\de\metas\issue\tracking\github\api\v3\service\rest\RestService.java
2
请完成以下Java代码
protected MonitorConfig parseMonitor(String monitor, DubboProperties properties, Environment environment, String... errors) { MonitorConfig monitorConfig = null; if (monitor == null || "".equals(monitor)) { monitorConfig = properties.getMonitor(); } else { monitor = environment.resolvePlaceholders(monitor); Map<String, AbstractConfig> monitorMap = ID_CONFIG_MAP.get(MONITORS_KEY); monitorConfig = (MonitorConfig) monitorMap.get(monitor); if (monitorConfig == null) { monitorConfig = properties.getMonitors().get(monitor); if (monitorConfig == null) { throw new NullPointerException(this.buildErrorMsg(errors)); } } } return monitorConfig; } protected ProviderConfig parseProvider(String provider, DubboProperties properties, Environment environment, String... errors) { ProviderConfig providerConfig = null; if (provider == null || "".equals(provider)) { providerConfig = properties.getProvider(); } else { provider = environment.resolvePlaceholders(provider); Map<String, AbstractConfig> providerMap = ID_CONFIG_MAP.get(PROVIDERS_KEY); providerConfig = (ProviderConfig) providerMap.get(provider); if (providerConfig == null) { providerConfig = properties.getProviders().get(provider); if (providerConfig == null) { throw new NullPointerException(this.buildErrorMsg(errors));
} } } return providerConfig; } protected ConsumerConfig parseConsumer(String consumer, DubboProperties properties, Environment environment, String... errors) { ConsumerConfig consumerConfig = null; if (consumer == null || "".equals(consumer)) { consumerConfig = properties.getConsumer(); } else { consumer = environment.resolvePlaceholders(consumer); Map<String, AbstractConfig> consumerMap = ID_CONFIG_MAP.get(CONSUMERS_KEY); consumerConfig = (ConsumerConfig) consumerMap.get(consumer); if (consumerConfig == null) { consumerConfig = properties.getConsumers().get(consumer); if (consumerConfig == null) { throw new NullPointerException(this.buildErrorMsg(errors)); } } } return consumerConfig; } }
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboCommonAutoConfiguration.java
1
请完成以下Java代码
public class ConfigurationPropertiesBindException extends BeanCreationException { private final ConfigurationPropertiesBean bean; ConfigurationPropertiesBindException(ConfigurationPropertiesBean bean, Exception cause) { super(bean.getName(), getMessage(bean), cause); this.bean = bean; } /** * Return the bean type that was being bound. * @return the bean type */ public Class<?> getBeanType() { return this.bean.getType(); } /** * Return the configuration properties annotation that triggered the binding. * @return the configuration properties annotation */ public ConfigurationProperties getAnnotation() {
return this.bean.getAnnotation(); } private static String getMessage(ConfigurationPropertiesBean bean) { ConfigurationProperties annotation = bean.getAnnotation(); StringBuilder message = new StringBuilder(); message.append("Could not bind properties to '"); message.append(ClassUtils.getShortName(bean.getType())).append("' : "); message.append("prefix=").append(annotation.prefix()); message.append(", ignoreInvalidFields=").append(annotation.ignoreInvalidFields()); message.append(", ignoreUnknownFields=").append(annotation.ignoreUnknownFields()); return message.toString(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindException.java
1
请完成以下Java代码
public class RoleImpl extends CmmnElementImpl implements Role { protected static Attribute<String> nameAttribute; public RoleImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Role.class, CMMN_ELEMENT_ROLE)
.extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Role>() { public Role newInstance(ModelTypeInstanceContext instanceContext) { return new RoleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RoleImpl.java
1
请完成以下Java代码
public String attribute(String name, String defaultValue) { if (attributeMap.containsKey(name)) { return attributeMap.get(name).getValue(); } return defaultValue; } public String attributeNS(Namespace namespace, String name, String defaultValue) { String attribute = attribute(composeMapKey(namespace.getNamespaceUri(), name)); if (attribute == null && namespace.hasAlternativeUri()) { attribute = attribute(composeMapKey(namespace.getAlternativeUri(), name)); } if (attribute == null) { return defaultValue; } return attribute; } protected String composeMapKey(String attributeUri, String attributeName) { StringBuilder strb = new StringBuilder(); if (attributeUri != null && !attributeUri.equals("")) { strb.append(attributeUri); strb.append(":"); } strb.append(attributeName); return strb.toString(); } public List<Element> elements() { return elements; } public String toString() { return "<"+tagName+"..."; } public String getUri() { return uri;
} public String getTagName() { return tagName; } public int getLine() { return line; } public int getColumn() { return column; } /** * Due to the nature of SAX parsing, sometimes the characters of an element * are not processed at once. So instead of a setText operation, we need * to have an appendText operation. */ public void appendText(String text) { this.text.append(text); } public String getText() { return text.toString(); } /** * allows to recursively collect the ids of all elements in the tree. */ public void collectIds(List<String> ids) { ids.add(attribute("id")); for (Element child : elements) { child.collectIds(ids); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Element.java
1
请完成以下Java代码
public SimpleAsyncTaskScheduler build() { return configure(new SimpleAsyncTaskScheduler()); } /** * Configure the provided {@link SimpleAsyncTaskScheduler} instance using this * builder. * @param <T> the type of task scheduler * @param taskScheduler the {@link SimpleAsyncTaskScheduler} to configure * @return the task scheduler instance * @see #build() */ public <T extends SimpleAsyncTaskScheduler> T configure(T taskScheduler) { PropertyMapper map = PropertyMapper.get(); map.from(this.threadNamePrefix).to(taskScheduler::setThreadNamePrefix); map.from(this.concurrencyLimit).to(taskScheduler::setConcurrencyLimit);
map.from(this.virtualThreads).to(taskScheduler::setVirtualThreads); map.from(this.taskTerminationTimeout).as(Duration::toMillis).to(taskScheduler::setTaskTerminationTimeout); map.from(this.taskDecorator).to(taskScheduler::setTaskDecorator); if (!CollectionUtils.isEmpty(this.customizers)) { this.customizers.forEach((customizer) -> customizer.customize(taskScheduler)); } return taskScheduler; } private <T> Set<T> append(@Nullable Set<T> set, Iterable<? extends T> additions) { Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet()); additions.forEach(result::add); return Collections.unmodifiableSet(result); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\task\SimpleAsyncTaskSchedulerBuilder.java
1
请完成以下Java代码
private static Object dataTypeConvert(String mysqlType, String value) { try { if (mysqlType.startsWith("int") || mysqlType.startsWith("tinyint") || mysqlType.startsWith("smallint") || mysqlType.startsWith("mediumint")) { //int(32) return StringUtils.isBlank(value) ? null : Integer.parseInt(value); } else if (mysqlType.startsWith("bigint")) { //int(64) return StringUtils.isBlank(value) ? null : Long.parseLong(value); } else if (mysqlType.startsWith("float") || mysqlType.startsWith("double")) { return StringUtils.isBlank(value) ? null : Double.parseDouble(value); } else if (mysqlType.startsWith("decimal")) { //小数精度为0时转换成long类型,否则转换为double类型 int lenBegin = mysqlType.indexOf('('); int lenCenter = mysqlType.indexOf(','); int lenEnd = mysqlType.indexOf(')'); if (lenBegin > 0 && lenEnd > 0 && lenCenter > 0) { int length = Integer.parseInt(mysqlType.substring(lenCenter + 1, lenEnd)); if (length == 0) { return StringUtils.isBlank(value) ? null : Long.parseLong(value);
} } return StringUtils.isBlank(value) ? null : Double.parseDouble(value); } else if (mysqlType.startsWith("datetime") || mysqlType.startsWith("timestamp")) { return StringUtils.isBlank(value) ? null : DATE_TIME_FORMAT.parse(value); } else if (mysqlType.equals("date")) { return StringUtils.isBlank(value) ? null : DATE_FORMAT.parse(value); } else if (mysqlType.startsWith("varchar")) { //设置默认空串 return value == null ? "" : value; } else { logger.error("unknown data type :[{}]-[{}]", mysqlType, value); } } catch (Exception e) { logger.error("data type convert error ", e); } return value; } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\util\DBConvertUtil.java
1
请完成以下Java代码
public void setHttpCacheMaxAge(final int httpCacheMaxAge) { final InternalUserSessionData data = getData(); final int httpCacheMaxAgeOld = data.getHttpCacheMaxAge(); data.setHttpCacheMaxAge(httpCacheMaxAge); logSettingChanged("HttpCacheMaxAge", httpCacheMaxAge, httpCacheMaxAgeOld); } public int getHttpCacheMaxAge() { return getData().getHttpCacheMaxAge(); } private static final String SYSCONFIG_DefaultLookupSearchStartDelayMillis = "de.metas.ui.web.window.descriptor.LookupDescriptor.DefaultLookupSearchStartDelayMillis"; public Supplier<Duration> getDefaultLookupSearchStartDelay() { return () -> { final int defaultLookupSearchStartDelayMillis = sysConfigBL.getIntValue(SYSCONFIG_DefaultLookupSearchStartDelayMillis, 0); return defaultLookupSearchStartDelayMillis > 0 ? Duration.ofMillis(defaultLookupSearchStartDelayMillis) : Duration.ZERO; }; } /* This configuration is used for a webui option. */ private static final String SYSCONFIG_isAlwaysDisplayNewBPartner = "de.metas.ui.web.session.UserSession.IsAlwaysDisplayNewBPartner"; public boolean isAlwaysShowNewBPartner() { return sysConfigBL.getBooleanValue(SYSCONFIG_isAlwaysDisplayNewBPartner, false, getClientId().getRepoId(), getOrgId().getRepoId()); } @NonNull public ZoneId getTimeZone() { final OrgId orgId = getOrgId(); final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId); if (orgInfo.getTimeZone() != null) { return orgInfo.getTimeZone(); } return de.metas.common.util.time.SystemTime.zoneId(); }
/** * @deprecated avoid using this method; usually it's workaround-ish / quick and dirty fix */ @Deprecated public static ZoneId getTimeZoneOrSystemDefault() { final UserSession userSession = getCurrentOrNull(); return userSession != null ? userSession.getTimeZone() : SystemTime.zoneId(); } public boolean isWorkplacesEnabled() { return workplaceService.isAnyWorkplaceActive(); } public @NonNull Optional<Workplace> getWorkplace() { if (!isWorkplacesEnabled()) { return Optional.empty(); } return getLoggedUserIdIfExists().flatMap(workplaceService::getWorkplaceByUserId); } /** * Event fired when the user language was changed. * Usually it is user triggered. * * @author metas-dev <dev@metasfresh.com> */ @lombok.Value public static class LanguagedChangedEvent { @NonNull String adLanguage; UserId adUserId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSession.java
1
请完成以下Java代码
public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschluessel. @return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Breite. @param Width Breite */
public void setWidth (BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } /** Get Breite. @return Breite */ public BigDecimal getWidth () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Width); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
public DirectMovementsFromSchedulesGenerator locatorToIdOverride(@Nullable final LocatorId locatorToIdOverride) { this.locatorToIdOverride = locatorToIdOverride; return this; } public DirectMovementsFromSchedulesGenerator skipCompletingDDOrder() { this.skipCompletingDDOrder = true; return this; } /** * Do direct movements (e.g. skip the InTransit warehouse) */ public void generateDirectMovements() { trxManager.runInThreadInheritedTrx(this::generateDirectMovementsInTrx); } private void generateDirectMovementsInTrx() { trxManager.assertThreadInheritedTrxExists(); markExecuted(); schedules.forEach(this::generateDirectMovement); } private void markExecuted() { if (executed) { throw new AdempiereException("Already executed"); } this.executed = true; } private void generateDirectMovement(final DDOrderMoveSchedule schedule) { // // Make sure DD Order is completed final DDOrderId ddOrderId = schedule.getDdOrderId(); if (!skipCompletingDDOrder) { final I_DD_Order ddOrder = getDDOrderById(ddOrderId); ddOrderService.completeDDOrderIfNeeded(ddOrder); } schedule.assertNotPickedFrom(); schedule.assertNotDroppedTo(); final Quantity qtyToMove = schedule.getQtyToPick(); final HuId huIdToMove = schedule.getPickFromHUId(); final MovementId directMovementId = createDirectMovement(schedule, huIdToMove); schedule.markAsPickedFrom( null, DDOrderMoveSchedulePickedHUs.of( DDOrderMoveSchedulePickedHU.builder() .actualHUIdPicked(huIdToMove) .qtyPicked(qtyToMove) .pickFromMovementId(directMovementId)
.inTransitLocatorId(null) .dropToLocatorId(schedule.getDropToLocatorId()) .build()) ); schedule.markAsDroppedTo(schedule.getDropToLocatorId(), directMovementId); ddOrderMoveScheduleService.save(schedule); } private MovementId createDirectMovement( final @NonNull DDOrderMoveSchedule schedule, final @NonNull HuId huIdToMove) { final HUMovementGeneratorResult result = new HUMovementGenerator(toMovementGenerateRequest(schedule, huIdToMove)) .sharedHUIdsWithPackingMaterialsTransferred(huIdsWithPackingMaterialsTransferred) .createMovement(); return result.getSingleMovementLineId().getMovementId(); } private HUMovementGenerateRequest toMovementGenerateRequest( final @NonNull DDOrderMoveSchedule schedule, final @NonNull HuId huIdToMove) { final I_DD_Order ddOrder = ddOrdersCache.getById(schedule.getDdOrderId()); return DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(locatorToIdOverride != null ? locatorToIdOverride : schedule.getDropToLocatorId()) .huIdToMove(huIdToMove) .build(); } private I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrdersCache.getById(ddOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\generate\DirectMovementsFromSchedulesGenerator.java
1
请完成以下Java代码
default void runBeforeCommit(@NonNull final Runnable runnable) { newEventListener(TrxEventTiming.BEFORE_COMMIT) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> runnable.run()); } default void runAfterRollback(@NonNull final Runnable runnable) { newEventListener(TrxEventTiming.AFTER_ROLLBACK) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> runnable.run()); } default void runAfterClose(@NonNull final Consumer<ITrx> runnable) { newEventListener(TrxEventTiming.AFTER_CLOSE) .invokeMethodJustOnce(true) .registerHandlingMethod(runnable::accept); }
/** * This method shall only be called by the framework. */ void fireBeforeCommit(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterCommit(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterRollback(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterClose(ITrx trx); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\ITrxListenerManager.java
1
请在Spring Boot框架中完成以下Java代码
public String hblogImages1() { String message = ""; try { QrConfig config = new QrConfig(300, 300); // Set the margin, that is, the margin between the QR code and the background config.setMargin(3); // Set the foreground color, which is the QR code color (cyan) config.setForeColor(Color.CYAN.getRGB()); // Set background color (gray) config.setBackColor(Color.GRAY.getRGB()); // Generate QR code to file or stream QrCodeUtil.generate("http://www.liuhiahua.cn/", config, FileUtil.file("D:\\tmp\\hblog1.png")); } catch (Exception e) { e.printStackTrace(); } return message; } @RequestMapping("/hblog/qrcode/image2")
public String hblogImages2() { String message = ""; try { QrCodeUtil.generate(// "http://www.liuhiahua.cn/", //content QrConfig.create().setImg("D:\\tmp\\logo.png"), //logo FileUtil.file("D:\\tmp\\qrcodeWithLogo.jpg")//output file ); } catch (Exception e) { e.printStackTrace(); } return message; } }
repos\springboot-demo-master\qrcode\src\main\java\com\et\qrcode\controller\QRCodeController.java
2
请在Spring Boot框架中完成以下Java代码
public class C_BPartner { private final static Logger logger = LogManager.getLogger(C_BPartner.class); private final IAcctSchemaDAO acctSchemaDAO = Services.get(IAcctSchemaDAO.class); private final IAcctSchemaBL acctSchemaBL = Services.get(IAcctSchemaBL.class); @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_BPartner.COLUMNNAME_Value, I_C_BPartner.COLUMNNAME_AD_Org_ID }) public void beforeSave(final I_C_BPartner bpartner) { final ClientId clientId = ClientId.ofRepoId(bpartner.getAD_Client_ID()); final OrgId orgId = OrgId.ofRepoIdOrAny(bpartner.getAD_Org_ID()); if (EmptyUtil.isBlank(bpartner.getValue())) { // we need a value for the debitor and creditor IDs; // if we don't set it here, then org.compiere.model.PO#saveNew would set it anyways
final String value = SequenceUtil.createValueFor(bpartner); bpartner.setValue(value); logger.debug("On-the-fly created C_BPartner.Value={}", value); } final AcctSchema as = acctSchemaDAO.getByClientAndOrgOrNull(clientId, orgId); if (as == null) { Loggables.withLogger(logger, Level.DEBUG).addLog( "Found no AcctSchema for AD_Client_ID={} and AD_Org_ID={}; -> can't update debitorId and creditorId of C_BPartner_ID={}", bpartner.getAD_Client_ID(), bpartner.getAD_Org_ID(), bpartner.getC_BPartner_ID()); return; } acctSchemaBL.updateDebitorCreditorIds(as, bpartner); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_BPartner.java
2
请在Spring Boot框架中完成以下Java代码
public EventSubscriptionQuery orderByTenantId() { return orderBy(EventSubscriptionQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return eventSubscriptionServiceConfiguration.getEventSubscriptionEntityManager().findEventSubscriptionCountByQueryCriteria(this); } @Override public List<EventSubscription> executeList(CommandContext commandContext) { return eventSubscriptionServiceConfiguration.getEventSubscriptionEntityManager().findEventSubscriptionsByQueryCriteria(this); } // getters ////////////////////////////////////////// @Override public String getId() { return id; } public String getEventType() { return eventType; } public String getEventName() { return eventName; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public boolean isWithoutProcessInstanceId() { return withoutProcessInstanceId; } public String getActivityId() { return activityId; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isWithoutProcessDefinitionId() { return withoutProcessDefinitionId; } public String getSubScopeId() { return subScopeId; } public String getScopeId() { return scopeId; } public boolean isWithoutScopeId() { return withoutScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId;
} public boolean isWithoutScopeDefinitionId() { return withoutScopeDefinitionId; } public String getScopeDefinitionKey() { return scopeDefinitionKey; } public String getScopeType() { return scopeType; } public Date getCreatedBefore() { return createdBefore; } public Date getCreatedAfter() { return createdAfter; } public String getTenantId() { return tenantId; } public Collection<String> getTenantIds() { return tenantIds; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getConfiguration() { return configuration; } public Collection<String> getConfigurations() { return configurations; } public boolean isWithoutConfiguration() { return withoutConfiguration; } public List<EventSubscriptionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public EventSubscriptionQueryImpl getCurrentOrQueryObject() { return currentOrQueryObject; } public boolean isInOrStatement() { return inOrStatement; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String login(String username, String password) { String token = null; //密码需要客户端加密后传递 try { UserDetails userDetails = loadUserByUsername(username); if(!passwordEncoder.matches(password,userDetails.getPassword())){ throw new BadCredentialsException("密码不正确"); } UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); token = jwtTokenUtil.generateToken(userDetails); } catch (AuthenticationException e) { LOGGER.warn("登录异常:{}", e.getMessage()); } return token; }
@Override public String refreshToken(String token) { return jwtTokenUtil.refreshHeadToken(token); } //对输入的验证码进行校验 private boolean verifyAuthCode(String authCode, String telephone){ if(StrUtil.isEmpty(authCode)){ return false; } String realAuthCode = memberCacheService.getAuthCode(telephone); return authCode.equals(realAuthCode); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberServiceImpl.java
2
请完成以下Java代码
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { // Builds the single entries. Item entryOne = new Item(); entryOne.setTitle("JUnit 5 @Test Annotation"); entryOne.setAuthor("donatohan.rimenti@gmail.com"); entryOne.setLink("http://www.baeldung.com/junit-5-test-annotation"); entryOne.setPubDate(Date.from(Instant.parse("2017-12-19T00:00:00Z"))); Item entryTwo = new Item(); entryTwo.setTitle("Creating and Configuring Jetty 9 Server in Java"); entryTwo.setAuthor("donatohan.rimenti@gmail.com"); entryTwo.setLink("http://www.baeldung.com/jetty-java-programmatic"); entryTwo.setPubDate(Date.from(Instant.parse("2018-01-23T00:00:00Z"))); Item entryThree = new Item(); entryThree.setTitle("Flyweight Pattern in Java"); entryThree.setAuthor("donatohan.rimenti@gmail.com"); entryThree.setLink("http://www.baeldung.com/java-flyweight"); entryThree.setPubDate(Date.from(Instant.parse("2018-02-01T00:00:00Z"))); Item entryFour = new Item(); entryFour.setTitle("Multi-Swarm Optimization Algorithm in Java"); entryFour.setAuthor("donatohan.rimenti@gmail.com"); entryFour.setLink("http://www.baeldung.com/java-multi-swarm-algorithm"); entryFour.setPubDate(Date.from(Instant.parse("2018-03-09T00:00:00Z"))); Item entryFive = new Item(); entryFive.setTitle("A Simple Tagging Implementation with MongoDB"); entryFive.setAuthor("donatohan.rimenti@gmail.com"); entryFive.setLink("http://www.baeldung.com/mongodb-tagging"); entryFive.setPubDate(Date.from(Instant.parse("2018-03-27T00:00:00Z")));
Item entrySix = new Item(); entrySix.setTitle("Double-Checked Locking with Singleton"); entrySix.setAuthor("donatohan.rimenti@gmail.com"); entrySix.setLink("http://www.baeldung.com/java-singleton-double-checked-locking"); entrySix.setPubDate(Date.from(Instant.parse("2018-04-23T00:00:00Z"))); Item entrySeven = new Item(); entrySeven.setTitle("Introduction to Dagger 2"); entrySeven.setAuthor("donatohan.rimenti@gmail.com"); entrySeven.setLink("http://www.baeldung.com/dagger-2"); entrySeven.setPubDate(Date.from(Instant.parse("2018-06-30T00:00:00Z"))); // Creates the feed. return Arrays.asList(entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-5\src\main\java\com\baeldung\rss\RssFeedView.java
1
请完成以下Java代码
public static boolean valid(String singlePinyin) { if (mapNumberKey.containsKey(singlePinyin)) return true; return false; } public static Pinyin convertFromToneNumber(String singlePinyin) { return mapNumberKey.get(singlePinyin); } public static List<Pinyin> convert(String[] pinyinArray) { List<Pinyin> pinyinList = new ArrayList<Pinyin>(pinyinArray.length); for (int i = 0; i < pinyinArray.length; i++) { pinyinList.add(mapKey.get(pinyinArray[i])); } return pinyinList; } public static Pinyin convert(String singlePinyin) { return mapKey.get(singlePinyin); } /** * * @param tonePinyinText * @return */ public static List<Pinyin> convert(String tonePinyinText, boolean removeNull) { List<Pinyin> pinyinList = new LinkedList<Pinyin>(); Collection<Token> tokenize = trie.tokenize(tonePinyinText); for (Token token : tokenize) { Pinyin pinyin = mapKey.get(token.getFragment()); if (removeNull && pinyin == null) continue; pinyinList.add(pinyin); }
return pinyinList; } /** * 这些拼音是否全部合格 * @param pinyinStringArray * @return */ public static boolean valid(String[] pinyinStringArray) { for (String p : pinyinStringArray) { if (!valid(p)) return false; } return true; } public static List<Pinyin> convertFromToneNumber(String[] pinyinArray) { List<Pinyin> pinyinList = new ArrayList<Pinyin>(pinyinArray.length); for (String py : pinyinArray) { pinyinList.add(convertFromToneNumber(py)); } return pinyinList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\py\TonePinyinString2PinyinConverter.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public MiddleCategory getMiddleCategory() { return middleCategory; } public void setMiddleCategory(MiddleCategory middleCategory) { this.middleCategory = middleCategory; } @Override
public int hashCode() { return 2018; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof BottomCategory)) { return false; } return id != null && id.equals(((BottomCategory) obj).id); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoSqlResultSetMapping\src\main\java\com\app\entity\BottomCategory.java
1
请完成以下Java代码
protected void create() { Employee employee = new Employee("Hugo","C","M","BN"); employee.saveIt(); employee.add(new Role("Java Developer","BN")); LazyList<Model> all = Employee.findAll(); System.out.println(all.size()); } protected void update() { Employee employee = Employee.findFirst("first_name = ?","Hugo"); employee.set("last_namea","Choi").saveIt(); employee = Employee.findFirst("last_name = ?","Choi"); System.out.println(employee.getString("first_name") + " " + employee.getString("last_name")); } protected void delete() { Employee employee = Employee.findFirst("first_name = ?","Hugo"); employee.delete(); employee = Employee.findFirst("last_name = ?","Choi");
if(null == employee){ System.out.println("No such Employee found!"); } } protected void deleteCascade() { create(); Employee employee = Employee.findFirst("first_name = ?","Hugo"); employee.deleteCascade(); employee = Employee.findFirst("last_name = ?","C"); if(null == employee){ System.out.println("No such Employee found!"); } } }
repos\tutorials-master\persistence-modules\activejdbc\src\main\java\com\baeldung\ActiveJDBCApp.java
1
请完成以下Java代码
public class SearcherIPUtils { public static String getCachePosition(String ip) { return SearcherIPUtils.getCachePosition("src/main/resources/ip2region/ip2region.xdb", ip, true); } public static String getPosition(String dbPath,String ip,boolean format) { // 1、create searcher object Searcher searcher = null; try { searcher = Searcher.newWithFileOnly(dbPath); } catch (IOException e) { throw new RuntimeException(e); } // 2、query try { String region = searcher.search(ip); if (format){ return region; } String[] split = region.split("\\|"); String s = split[0] + split[2] + split[3]; return s; } catch (Exception e) { throw new RuntimeException(e); } } /** * @Description : * @Author : mabo */ public static String getIndexCachePosition(String dbPath, String ip, boolean format) { Searcher searcher = null; byte[] vIndex; try { vIndex = Searcher.loadVectorIndexFromFile(dbPath); } catch (Exception e) { throw new RuntimeException(e); } try { searcher = Searcher.newWithVectorIndex(dbPath, vIndex); } catch (Exception e) { throw new RuntimeException(e); } try { String region = searcher.search(ip); if (format){ return region; } String[] split = region.split("\\|"); String s = split[0] + split[2] + split[3]; return s; } catch (Exception e) { throw new RuntimeException(e); }
} /** * @Description : * @Author : mabo */ public static String getCachePosition(String dbPath,String ip,boolean format) { byte[] cBuff; try { cBuff = Searcher.loadContentFromFile(dbPath); } catch (Exception e) { throw new RuntimeException(e); } Searcher searcher; try { searcher = Searcher.newWithBuffer(cBuff); } catch (Exception e) { throw new RuntimeException(e); } try { String region = searcher.search(ip); if (format){ return region; } String[] split = region.split("\\|"); String s = split[0] + split[2] + split[3]; return s; } catch (Exception e) { throw new RuntimeException(e); } } }
repos\springboot-demo-master\ipfilter\src\main\java\com\et\ipfilter\util\SearcherIPUtils.java
1
请完成以下Java代码
public class AsyncConsumerRestartedEvent extends AmqpEvent { private final Object oldConsumer; private final Object newConsumer; /** * @param source the listener container. * @param oldConsumer the old consumer. * @param newConsumer the new consumer. */ public AsyncConsumerRestartedEvent(Object source, Object oldConsumer, Object newConsumer) { super(source); this.oldConsumer = oldConsumer; this.newConsumer = newConsumer; }
public Object getOldConsumer() { return this.oldConsumer; } public Object getNewConsumer() { return this.newConsumer; } @Override public String toString() { return "AsyncConsumerRestartedEvent [oldConsumer=" + this.oldConsumer + ", newConsumer=" + this.newConsumer + ", container=" + this.getSource() + "]"; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\AsyncConsumerRestartedEvent.java
1
请完成以下Java代码
public void markAsProcessed(@NonNull final String processingTag) { queryForTag(processingTag) .create() .updateDirectly() .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Processed, true) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Updated, SystemTime.asInstant()) .execute(); } public void markAsError(@NonNull final String processingTag, @NonNull final AdIssueId adIssueId) { queryForTag(processingTag) .create() .updateDirectly() .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Processed, true) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_IsError, true)
.addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_AD_Issue_ID, adIssueId) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Updated, SystemTime.asInstant()) .execute(); } public void untag(final String processingTag) { queryForTag(processingTag) .create() .updateDirectly() .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_ProcessingTag, null) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Processed, false) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_IsError, false) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_AD_Issue_ID, null) .addSetColumnValue(I_ES_FTS_Index_Queue.COLUMNNAME_Updated, SystemTime.asInstant()) .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelToIndexRepository.java
1
请完成以下Java代码
public String toString() { // @formatter:off String fromHeader = config.getFromHeader(); String toHeader = config.getToHeader(); return filterToStringCreator(MapRequestHeaderGatewayFilterFactory.this) .append(FROM_HEADER_KEY, fromHeader != null ? fromHeader : "") .append(TO_HEADER_KEY, toHeader != null ? toHeader : "") .toString(); // @formatter:on } }; } public static class Config { private @Nullable String fromHeader; private @Nullable String toHeader; public @Nullable String getFromHeader() { return this.fromHeader; } public Config setFromHeader(String fromHeader) { this.fromHeader = fromHeader; return this; } public @Nullable String getToHeader() { return this.toHeader;
} public Config setToHeader(String toHeader) { this.toHeader = toHeader; return this; } @Override public String toString() { // @formatter:off return new ToStringCreator(this) .append("fromHeader", fromHeader) .append("toHeader", toHeader) .toString(); // @formatter:on } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\MapRequestHeaderGatewayFilterFactory.java
1
请完成以下Spring Boot application配置
management: endpoints: # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 spring: application: name: demo-application # 应用名 # Spring Security 配置项,对应 SecurityProperties 配置类 security: # 配置默认的 InMemoryUserDetailsManager 的用户账号与密码。 user: name: test # 账号 password: test # 密码 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 service: ${s
pring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。 metadata: user.name: ${spring.security.user.name} # Spring Security 认证账号 user.password: ${spring.security.user.password} # Spring Security 认证密码
repos\SpringBoot-Labs-master\labx-15\labx-15-admin-03-demo-application\src\main\resources\application.yaml
2
请完成以下Java代码
public class Consumer implements Runnable { private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName()); private boolean running = false; private final DataQueue dataQueue; public Consumer(DataQueue dataQueue) { this.dataQueue = dataQueue; } @Override public void run() { running = true; consume(); } public void stop() { running = false; } public void consume() { while (running) { if (dataQueue.isEmpty()) { try { dataQueue.waitIsNotEmpty(); } catch (InterruptedException e) { log.severe("Error while waiting to Consume messages."); break; } } // avoid spurious wake-up
if (!running) { break; } Message message = dataQueue.poll(); useMessage(message); //Sleeping on random time to make it realistic ThreadUtil.sleep((long) (Math.random() * 100)); } log.info("Consumer Stopped"); } private void useMessage(Message message) { if (message != null) { log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n", Thread.currentThread().getName(), message.getId(), message.getData())); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\Consumer.java
1
请完成以下Java代码
public class PurchaseCandidateAggregate { public static PurchaseCandidateAggregate of(final PurchaseCandidateAggregateKey aggregationKey) { return new PurchaseCandidateAggregate(aggregationKey); } private final PurchaseCandidateAggregateKey aggregationKey; private ZonedDateTime purchaseDatePromised; private Quantity qtyToDeliver; private final ArrayList<PurchaseCandidate> purchaseCandidates = new ArrayList<>(); private final HashSet<OrderAndLineId> salesOrderAndLineIds = new HashSet<>(); private PurchaseCandidateAggregate(@NonNull final PurchaseCandidateAggregateKey aggregationKey) { this.aggregationKey = aggregationKey; } public void add(@NonNull final PurchaseCandidate purchaseCandidate) { final PurchaseCandidateAggregateKey purchaseCandidateAggKey = PurchaseCandidateAggregateKey.fromPurchaseCandidate(purchaseCandidate); if (!aggregationKey.equals(purchaseCandidateAggKey)) { throw new AdempiereException("" + purchaseCandidate + " does not have the expected aggregation key: " + aggregationKey); } purchaseCandidates.add(purchaseCandidate); // purchaseDatePromised = TimeUtil.min(purchaseDatePromised, purchaseCandidate.getPurchaseDatePromised()); final OrderAndLineId orderAndLineId = purchaseCandidate.getSalesOrderAndLineIdOrNull(); if (orderAndLineId != null) { salesOrderAndLineIds.add(orderAndLineId); } } public OrgId getOrgId() { return aggregationKey.getOrgId(); } public WarehouseId getWarehouseId() { return aggregationKey.getWarehouseId(); } public ProductId getProductId() {
return aggregationKey.getProductId(); } public AttributeSetInstanceId getAttributeSetInstanceId() { return aggregationKey.getAttributeSetInstanceId(); } public Quantity getQtyToDeliver() { return qtyToDeliver; } void setQtyToDeliver(final Quantity qtyToDeliver) { this.qtyToDeliver = qtyToDeliver; } public ZonedDateTime getDatePromised() { return purchaseDatePromised; } public List<PurchaseCandidateId> getPurchaseCandidateIds() { return purchaseCandidates .stream() .map(PurchaseCandidate::getId) .collect(ImmutableList.toImmutableList()); } public Set<OrderAndLineId> getSalesOrderAndLineIds() { return ImmutableSet.copyOf(salesOrderAndLineIds); } public void calculateAndSetQtyToDeliver() { if (purchaseCandidates.isEmpty()) { return; } final Quantity qtyToPurchase = purchaseCandidates.get(0).getQtyToPurchase(); final Quantity sum = purchaseCandidates .stream() .map(PurchaseCandidate::getQtyToPurchase) .reduce(qtyToPurchase.toZero(), Quantity::add); setQtyToDeliver(sum); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\localorder\PurchaseCandidateAggregate.java
1
请完成以下Java代码
class UserDashboardItemChangeRequest { public static UserDashboardItemChangeRequest of( final DashboardWidgetType widgetType, final UserDashboardItemId itemId, final String adLanguage, @NonNull final List<JSONPatchEvent<DashboardItemPatchPath>> events) { if (events.isEmpty()) { throw new AdempiereException("no events"); } final UserDashboardItemChangeRequest.UserDashboardItemChangeRequestBuilder changeRequestBuilder = UserDashboardItemChangeRequest.builder() .itemId(itemId) .widgetType(widgetType) .adLanguage(adLanguage) .position(-1); // // Extract change actions for (final JSONPatchEvent<DashboardItemPatchPath> event : events) { if (!event.isReplace()) { throw new AdempiereException("Invalid event operation").setParameter("event", event); } final DashboardItemPatchPath path = event.getPath(); if (DashboardItemPatchPath.caption.equals(path)) { final String caption = event.getValueAsString(); changeRequestBuilder.caption(caption); } else if (DashboardItemPatchPath.interval.equals(path)) { final JSONInterval interval = event.getValueAsEnum(JsonUserDashboardItemAddRequest.JSONInterval.class); changeRequestBuilder.interval(interval); } else if (DashboardItemPatchPath.when.equals(path)) { final JSONWhen when = event.getValueAsEnum(JsonUserDashboardItemAddRequest.JSONWhen.class); changeRequestBuilder.when(when); } else if (DashboardItemPatchPath.position.equals(path)) { final int position = event.getValueAsInteger(-1); changeRequestBuilder.position(position);
} else { throw new AdempiereException("Unknown path").setParameter("event", event).setParameter("availablePaths", Arrays.asList(DashboardItemPatchPath.values())); } } final UserDashboardItemChangeRequest changeRequest = changeRequestBuilder.build(); if (changeRequest.isEmpty()) { throw new AdempiereException("no changes to perform").setParameter("events", events); } return changeRequest; } @Nullable UserDashboardItemId itemId; @NonNull DashboardWidgetType widgetType; @NonNull String adLanguage; // Changes String caption; JSONInterval interval; JSONWhen when; int position; public boolean isEmpty() { return Check.isEmpty(caption, true) && interval == null && when == null && position < 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardItemChangeRequest.java
1
请完成以下Java代码
private void getAllArticlesHandler(RoutingContext routingContext) { vertx.eventBus() .<String>send(ArticleRecipientVerticle.GET_ALL_ARTICLES, "", result -> { if (result.succeeded()) { routingContext.response() .putHeader("content-type", "application/json") .setStatusCode(200) .end(result.result() .body()); } else { routingContext.response() .setStatusCode(500) .end(); } });
} @Override public void start() throws Exception { super.start(); Router router = Router.router(vertx); router.get("/api/baeldung/articles") .handler(this::getAllArticlesHandler); vertx.createHttpServer() .requestHandler(router::accept) .listen(config().getInteger("http.port", defaultPort)); } }
repos\tutorials-master\vertx-modules\spring-vertx\src\main\java\com\baeldung\vertxspring\verticles\ServerVerticle.java
1
请完成以下Java代码
public int getWithholding_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Withholding_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getWriteOff_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setWriteOff_A(org.compiere.model.I_C_ValidCombination WriteOff_A) { set_ValueFromPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, WriteOff_A); } /** Set Forderungsverluste. @param WriteOff_Acct Konto für Forderungsverluste
*/ @Override public void setWriteOff_Acct (int WriteOff_Acct) { set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct)); } /** Get Forderungsverluste. @return Konto für Forderungsverluste */ @Override public int getWriteOff_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Default.java
1
请完成以下Java代码
public class KafkaResourceHolder<K, V> extends ResourceHolderSupport { private final Producer<K, V> producer; private final Duration closeTimeout; private boolean committed; /** * Construct an instance for the producer. * @param producer the producer. * @param closeTimeout the close timeout. */ public KafkaResourceHolder(Producer<K, V> producer, Duration closeTimeout) { Assert.notNull(producer, "'producer' cannot be null"); Assert.notNull(closeTimeout, "'closeTimeout' cannot be null"); this.producer = producer; this.closeTimeout = closeTimeout; } public Producer<K, V> getProducer() { return this.producer; } public void commit() {
if (!this.committed) { this.producer.commitTransaction(); this.committed = true; } } public void close() { this.producer.close(this.closeTimeout); } public void rollback() { this.producer.abortTransaction(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaResourceHolder.java
1
请完成以下Java代码
public static void writeProcess(Process process, XMLStreamWriter xtw) throws Exception { // start process element xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_PROCESS, BPMN2_NAMESPACE); xtw.writeAttribute(ATTRIBUTE_ID, process.getId()); if (StringUtils.isNotEmpty(process.getName())) { xtw.writeAttribute(ATTRIBUTE_NAME, process.getName()); } xtw.writeAttribute(ATTRIBUTE_PROCESS_EXECUTABLE, Boolean.toString(process.isExecutable())); if (!process.getCandidateStarterUsers().isEmpty()) { xtw.writeAttribute( ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_PROCESS_CANDIDATE_USERS, BpmnXMLUtil.convertToDelimitedString(process.getCandidateStarterUsers()) ); } if (!process.getCandidateStarterGroups().isEmpty()) { xtw.writeAttribute( ACTIVITI_EXTENSIONS_PREFIX, ACTIVITI_EXTENSIONS_NAMESPACE,
ATTRIBUTE_PROCESS_CANDIDATE_GROUPS, BpmnXMLUtil.convertToDelimitedString(process.getCandidateStarterGroups()) ); } // write custom attributes BpmnXMLUtil.writeCustomAttributes(process.getAttributes().values(), xtw, defaultProcessAttributes); if (StringUtils.isNotEmpty(process.getDocumentation())) { xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_DOCUMENTATION, BPMN2_NAMESPACE); xtw.writeCharacters(process.getDocumentation()); xtw.writeEndElement(); } boolean didWriteExtensionStartElement = ActivitiListenerExport.writeListeners(process, false, xtw); didWriteExtensionStartElement = BpmnXMLUtil.writeExtensionElements(process, didWriteExtensionStartElement, xtw); if (didWriteExtensionStartElement) { // closing extensions element xtw.writeEndElement(); } LaneExport.writeLanes(process, xtw); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\export\ProcessExport.java
1
请完成以下Java代码
public ResponseEntity<Resource> exportToExcel( @PathVariable("windowId") final String windowIdStr, @PathVariable(PARAM_ViewId) final String viewIdStr, @RequestParam(name = "selectedIds", required = false) @Parameter(description = "comma separated IDs") final String selectedIdsListStr) throws Exception { userSession.assertLoggedIn(); final ViewId viewId = ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr)); final ExcelFormat excelFormat = ExcelFormats.getDefaultFormat(); final File tmpFile = File.createTempFile("exportToExcel", "." + excelFormat.getFileExtension()); try (final FileOutputStream out = new FileOutputStream(tmpFile)) { ViewExcelExporter.builder() .excelFormat(excelFormat) .view(viewsRepo.getView(viewId)) .rowIds(DocumentIdsSelection.ofCommaSeparatedString(selectedIdsListStr)) .layout(viewsRepo.getViewLayout(viewId.getWindowId(), JSONViewDataType.grid, ViewProfileId.NULL, userSession.getUserRolePermissionsKey()))
.language(userSession.getLanguage()) .zoneId(userSession.getTimeZone()) .build() .export(out); } final String filename = "report." + excelFormat.getFileExtension(); // TODO: use a better name final String contentType = MimeType.getMimeType(filename); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(contentType)); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return new ResponseEntity<>(new InputStreamResource(Files.newInputStream(tmpFile.toPath())), headers, HttpStatus.OK); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRestController.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isAbleToStore(Object value) { if (value == null) { return true; } return mappings.isJPAEntity(value); } @Override public void setValue(Object value, ValueFields valueFields) { EntityManagerSession entityManagerSession = Context.getCommandContext().getSession(EntityManagerSession.class); if (entityManagerSession == null) { throw new FlowableException("Cannot set JPA variable: " + EntityManagerSession.class + " not configured"); } else { // Before we set the value we must flush all pending changes from // the entitymanager // If we don't do this, in some cases the primary key will not yet // be set in the object // which will cause exceptions down the road. entityManagerSession.flush(); } if (value != null) { String className = mappings.getJPAClassString(value); String idString = mappings.getJPAIdString(value); valueFields.setTextValue(className); valueFields.setTextValue2(idString);
} else { valueFields.setTextValue(null); valueFields.setTextValue2(null); } } @Override public Object getValue(ValueFields valueFields) { if (valueFields.getTextValue() != null && valueFields.getTextValue2() != null) { return mappings.getJPAEntity(valueFields.getTextValue(), valueFields.getTextValue2()); } return null; } /** * Force the value to be cacheable. */ @Override public void setForceCacheable(boolean forceCachedValue) { this.forceCacheable = forceCachedValue; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JPAEntityVariableType.java
2
请完成以下Java代码
public String toString() { return toETagString(); } public String toETagString() { String etagString = _etagString; if (etagString == null) { _etagString = etagString = buildETagString(); } return etagString; } private String buildETagString() { final StringBuilder etagString = new StringBuilder(); etagString.append("v=").append(version); if (!attributes.isEmpty()) { final String attributesStr = attributes.entrySet() .stream() .sorted(Comparator.comparing(entry -> entry.getKey())) .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.joining("#")); etagString.append("#").append(attributesStr); } return etagString.toString(); }
public final ETag overridingAttributes(final Map<String, String> overridingAttributes) { if (overridingAttributes.isEmpty()) { return this; } if (attributes.isEmpty()) { return new ETag(version, ImmutableMap.copyOf(overridingAttributes)); } final Map<String, String> newAttributes = new HashMap<>(attributes); newAttributes.putAll(overridingAttributes); return new ETag(version, ImmutableMap.copyOf(newAttributes)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETag.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricVariableInstanceResponse { protected String id; protected String processInstanceId; protected String processInstanceUrl; protected String taskId; protected String executionId; protected RestVariable variable; @ApiModelProperty(example = "14") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "6") public String getTaskId() {
return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public RestVariable getVariable() { return variable; } public void setVariable(RestVariable variable) { this.variable = variable; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricVariableInstanceResponse.java
2
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getTypeRef() { return typeRefAttribute.getValue(this); } public void setTypeRef(String typeRef) { typeRefAttribute.setValue(this, typeRef); } public OutputValues getOutputValues() { return outputValuesChild.getChild(this); } public void setOutputValues(OutputValues outputValues) { outputValuesChild.setChild(this, outputValues); } public DefaultOutputEntry getDefaultOutputEntry() { return defaultOutputEntryChild.getChild(this); } public void setDefaultOutputEntry(DefaultOutputEntry defaultOutputEntry) { defaultOutputEntryChild.setChild(this, defaultOutputEntry); }
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(OutputClause.class, DMN_ELEMENT_OUTPUT_CLAUSE) .namespaceUri(LATEST_DMN_NS) .extendsType(DmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<OutputClause>() { public OutputClause newInstance(ModelTypeInstanceContext instanceContext) { return new OutputClauseImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAME) .build(); typeRefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_REF) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); outputValuesChild = sequenceBuilder.element(OutputValues.class) .build(); defaultOutputEntryChild = sequenceBuilder.element(DefaultOutputEntry.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\OutputClauseImpl.java
1
请完成以下Java代码
public @Nullable String getRegexp() { return this.regexp; } public Config setRegexp(@Nullable String regexp) { this.regexp = regexp; return this; } public @Nullable Predicate<String> getPredicate() { return this.predicate; } public Config setPredicate(Predicate<String> predicate) { this.predicate = predicate; return this; }
/** * Enforces the validation done on predicate configuration: {@link #regexp} and * {@link #predicate} can't be both set at runtime. * @return <code>false</code> if {@link #regexp} and {@link #predicate} are both * set in this predicate factory configuration */ @AssertTrue public boolean isValid() { return !(StringUtils.hasText(this.regexp) && this.predicate != null); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\QueryRoutePredicateFactory.java
1
请完成以下Java代码
public class C_Order_CreateForAllMembers extends JavaProcess { final MembershipOrderService membershipOrderService = SpringContextHolder.instance.getBean(MembershipOrderService.class); @Param(parameterName = I_AD_Org.COLUMNNAME_AD_Org_ID, mandatory = true) private OrgId p_orgId; @Param(parameterName = I_M_Product.COLUMNNAME_M_Product_ID, mandatory = true) private ProductId p_productId; @Param(parameterName = I_C_Flatrate_Term.COLUMNNAME_StartDate, mandatory = true) private Instant p_startDate; @Param(parameterName = I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Conditions_ID, mandatory = true) private ConditionsId p_conditionsId;
@Override protected String doIt() throws Exception { final MembershipOrderCreateRequest request = MembershipOrderCreateRequest.builder() .orgId(p_orgId) .productId(p_productId) .conditionsID(p_conditionsId) .startDate(p_startDate) .build(); membershipOrderService.createMembershipContractOrders(request); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\process\C_Order_CreateForAllMembers.java
1
请完成以下Java代码
class TableChecker { static void printAllTables(Connection connection, String tableName) throws SQLException { DatabaseMetaData databaseMetaData = connection.getMetaData(); ResultSet resultSet = databaseMetaData.getTables(null, null, tableName, new String[] {"TABLE"}); while (resultSet.next()) { String name = resultSet.getString("TABLE_NAME"); String schema = resultSet.getString("TABLE_SCHEM"); System.out.println(name + " on schema " + schema); } } static boolean tableExists(Connection connection, String tableName) throws SQLException { DatabaseMetaData meta = connection.getMetaData(); ResultSet resultSet = meta.getTables(null, null, tableName, new String[] {"TABLE"});
return resultSet.next(); } static boolean tableExistsSQL(Connection connection, String tableName) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) " + "FROM information_schema.tables " + "WHERE table_name = ?" + "LIMIT 1;"); preparedStatement.setString(1, tableName); ResultSet resultSet = preparedStatement.executeQuery(); resultSet.next(); return resultSet.getInt(1) != 0; } }
repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\tableexists\TableChecker.java
1
请完成以下Java代码
public String getHU_UnitType() { return huUnitType; } @Override public void setHU_UnitType(final String huUnitType) { this.huUnitType = huUnitType; } @Override public boolean isAllowVirtualPI() { return allowVirtualPI; } @Override public void setAllowVirtualPI(final boolean allowVirtualPI) { this.allowVirtualPI = allowVirtualPI; } @Override public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI) { this.oneConfigurationPerPI = oneConfigurationPerPI; } @Override public boolean isOneConfigurationPerPI() { return oneConfigurationPerPI; } @Override public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public void setAllowDifferentCapacities(final boolean allowDifferentCapacities) {
this.allowDifferentCapacities = allowDifferentCapacities; } @Override public boolean isAllowInfiniteCapacity() { return allowInfiniteCapacity; } @Override public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity) { this.allowInfiniteCapacity = allowInfiniteCapacity; } @Override public boolean isAllowAnyPartner() { return allowAnyPartner; } @Override public void setAllowAnyPartner(final boolean allowAnyPartner) { this.allowAnyPartner = allowAnyPartner; } @Override public int getM_Product_Packaging_ID() { return packagingProductId; } @Override public void setM_Product_Packaging_ID(final int packagingProductId) { this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
1
请完成以下Java代码
private void assertEnabled() { if (!checkEnabled()) { throw new AdempiereException("Action is not enabled"); } } private void save() { assertEnabled(); final GridController gc = parent.getCurrentGridController(); save(gc); for (final GridController child : gc.getChildGridControllers()) { save(child); } } private void save(final GridController gc) { Check.assumeNotNull(gc, "gc not null"); final GridTab gridTab = gc.getMTab(); final VTable table = gc.getVTable();
// // Check CTable to GridTab synchronizer final CTableColumns2GridTabSynchronizer synchronizer = CTableColumns2GridTabSynchronizer.get(table); if (synchronizer == null) { // synchronizer does not exist, nothing to save return; } // // Make sure we have the latest values in GridTab synchronizer.saveToGridTab(); // // Ask model to settings to database model.save(gridTab); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveState.java
1
请完成以下Java代码
public class ConsumerMain { private static Consumer<String, String> createConsumer() { // 设置 Producer 的属性 Properties properties = new Properties(); properties.put("bootstrap.servers", "127.0.0.1:9092"); // 设置 Broker 的地址 properties.put("group.id", "demo-consumer-group"); // 消费者分组 properties.put("auto.offset.reset", "earliest"); // 设置消费者分组最初的消费进度为 earliest 。可参考博客 https://blog.csdn.net/lishuangzhe7047/article/details/74530417 理解 properties.put("enable.auto.commit", true); // 是否自动提交消费进度 properties.put("auto.commit.interval.ms", "1000"); // 自动提交消费进度频率 properties.put("key.deserializer", StringDeserializer.class.getName()); // 消息的 key 的反序列化方式 properties.put("value.deserializer", StringDeserializer.class.getName()); // 消息的 value 的反序列化方式 // 创建 KafkaProducer 对象 // 因为我们消息的 key 和 value 都使用 String 类型,所以创建的 Producer 是 <String, String> 的泛型。 return new KafkaConsumer<>(properties); } public static void main(String[] args) { // 创建 KafkaConsumer 对象 Consumer<String, String> consumer = createConsumer(); // 订阅消息
consumer.subscribe(Collections.singleton("TestTopic")); // 拉取消息 while (true) { // 拉取消息。如果拉取不到消息,阻塞等待最多 10 秒,或者等待拉取到消息。 ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); // 遍历处理消息 records.forEach(new java.util.function.Consumer<ConsumerRecord>() { @Override public void accept(ConsumerRecord record) { System.out.println(record.key() + "\t" + record.value()); } }); } } }
repos\SpringBoot-Labs-master\lab-03-kafka\lab-03-kafka-native\src\main\java\cn\iocoder\springboot\lab03\kafkademo\ConsumerMain.java
1
请完成以下Java代码
public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Service date. @param ServiceDate Date service was provided */ public void setServiceDate (Timestamp ServiceDate) { set_Value (COLUMNNAME_ServiceDate, ServiceDate); } /** Get Service date. @return Date service was provided */ public Timestamp getServiceDate () { return (Timestamp)get_Value(COLUMNNAME_ServiceDate); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from.
@return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java
1
请完成以下Java代码
public class DecisionTableEvaluationBuilderImpl implements DecisionEvaluationBuilder { private final static DecisionLogger LOG = ProcessEngineLogger.DECISION_LOGGER; protected CommandExecutor commandExecutor; protected String decisionDefinitionKey; protected String decisionDefinitionId; protected Integer version; protected Map<String, Object> variables; protected String decisionDefinitionTenantId; protected boolean isTenantIdSet = false; public DecisionTableEvaluationBuilderImpl(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } public DecisionEvaluationBuilder variables(Map<String, Object> variables) { this.variables = variables; return this; } public DecisionEvaluationBuilder version(Integer version) { this.version = version; return this; } public DecisionEvaluationBuilder decisionDefinitionTenantId(String tenantId) { this.decisionDefinitionTenantId = tenantId; isTenantIdSet = true; return this; } public DecisionEvaluationBuilder decisionDefinitionWithoutTenantId() { this.decisionDefinitionTenantId = null; isTenantIdSet = true; return this; } public DmnDecisionTableResult evaluate() { ensureOnlyOneNotNull(NotValidException.class, "either decision definition id or key must be set", decisionDefinitionId, decisionDefinitionKey); if (isTenantIdSet && decisionDefinitionId != null) { throw LOG.exceptionEvaluateDecisionDefinitionByIdAndTenantId(); } try { return commandExecutor.execute(new EvaluateDecisionTableCmd(this));
} catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (DecisionDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } } public static DecisionEvaluationBuilder evaluateDecisionTableByKey(CommandExecutor commandExecutor, String decisionDefinitionKey) { DecisionTableEvaluationBuilderImpl builder = new DecisionTableEvaluationBuilderImpl(commandExecutor); builder.decisionDefinitionKey = decisionDefinitionKey; return builder; } public static DecisionEvaluationBuilder evaluateDecisionTableById(CommandExecutor commandExecutor, String decisionDefinitionId) { DecisionTableEvaluationBuilderImpl builder = new DecisionTableEvaluationBuilderImpl(commandExecutor); builder.decisionDefinitionId = decisionDefinitionId; return builder; } // getters //////////////////////////////////// public String getDecisionDefinitionKey() { return decisionDefinitionKey; } public String getDecisionDefinitionId() { return decisionDefinitionId; } public Integer getVersion() { return version; } public Map<String, Object> getVariables() { return variables; } public String getDecisionDefinitionTenantId() { return decisionDefinitionTenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\DecisionTableEvaluationBuilderImpl.java
1
请完成以下Java代码
protected CostDetailCreateResult createCostForMaterialReceipt_NonMaterialCosts(CostDetailCreateRequest request) { throw new AdempiereException("Costing method " + getCostingMethod() + " does not support non material costs receipt") .setParameter("request", request) .appendParametersToMessage(); } protected abstract CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request); @Override public CostDetailAdjustment recalculateCostDetailAmountAndUpdateCurrentCost( @NonNull final CostDetail costDetail, @NonNull final CurrentCost currentCost) { if (costDetail.getDocumentRef().isCostRevaluationLine()) { throw new AdempiereException(MSG_RevaluatingAnotherRevaluationIsNotSupported) .setParameter("costDetail", costDetail); } final CurrencyPrecision precision = currentCost.getPrecision(); final Quantity qty = costDetail.getQty(); final CostAmount oldCostAmount = costDetail.getAmt(); final CostAmount oldCostPrice = qty.signum() != 0 ? oldCostAmount.divide(qty, precision) : oldCostAmount;
final CostAmount newCostPrice = currentCost.getCostPrice().toCostAmount(); final CostAmount newCostAmount = qty.signum() != 0 ? newCostPrice.multiply(qty).roundToPrecisionIfNeeded(precision) : newCostPrice.roundToPrecisionIfNeeded(precision); if (costDetail.isInboundTrx()) { currentCost.addWeightedAverage(newCostAmount, qty, utils.getQuantityUOMConverter()); } else { currentCost.addToCurrentQtyAndCumulate(qty, newCostAmount, utils.getQuantityUOMConverter()); } // return CostDetailAdjustment.builder() .costDetailId(costDetail.getId()) .qty(qty) .oldCostPrice(oldCostPrice) .oldCostAmount(oldCostAmount) .newCostPrice(newCostPrice) .newCostAmount(newCostAmount) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\CostingMethodHandlerTemplate.java
1
请完成以下Java代码
public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProductPriceInStockUOM (final BigDecimal ProductPriceInStockUOM) { set_ValueNoCheck (COLUMNNAME_ProductPriceInStockUOM, ProductPriceInStockUOM); } @Override public BigDecimal getProductPriceInStockUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ProductPriceInStockUOM); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_ValueNoCheck (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_ValueNoCheck (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_purchase_prices_in_stock_uom_plv_v.java
1
请完成以下Java代码
private Quantity getCurrentTURemainingQty() { if (capacity.isInfiniteCapacity()) { return Quantity.infinite(capacity.getC_UOM()); } Quantity qtyRemaining = capacity.toQuantity(); if (this._currentTUQty != null) { qtyRemaining = qtyRemaining.subtract(this._currentTUQty); } return qtyRemaining; } private I_M_HU getOrCreateCurrentTU() { if (_currentTU == null) { _currentTU = newHUBuilder().create(tuPI); } return _currentTU; } private void closeCurrentTUIfCapacityExceeded() { if (_currentTU != null && getCurrentTURemainingQty().signum() <= 0) { closeCurrentTU(); } } void closeCurrentTU() { if (_currentTU != null && _currentAttributes != null) { final IAttributeStorage tuAttributes = getAttributeStorage(_currentTU); tuAttributes.setSaveOnChange(true); _currentAttributes.updateAggregatedValuesTo(tuAttributes); } _currentTU = null; _currentTUQty = null; _currentAttributes = null; } private void addToCurrentTUQty(final Quantity qtyToAdd) { Check.assumeNotNull(_currentTU, "current TU is created");
if (this._currentTUQty == null) { this._currentTUQty = Quantity.zero(capacity.getC_UOM()); } this._currentTUQty = this._currentTUQty.add(qtyToAdd); } private IHUBuilder newHUBuilder() { final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext); huBuilder.setLocatorId(locatorId); if (!Check.isEmpty(huStatus, true)) { huBuilder.setHUStatus(huStatus); } if (bpartnerId != null) { huBuilder.setBPartnerId(bpartnerId); } if (bpartnerLocationRepoId > 0) { huBuilder.setC_BPartner_Location_ID(bpartnerLocationRepoId); } huBuilder.setHUPlanningReceiptOwnerPM(true); huBuilder.setHUClearanceStatusInfo(clearanceStatusInfo); return huBuilder; } private I_M_HU splitCU(final I_M_HU fromCU, final ProductId cuProductId, final Quantity qtyToSplit) { Check.assume(qtyToSplit.signum() > 0, "qtyToSplit shall be greater than zero but it was {}", qtyToSplit); final HUProducerDestination destination = HUProducerDestination.ofVirtualPI(); HULoader.builder() .source(HUListAllocationSourceDestination.of(fromCU)) .destination(destination) .load(AllocationUtils.builder() .setHUContext(huContext) .setProduct(cuProductId) .setQuantity(qtyToSplit) .setForceQtyAllocation(false) // no need to force .setClearanceStatusInfo(clearanceStatusInfo) .create()); return CollectionUtils.singleElement(destination.getCreatedHUs()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TULoaderInstance.java
1
请完成以下Java代码
public class ParallelPrefixBenchmark { private static final int ARRAY_SIZE = 200_000_000; @State(Scope.Benchmark) public static class BigArray { int[] data; @Setup(Level.Iteration) public void prepare() { data = new int[ARRAY_SIZE]; for(int j = 0; j< ARRAY_SIZE; j++) { data[j] = 1; } } @TearDown(Level.Iteration) public void destroy() { data = null; }
} @Benchmark public void largeArrayLoopSum(BigArray bigArray, Blackhole blackhole) { for (int i = 0; i < ARRAY_SIZE - 1; i++) { bigArray.data[i + 1] += bigArray.data[i]; } blackhole.consume(bigArray.data); } @Benchmark public void largeArrayParallelPrefixSum(BigArray bigArray, Blackhole blackhole) { Arrays.parallelPrefix(bigArray.data, (left, right) -> left + right); blackhole.consume(bigArray.data); } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\arrays\ParallelPrefixBenchmark.java
1
请完成以下Java代码
public class LotNumberBL implements ILotNumberBL { @Override public String calculateLotNumber(final Date date) { final StringBuilder lotNumber = new StringBuilder(); final int weekNumber = TimeUtil.getWeekNumber(date); if (weekNumber < 10) { lotNumber.append(0); } lotNumber.append(weekNumber); final int dayOfWeek = TimeUtil.getDayOfWeek(date); lotNumber.append(dayOfWeek); return lotNumber.toString(); } @Override public Optional<String> getAndIncrementLotNo(@NonNull final LotNoContext context) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String lotNo = documentNoFactory.forSequenceId(context.getSequenceId()) .setFailOnError(true) .setClientId(context.getClientId()) .setEvaluationContext(Evaluatees.empty()) .build();
return lotNo != null && !Objects.equals(lotNo, IDocumentNoBuilder.NO_DOCUMENTNO) ? Optional.of(lotNo) : Optional.empty(); } @Override public String getLotNumberAttributeValueOrNull(@NonNull final I_M_AttributeSetInstance asi) { final AttributeId lotNumberAttrId = Services.get(ILotNumberDateAttributeDAO.class).getLotNumberAttributeId(); if (lotNumberAttrId == null) { return null; } final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class); final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(asi.getM_AttributeSetInstance_ID()); final I_M_AttributeInstance lotNumberAI = asiBL.getAttributeInstance(asiId, lotNumberAttrId); if (lotNumberAI == null) { return null; } return lotNumberAI.getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\LotNumberBL.java
1
请完成以下Java代码
public void delete(final @NotNull Document processParameters) { throw new UnsupportedOperationException(); } @Override public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) { return VERSION_DEFAULT; } @Override public int retrieveLastLineNo(final DocumentQuery query) { throw new UnsupportedOperationException(); } private static final class ProcessInfoParameterDocumentValuesSupplier implements DocumentValuesSupplier { private final DocumentId adPInstanceId; private final Map<String, ProcessInfoParameter> processInfoParameters; public ProcessInfoParameterDocumentValuesSupplier(final DocumentId adPInstanceId, final Map<String, ProcessInfoParameter> processInfoParameters) { this.adPInstanceId = adPInstanceId; this.processInfoParameters = processInfoParameters; } @Override public DocumentId getDocumentId() {
return adPInstanceId; } @Override public String getVersion() { return VERSION_DEFAULT; } @Override public Object getValue(final DocumentFieldDescriptor parameterDescriptor) { return extractParameterValue(processInfoParameters, parameterDescriptor); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessParametersRepository.java
1
请完成以下Java代码
public Integer getMinPriority() { return minPriority; } public Integer getMaxPriority() { return maxPriority; } public String getAssigneeLike() { return assigneeLike; } public List<String> getAssigneeIds() { return assigneeIds; } public String getInvolvedUser() { return involvedUser; } public List<String> getInvolvedGroups() { return involvedGroups; } public String getOwner() { return owner; } public String getOwnerLike() { return ownerLike; } public String getTaskParentTaskId() { return taskParentTaskId; } public String getCategory() { return category; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public List<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getProcessDefinitionNameLike() { return processDefinitionNameLike; } public List<String> getProcessCategoryInList() { return processCategoryInList; } public List<String> getProcessCategoryNotInList() { return processCategoryNotInList; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getProcessInstanceBusinessKeyLike() {
return processInstanceBusinessKeyLike; } public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; } public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String db() { return obtain(InfluxProperties::getDb, InfluxConfig.super::db); } @Override public InfluxConsistency consistency() { return obtain(InfluxProperties::getConsistency, InfluxConfig.super::consistency); } @Override public @Nullable String userName() { return get(InfluxProperties::getUserName, InfluxConfig.super::userName); } @Override public @Nullable String password() { return get(InfluxProperties::getPassword, InfluxConfig.super::password); } @Override public @Nullable String retentionPolicy() { return get(InfluxProperties::getRetentionPolicy, InfluxConfig.super::retentionPolicy); } @Override public @Nullable Integer retentionReplicationFactor() { return get(InfluxProperties::getRetentionReplicationFactor, InfluxConfig.super::retentionReplicationFactor); } @Override public @Nullable String retentionDuration() { return get(InfluxProperties::getRetentionDuration, InfluxConfig.super::retentionDuration); } @Override public @Nullable String retentionShardDuration() { return get(InfluxProperties::getRetentionShardDuration, InfluxConfig.super::retentionShardDuration);
} @Override public String uri() { return obtain(InfluxProperties::getUri, InfluxConfig.super::uri); } @Override public boolean compressed() { return obtain(InfluxProperties::isCompressed, InfluxConfig.super::compressed); } @Override public boolean autoCreateDb() { return obtain(InfluxProperties::isAutoCreateDb, InfluxConfig.super::autoCreateDb); } @Override public InfluxApiVersion apiVersion() { return obtain(InfluxProperties::getApiVersion, InfluxConfig.super::apiVersion); } @Override public @Nullable String org() { return get(InfluxProperties::getOrg, InfluxConfig.super::org); } @Override public String bucket() { return obtain(InfluxProperties::getBucket, InfluxConfig.super::bucket); } @Override public @Nullable String token() { return get(InfluxProperties::getToken, InfluxConfig.super::token); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxPropertiesConfigAdapter.java
2
请完成以下Java代码
public void addCandidateUsers(CandidateUsersPayload candidateUsersPayload) { if (candidateUsersPayload.getCandidateUsers() != null && !candidateUsersPayload.getCandidateUsers().isEmpty()) { for (String u : candidateUsersPayload.getCandidateUsers()) { taskService.addCandidateUser(candidateUsersPayload.getTaskId(), u); } } } @Override public void deleteCandidateUsers(CandidateUsersPayload candidateUsersPayload) { if (candidateUsersPayload.getCandidateUsers() != null && !candidateUsersPayload.getCandidateUsers().isEmpty()) { for (String u : candidateUsersPayload.getCandidateUsers()) { taskService.deleteCandidateUser(candidateUsersPayload.getTaskId(), u); } } } @Override public void addCandidateGroups(CandidateGroupsPayload candidateGroupsPayload) { if ( candidateGroupsPayload.getCandidateGroups() != null && !candidateGroupsPayload.getCandidateGroups().isEmpty() ) { for (String g : candidateGroupsPayload.getCandidateGroups()) { taskService.addCandidateGroup(candidateGroupsPayload.getTaskId(), g); } } } @Override public void deleteCandidateGroups(CandidateGroupsPayload candidateGroupsPayload) { if ( candidateGroupsPayload.getCandidateGroups() != null && !candidateGroupsPayload.getCandidateGroups().isEmpty() ) { for (String g : candidateGroupsPayload.getCandidateGroups()) { taskService.deleteCandidateGroup(candidateGroupsPayload.getTaskId(), g); } } } @Override public List<String> userCandidates(String taskId) { List<IdentityLink> identityLinks = getIdentityLinks(taskId); List<String> userCandidates = new ArrayList<>(); if (identityLinks != null) { for (IdentityLink i : identityLinks) {
if (i.getUserId() != null) { if (i.getType().equals(IdentityLinkType.CANDIDATE)) { userCandidates.add(i.getUserId()); } } } } return userCandidates; } @Override public List<String> groupCandidates(String taskId) { List<IdentityLink> identityLinks = getIdentityLinks(taskId); List<String> groupCandidates = new ArrayList<>(); if (identityLinks != null) { for (IdentityLink i : identityLinks) { if (i.getGroupId() != null) { if (i.getType().equals(IdentityLinkType.CANDIDATE)) { groupCandidates.add(i.getGroupId()); } } } } return groupCandidates; } private List<IdentityLink> getIdentityLinks(String taskId) { return taskService.getIdentityLinksForTask(taskId); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskAdminRuntimeImpl.java
1
请完成以下Java代码
public void setM_Package_ID (int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID)); } /** Get Packstück. @return Shipment Package */ @Override public int getM_Package_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Package Content. @param PackageContent Package Content */ @Override public void setPackageContent (java.lang.String PackageContent) { set_Value (COLUMNNAME_PackageContent, PackageContent); } /** Get Package Content. @return Package Content */ @Override public java.lang.String getPackageContent () { return (java.lang.String)get_Value(COLUMNNAME_PackageContent); } /** Set Weight In Kg. @param WeightInKg Weight In Kg */ @Override public void setWeightInKg (int WeightInKg) { set_Value (COLUMNNAME_WeightInKg, Integer.valueOf(WeightInKg)); } /** Get Weight In Kg. @return Weight In Kg */
@Override public int getWeightInKg () { Integer ii = (Integer)get_Value(COLUMNNAME_WeightInKg); if (ii == null) return 0; return ii.intValue(); } /** Set Width In Cm. @param WidthInCm Width In Cm */ @Override public void setWidthInCm (int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, Integer.valueOf(WidthInCm)); } /** Get Width In Cm. @return Width In Cm */ @Override public int getWidthInCm () { Integer ii = (Integer)get_Value(COLUMNNAME_WidthInCm); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrderLine.java
1
请完成以下Java代码
public Expression getLoopCardinalityExpression() { return loopCardinalityExpression; } public void setLoopCardinalityExpression(Expression loopCardinalityExpression) { this.loopCardinalityExpression = loopCardinalityExpression; } public Expression getCompletionConditionExpression() { return completionConditionExpression; } public void setCompletionConditionExpression(Expression completionConditionExpression) { this.completionConditionExpression = completionConditionExpression; } public Expression getCollectionExpression() { return collectionExpression; } public void setCollectionExpression(Expression collectionExpression) { this.collectionExpression = collectionExpression; }
public String getCollectionVariable() { return collectionVariable; } public void setCollectionVariable(String collectionVariable) { this.collectionVariable = collectionVariable; } public String getCollectionElementVariable() { return collectionElementVariable; } public void setCollectionElementVariable(String collectionElementVariable) { this.collectionElementVariable = collectionElementVariable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1