instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Column(columnDefinition = "jsonb") private String attributes; public Product() { } public Product(String name, String attributes) { this.name = name; this.attributes = attributes; } public Long getId() { return id; } public void setId(Long id) { this.id = id;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAttributes() { return attributes; } public void setAttributes(String attributes) { this.attributes = attributes; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\queryjsonb\Product.java
2
请完成以下Java代码
public JobQuery unlocked() { this.onlyUnlocked = true; return this; } // sorting ////////////////////////////////////////// public JobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public JobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public JobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public JobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public JobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public JobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } // results ////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getJobEntityManager().findJobCountByQueryCriteria(this); } public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getJobEntityManager().findJobsByQueryCriteria(this, page); } // getters ////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return Context.getProcessEngineConfiguration().getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public static long getSerialversionuid() { return serialVersionUID; } public String getId() {
return id; } public String getProcessDefinitionId() { return processDefinitionId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } public boolean isNoRetriesLeft() { return noRetriesLeft; } public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
1
请完成以下Java代码
public java.lang.String getEftStatementReference() { return (java.lang.String)get_Value(COLUMNNAME_EftStatementReference); } @Override public void setEndingBalance (java.math.BigDecimal EndingBalance) { set_Value (COLUMNNAME_EndingBalance, EndingBalance); } @Override public java.math.BigDecimal getEndingBalance() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_EndingBalance); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setIsApproved (boolean IsApproved) { set_Value (COLUMNNAME_IsApproved, Boolean.valueOf(IsApproved)); } @Override public boolean isApproved() { return get_ValueAsBoolean(COLUMNNAME_IsApproved); } @Override public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } @Override public boolean isManual() { return get_ValueAsBoolean(COLUMNNAME_IsManual); } @Override public void setIsReconciled (boolean IsReconciled) { set_Value (COLUMNNAME_IsReconciled, Boolean.valueOf(IsReconciled)); } @Override public boolean isReconciled() { return get_ValueAsBoolean(COLUMNNAME_IsReconciled); } @Override public void setMatchStatement (java.lang.String MatchStatement) { set_Value (COLUMNNAME_MatchStatement, MatchStatement); } @Override public java.lang.String getMatchStatement() { return (java.lang.String)get_Value(COLUMNNAME_MatchStatement); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name);
} @Override public void setPosted (boolean Posted) { set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted)); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setStatementDate (java.sql.Timestamp StatementDate) { set_Value (COLUMNNAME_StatementDate, StatementDate); } @Override public java.sql.Timestamp getStatementDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementDate); } @Override public void setStatementDifference (java.math.BigDecimal StatementDifference) { set_Value (COLUMNNAME_StatementDifference, StatementDifference); } @Override public java.math.BigDecimal getStatementDifference() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StatementDifference); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BankStatement.java
1
请完成以下Java代码
public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); }
@Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请完成以下Java代码
public class TbGetOriginatorFieldsNode extends TbAbstractGetMappedDataNode<EntityId, TbGetOriginatorFieldsConfiguration> { protected final static String DATA_MAPPING_PROPERTY_NAME = "dataMapping"; protected static final String OLD_DATA_MAPPING_PROPERTY_NAME = "fieldsMapping"; @Override protected TbGetOriginatorFieldsConfiguration loadNodeConfiguration(TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbGetOriginatorFieldsConfiguration.class); checkIfMappingIsNotEmptyOrElseThrow(config.getDataMapping()); return config; } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { var msgDataAsJsonNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null; processFieldsData(ctx, msg, msg.getOriginator(), msgDataAsJsonNode, config.isIgnoreNullStrings()); }
@Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { if (fromVersion == 0) { var newConfigObjectNode = (ObjectNode) oldConfiguration; if (!newConfigObjectNode.has(OLD_DATA_MAPPING_PROPERTY_NAME)) { throw new TbNodeException("property to update: '" + OLD_DATA_MAPPING_PROPERTY_NAME + "' doesn't exists in configuration!"); } newConfigObjectNode.set(DATA_MAPPING_PROPERTY_NAME, newConfigObjectNode.get(OLD_DATA_MAPPING_PROPERTY_NAME)); newConfigObjectNode.remove(OLD_DATA_MAPPING_PROPERTY_NAME); newConfigObjectNode.put(FETCH_TO_PROPERTY_NAME, TbMsgSource.METADATA.name()); return new TbPair<>(true, newConfigObjectNode); } return new TbPair<>(false, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbGetOriginatorFieldsNode.java
1
请在Spring Boot框架中完成以下Java代码
public class PersistenceJPAConfigL2Cache { @Autowired private Environment env; public PersistenceJPAConfigL2Cache() { super(); } // beans @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan(getPackagesToScan()); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); em.setJpaProperties(additionalProperties()); return em; } protected String[] getPackagesToScan() { return new String[] { "com.baeldung.hibernate.cache.model" }; } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); return dataSource; }
@Bean public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(emf); return transactionManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); hibernateProperties.setProperty("hibernate.cache.region.factory_class", env.getProperty("hibernate.cache.region.factory_class")); hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\spring\PersistenceJPAConfigL2Cache.java
2
请完成以下Java代码
public class SimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler { public SimpleUrlAuthenticationSuccessHandler() { } /** * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base class. * @param defaultTargetUrl the URL to which the user should be redirected on * successful authentication. */ public SimpleUrlAuthenticationSuccessHandler(String defaultTargetUrl) { setDefaultTargetUrl(defaultTargetUrl); } /** * Calls the parent class {@code handle()} method to forward or redirect to the target * URL, and then calls {@code clearAuthenticationAttributes()} to remove any leftover * session data. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
handle(request, response, authentication); clearAuthenticationAttributes(request); } /** * Removes temporary authentication-related data which may have been stored in the * session during the authentication process. */ protected final void clearAuthenticationAttributes(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\SimpleUrlAuthenticationSuccessHandler.java
1
请完成以下Java代码
boolean containsEntry(String name) { if (name == null || name.isEmpty()) { return false; } return this.lines.contains(name); } List<URL> getUrls() { return this.lines.stream().map(this::asUrl).toList(); } private URL asUrl(String line) { try { return new File(this.root, line).toURI().toURL(); } catch (MalformedURLException ex) { throw new IllegalStateException(ex); } }
static ClassPathIndexFile loadIfPossible(File root, String location) throws IOException { return loadIfPossible(root, new File(root, location)); } private static ClassPathIndexFile loadIfPossible(File root, File indexFile) throws IOException { if (indexFile.exists() && indexFile.isFile()) { List<String> lines = Files.readAllLines(indexFile.toPath()) .stream() .filter(ClassPathIndexFile::lineHasText) .toList(); return new ClassPathIndexFile(root, lines); } return null; } private static boolean lineHasText(String line) { return !line.trim().isEmpty(); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\ClassPathIndexFile.java
1
请完成以下Spring Boot application配置
spring: task: # Spring Task 调度任务的配置,对应 TaskSchedulingProperties 配置类 scheduling: thread-name-prefix: pikaqiu-demo- # 线程池的线程名的前缀。默认为 scheduling- ,建议根据自己应用来设置 pool: size: 10 # 线程池大小。默认为 1 ,根据自己应用来设置 shutdown: await-termination: tru
e # 应用关闭时,是否等待定时任务执行完成。默认为 false ,建议设置为 true await-termination-period: 60 # 等待任务完成的最大时长,单位为秒。默认为 0 ,根据自己应用来设置
repos\SpringBoot-Labs-master\lab-28\lab-28-task-demo\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) { super(request); String sessionStream = getBodyString(request); body = sessionStream.getBytes(Charset.forName("UTF-8")); } /** * 获取请求Body * * @param request * @return */ public String getBodyString(final ServletRequest request) { StringBuilder sb = new StringBuilder(); try (InputStream inputStream = cloneInputStream(request.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")))) { String line; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } /** * Description: 复制输入流</br> * * @param inputStream * @return</br> */ public InputStream cloneInputStream(ServletInputStream inputStream) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while ((len = inputStream.read(buffer)) > -1) { byteArrayOutputStream.write(buffer, 0, len); } byteArrayOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } @Override public BufferedReader getReader() { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() {
final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() { return bais.read(); } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } }; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\BodyReaderHttpServletRequestWrapper.java
2
请完成以下Java代码
/* package */class IncludedHUsLocalCache extends AbstractModelListCacheLocal<I_M_HU_Item, I_M_HU> { private final transient IQueryBL queryBL = Services.get(IQueryBL.class); private static final IQueryOrderBy queryOrderBy; static { queryOrderBy = Services.get(IQueryBL.class) .createQueryOrderByBuilder(I_M_HU.class) .addColumn(I_M_HU.COLUMN_M_HU_ID, Direction.Ascending, Nulls.Last) .createQueryOrderBy(); } private static final String DYNATTR_Instance = IncludedHUsLocalCache.class.getName(); public static final IncludedHUsLocalCache getCreate(final I_M_HU_Item huItem) { IncludedHUsLocalCache cache = InterfaceWrapperHelper.getDynAttribute(huItem, DYNATTR_Instance); if (cache == null) { cache = new IncludedHUsLocalCache(huItem); // FIXME: this is making de.metas.customer.picking.service.impl.PackingServiceTest to fail cache.setCacheDisabled(HUConstants.DEBUG_07504_Disable_IncludedHUsLocalCache); InterfaceWrapperHelper.setDynAttribute(huItem, DYNATTR_Instance, cache); } return cache; } public IncludedHUsLocalCache(final I_M_HU_Item parentItem) { super(parentItem); } @Override protected Comparator<I_M_HU> createItemsComparator() { return queryOrderBy.getComparator(I_M_HU.class); } @Override protected List<I_M_HU> retrieveItems(final IContextAware ctx, final I_M_HU_Item parentItem) { final IQueryBuilder<I_M_HU> queryBuilder = queryBL .createQueryBuilder(I_M_HU.class, ctx) .addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, parentItem.getM_HU_Item_ID()) // Retrieve all HUs, even if they are not active. // We need this because in case of shipped HUs (HUStatus=E) those are also inactivated (IsActive=N). // see https://github.com/metasfresh/metasfresh-webui-api/issues/567.
// .addOnlyActiveRecordsFilter() ; final List<I_M_HU> hus = queryBuilder .create() .setOrderBy(queryOrderBy) .list(); // Make sure hu.getM_HU_Item_Parent() returns our parentItem for (final I_M_HU hu : hus) { hu.setM_HU_Item_Parent(parentItem); } return hus; } @Override protected final Object mkKey(final I_M_HU item) { return item.getM_HU_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\IncludedHUsLocalCache.java
1
请在Spring Boot框架中完成以下Java代码
FilterRegistrationBean<ServerHttpObservationFilter> webMvcObservationFilter(ObservationRegistry registry, ObjectProvider<ServerRequestObservationConvention> customConvention, ObservationProperties observationProperties) { String name = observationProperties.getHttp().getServer().getRequests().getName(); ServerRequestObservationConvention convention = customConvention .getIfAvailable(() -> new DefaultServerRequestObservationConvention(name)); ServerHttpObservationFilter filter = new ServerHttpObservationFilter(registry, convention); FilterRegistrationBean<ServerHttpObservationFilter> registration = new FilterRegistrationBean<>(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC); return registration; } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(MeterRegistry.class)
@ConditionalOnBean(MeterRegistry.class) static class MeterFilterConfiguration { @Bean @Order(0) MaximumAllowableTagsMeterFilter metricsHttpServerUriTagFilter(ObservationProperties observationProperties, MetricsProperties metricsProperties) { String meterNamePrefix = observationProperties.getHttp().getServer().getRequests().getName(); int maxUriTags = metricsProperties.getWeb().getServer().getMaxUriTags(); return new MaximumAllowableTagsMeterFilter(meterNamePrefix, "uri", maxUriTags); } } }
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\WebMvcObservationAutoConfiguration.java
2
请完成以下Java代码
public String getTextContent() { synchronized(document) { return element.getTextContent(); } } public void setTextContent(String textContent) { synchronized(document) { element.setTextContent(textContent); } } public void addCDataSection(String data) { synchronized (document) { CDATASection cdataSection = document.createCDATASection(data); element.appendChild(cdataSection); } } public ModelElementInstance getModelElementInstance() { synchronized(document) { return (ModelElementInstance) element.getUserData(MODEL_ELEMENT_KEY); } } public void setModelElementInstance(ModelElementInstance modelElementInstance) { synchronized(document) { element.setUserData(MODEL_ELEMENT_KEY, modelElementInstance, null); } } public String registerNamespace(String namespaceUri) { synchronized(document) { String lookupPrefix = lookupPrefix(namespaceUri); if (lookupPrefix == null) { // check if a prefix is known String prefix = XmlQName.KNOWN_PREFIXES.get(namespaceUri); // check if prefix is not already used if (prefix != null && getRootElement() != null && getRootElement().hasAttribute(XMLNS_ATTRIBUTE_NS_URI, prefix)) { prefix = null; } if (prefix == null) { // generate prefix prefix = ((DomDocumentImpl) getDocument()).getUnusedGenericNsPrefix(); } registerNamespace(prefix, namespaceUri); return prefix; } else { return lookupPrefix; } } } public void registerNamespace(String prefix, String namespaceUri) {
synchronized(document) { element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE + ":" + prefix, namespaceUri); } } public String lookupPrefix(String namespaceUri) { synchronized(document) { return element.lookupPrefix(namespaceUri); } } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DomElementImpl that = (DomElementImpl) o; return element.equals(that.element); } public int hashCode() { return element.hashCode(); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomElementImpl.java
1
请完成以下Java代码
public String getOperationType() { return operationType; } public String getEntityType() { return entityType; } public String getProperty() { return property; } public String getOrgValue() { return orgValue; } public String getNewValue() { return newValue; }
public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getCategory() { return category; } public String getAnnotation() { return annotation; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogEntryDto.java
1
请完成以下Java代码
Location getLocation() { return new Location(this.reader.getLineNumber(), this.columnNumber); } boolean isSameLastLineCommentPrefix() { return this.lastLineCommentPrefixCharacter == this.character; } boolean isCommentPrefixCharacter() { return this.character == '#' || this.character == '!'; } boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>(); void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) {
this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请完成以下Java代码
void alwaysFail() { throw new RuntimeException(); } @Contract(" -> fail") void doNothingWithWrongContract() { } @Contract("_, null -> null; null, _ -> param2; _, !null -> !null") String concatenateOnlyIfSecondArgumentIsNotNull(String head, String tail) { if (tail == null) { return null; } if (head == null) { return tail; } return head + tail; } void uselessNullCheck() { String head = "1234"; String tail = "5678"; String concatenation = concatenateOnlyIfSecondArgumentIsNotNull(head, tail); if (concatenation != null) { System.out.println(concatenation); } } void uselessNullCheckOnInferredAnnotation() { if (StringUtils.isEmpty(null)) { System.out.println("baeldung"); } } @Contract(pure = true) String replace(String string, char oldChar, char newChar) { return string.replace(oldChar, newChar); } @Contract(value = "true -> false; false -> true", pure = true) boolean not(boolean input) { return !input; } @Contract("true -> new") void contractExpectsWrongParameterType(List<Integer> integers) { } @Contract("_, _ -> new") void contractExpectsMoreParametersThanMethodHas(String s) { } @Contract("_ -> _; null -> !null") String secondContractClauseNotReachable(String s) { return ""; }
@Contract("_ -> true") void contractExpectsWrongReturnType(String s) { } // NB: the following examples demonstrate how to use the mutates attribute of the annotation // This attribute is currently experimental and could be changed or removed in the future @Contract(mutates = "param") void incrementArrayFirstElement(Integer[] integers) { if (integers.length > 0) { integers[0] = integers[0] + 1; } } @Contract(pure = true, mutates = "param") void impossibleToMutateParamInPureFunction(List<String> strings) { if (strings != null) { strings.forEach(System.out::println); } } @Contract(mutates = "param3") void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) { } @Contract(mutates = "param") void impossibleToMutableImmutableType(String s) { } @Contract(mutates = "this") static void impossibleToMutateThisInStaticMethod() { } }
repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isBPartnerDetailsActive(@NonNull final BPartnerId bpartnerId) { final ImmutableCollection<InvoiceProcessingServiceCompanyConfigBPartnerDetails> detailsList = bpartnerDetails.get(bpartnerId); if (detailsList.isEmpty()) { return false; } return detailsList.stream() .anyMatch(InvoiceProcessingServiceCompanyConfigBPartnerDetails::isActive); } public boolean isValid(@NonNull final ZonedDateTime validFrom) { return this.validFrom.isBefore(validFrom) || this.validFrom.isEqual(validFrom); } }
@Builder @Value /* package */ class InvoiceProcessingServiceCompanyConfigBPartnerDetails { @NonNull BPartnerId bpartnerId; @NonNull Percent percent; @Nullable DocTypeId docTypeId; @Default boolean isActive = true; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\invoiceProcessingServiceCompany\InvoiceProcessingServiceCompanyConfig.java
2
请在Spring Boot框架中完成以下Java代码
private void handleEvent(@NonNull final Exchange exchange, @NonNull final String message) { final String auditTrailEndpoint = exchange.getIn().getHeader(HEADER_AUDIT_TRAIL, String.class); if (EmptyUtil.isEmpty(auditTrailEndpoint)) { return; } AuditFileTrailUtil.computeAuditLogFileContent(exchange, message) .ifPresent(logFileContent -> producerTemplate.sendBody(getAuditEndpoint(exchange), logFileContent)); } @NonNull private static String extractEndpointURI(@Nullable final Endpoint endpoint) { return endpoint != null && Check.isNotBlank(endpoint.getEndpointUri()) ? endpoint.getEndpointUri() : "[Could not obtain endpoint information]"; } @NonNull private static String getAuditEndpoint(@NonNull final Exchange exchange) { final String auditTrailEndpoint = exchange.getIn().getHeader(HEADER_AUDIT_TRAIL, String.class);
if (EmptyUtil.isEmpty(auditTrailEndpoint)) { throw new RuntimeCamelException("auditTrailEndpoint cannot be empty at this point!"); } final String externalSystemValue = exchange.getIn().getHeader(HEADER_EXTERNAL_SYSTEM_VALUE, String.class); final String value = FileUtil.stripIllegalCharacters(externalSystemValue); final String traceId = CoalesceUtil.coalesceNotNull(exchange.getIn().getHeader(HEADER_TRACE_ID, String.class), UUID.randomUUID().toString()); final String auditFolderName = DateTimeFormatter.ofPattern("yyyy-MM-dd") .withZone(ZoneId.systemDefault()) .format(LocalDate.now()); final String auditFileNameTimeStamp = DateTimeFormatter.ofPattern("yyyy-MM-dd_HHmmssSSS") .withZone(ZoneId.systemDefault()) .format(Instant.now()); final String auditFileName = traceId + "_" + value + "_" + auditFileNameTimeStamp + ".txt"; return file(auditTrailEndpoint + "/" + auditFolderName + "/?fileName=" + auditFileName).getUri(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AuditEventNotifier.java
2
请完成以下Java代码
private TbMsg processSendMessageResult(TbMsg origMsg, SendMessageResult result) { TbMsgMetaData metaData = origMsg.getMetaData().copy(); metaData.putValue(MESSAGE_ID, result.getMessageId()); metaData.putValue(REQUEST_ID, result.getSdkResponseMetadata().getRequestId()); if (!StringUtils.isEmpty(result.getMD5OfMessageBody())) { metaData.putValue(MESSAGE_BODY_MD5, result.getMD5OfMessageBody()); } if (!StringUtils.isEmpty(result.getMD5OfMessageAttributes())) { metaData.putValue(MESSAGE_ATTRIBUTES_MD5, result.getMD5OfMessageAttributes()); } if (!StringUtils.isEmpty(result.getSequenceNumber())) { metaData.putValue(SEQUENCE_NUMBER, result.getSequenceNumber()); } return origMsg.transform() .metaData(metaData) .build(); } private TbMsg processException(TbMsg origMsg, Throwable t) { TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage()); return origMsg.transform() .metaData(metaData) .build(); } @Override public void destroy() { if (this.sqsClient != null) { try { this.sqsClient.shutdown(); } catch (Exception e) { log.error("Failed to shutdown SQS client during destroy()", e); } } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\sqs\TbSqsNode.java
1
请完成以下Java代码
public String normalizeDBIdentifier(@NonNull final String dbIdentifier, @NonNull final DatabaseMetaData md) { try { if (md.storesUpperCaseIdentifiers()) { return dbIdentifier.toUpperCase(); } else if (md.storesLowerCaseIdentifiers()) { return dbIdentifier.toLowerCase(); } else { return dbIdentifier; } } catch (final SQLException ex) { throw new DBException(ex); } } public boolean isDBColumnPresent(@NonNull final String tableName, @NonNull final String columnName) { final String catalog = getDatabase().getCatalog(); final String schema = getDatabase().getSchema(); String tableNameNorm = tableName; String columnNameNorm = columnName; Connection conn = null; ResultSet rs = null; try { conn = getConnectionRO(); final DatabaseMetaData md = conn.getMetaData(); tableNameNorm = normalizeDBIdentifier(tableName, md); columnNameNorm = normalizeDBIdentifier(columnName, md); // rs = md.getColumns(catalog, schema, tableNameNorm, columnNameNorm); return rs.next(); } catch (final SQLException ex) { throw new DBException(ex) .appendParametersToMessage() .setParameter("catalog", catalog) .setParameter("schema", schema) .setParameter("tableNameNorm", tableNameNorm) .setParameter("columnNameNorm", columnNameNorm); } finally { DB.close(rs); DB.close(conn); } } /** * @param sqlStatement SQL statement to be executed * @param parameters Parameters to be used in the {@param sqlStatement} * @param trxName transaction name * @return each resulted row as a {@link List<String>} */ public ImmutableList<List<String>> getSQL_ResultRowsAsListsOfStrings(final String sqlStatement, final List<Object> parameters, final String trxName) { List<List<String>> result = null; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = prepareStatement(sqlStatement, trxName); setParameters(pstmt, parameters);
rs = pstmt.executeQuery(); final int columnsCount = rs.getMetaData().getColumnCount(); if (columnsCount > 0) { result = new ArrayList<>(); while (rs.next()) { final List<String> row = new ArrayList<>(); for (int i = 1; i <= columnsCount; i++) { row.add(rs.getString(i)); } result.add(row); } } } catch (final SQLException sqlException) { throw new DBException(sqlException, sqlStatement, parameters); } finally { DB.close(rs, pstmt); } return result != null ? ImmutableList.copyOf(result) : ImmutableList.of(); } } // DB
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\DB.java
1
请在Spring Boot框架中完成以下Java代码
public ModelAndView exportXls(HttpServletRequest request, AiragModel airagModel) { return super.exportXls(request, airagModel, AiragModel.class, "AiRag模型配置"); } /** * 通过excel导入数据 * * @param request * @param response * @return */ @RequestMapping(value = "/importExcel", method = RequestMethod.POST) public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, AiragModel.class); } @PostMapping(value = "/test") public Result<?> test(@RequestBody AiragModel airagModel) { // 验证 模型名称/模型类型/基础模型 AssertUtils.assertNotEmpty("模型名称不能为空", airagModel.getName());
AssertUtils.assertNotEmpty("模型类型不能为空", airagModel.getModelType()); AssertUtils.assertNotEmpty("基础模型不能为空", airagModel.getModelName()); try { if(LLMConsts.MODEL_TYPE_LLM.equals(airagModel.getModelType())){ aiChatHandler.completions(airagModel, Collections.singletonList(UserMessage.from("To test whether it can be successfully called, simply return success")), null); }else{ AiModelOptions aiModelOptions = EmbeddingHandler.buildModelOptions(airagModel); EmbeddingModel embeddingModel = AiModelFactory.createEmbeddingModel(aiModelOptions); embeddingModel.embed("test text"); } }catch (Exception e){ log.error("测试模型连接失败", e); return Result.error("测试模型连接失败,请检查模型配置是否正确!"); } // 测试成功激活数据 airagModel.setActivateFlag(1); airagModelService.updateById(airagModel); return Result.OK(""); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\controller\AiragModelController.java
2
请完成以下Java代码
public class TeacherUtils { private static List<Teacher> teachers = new ArrayList<Teacher>(); public static List<Teacher> buildTeachers() { if (teachers.isEmpty()) { Teacher teacher1 = new Teacher(); teacher1.setId(2001); teacher1.setName("Jane Doe"); teacher1.setGender("F"); teacher1.setActive(true); teacher1.getCourses().add("Mathematics"); teacher1.getCourses().add("Physics"); teachers.add(teacher1); Teacher teacher2 = new Teacher(); teacher2.setId(2002); teacher2.setName("Lazy Dude"); teacher2.setGender("M"); teacher2.setActive(false); teacher2.setAdditionalSkills("emergency responder");
teachers.add(teacher2); Teacher teacher3 = new Teacher(); teacher3.setId(2002); teacher3.setName("Micheal Jordan"); teacher3.setGender("M"); teacher3.setActive(true); teacher3.getCourses().add("Sports"); teachers.add(teacher3); } return teachers; } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\utils\TeacherUtils.java
1
请完成以下Java代码
public class Employee { private int id; private String name; private Division division; private Date startDt; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) {
this.name = name; } public Division getDivision() { return division; } public void setDivision(Division division) { this.division = division; } public Date getStartDt() { return startDt; } public void setStartDt(Date startDt) { this.startDt = startDt; } }
repos\tutorials-master\mapstruct\src\main\java\com\baeldung\entity\Employee.java
1
请完成以下Java代码
public BigDecimal getTotalAmt() { return totalAmt; } @Override public BigDecimal getOpenAmt() { return openAmt; } @Override public Date getDueDate() { return (Date)dueDate.clone(); } @Override public Date getGraceDate() { if (graceDate == null) { return null; } return (Date)graceDate.clone(); } @Override public int getDaysDue() { return daysDue; } @Override public String getTableName() { return tableName; } @Override public int getRecordId() { return record_id;
} @Override public boolean isInDispute() { return inDispute; } @Override public String toString() { return "DunnableDoc [tableName=" + tableName + ", record_id=" + record_id + ", C_BPartner_ID=" + C_BPartner_ID + ", C_BPatner_Location_ID=" + C_BPatner_Location_ID + ", Contact_ID=" + Contact_ID + ", C_Currency_ID=" + C_Currency_ID + ", totalAmt=" + totalAmt + ", openAmt=" + openAmt + ", dueDate=" + dueDate + ", graceDate=" + graceDate + ", daysDue=" + daysDue + ", inDispute=" + inDispute + "]"; } @Override public String getDocumentNo() { return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunnableDoc.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("inOutLineId", inOutLineId) .toString(); } public int getM_InOutLine_ID() { return inOutLineId; } } private static final WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<InOutLineWithQualityIssues>(C_Request_CreateFromInout_Async.class) { @Override protected boolean isEligibleForScheduling(final InOutLineWithQualityIssues model) { return model != null && model.getM_InOutLine_ID() > 0; } ; @Override protected Properties extractCtxFromItem(final InOutLineWithQualityIssues item) { return Env.getCtx(); } @Override protected String extractTrxNameFromItem(final InOutLineWithQualityIssues item) { return ITrx.TRXNAME_ThreadInherited; } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final InOutLineWithQualityIssues item) { return TableRecordReference.of(I_M_InOutLine.Table_Name, item.getM_InOutLine_ID()); } };
@Override public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName) { // Services final IQueueDAO queueDAO = Services.get(IQueueDAO.class); final IRequestBL requestBL = Services.get(IRequestBL.class); // retrieve the items (inout lines) that were enqueued and put them in a list final List<I_M_InOutLine> lines = queueDAO.retrieveAllItems(workPackage, I_M_InOutLine.class); // for each line that was enqueued, create a R_Request containing the information from the inout line and inout for (final I_M_InOutLine line : lines) { requestBL.createRequestFromInOutLineWithQualityIssues(line); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\C_Request_CreateFromInout_Async.java
2
请完成以下Java代码
protected List<String> getMappingFiles() { List<CockpitPlugin> cockpitPlugins = pluginRegistry.getPlugins(); List<String> mappingFiles = new ArrayList<String>(); for (CockpitPlugin plugin: cockpitPlugins) { mappingFiles.addAll(plugin.getMappingFiles()); } return mappingFiles; } /** * Create command executor for the engine with the given name * * @param processEngineName
* @return */ protected CommandExecutor createCommandExecutor(String processEngineName) { ProcessEngine processEngine = getProcessEngine(processEngineName); if (processEngine == null) { throw new ProcessEngineException("No process engine with name " + processEngineName + " found."); } ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl)processEngine).getProcessEngineConfiguration(); List<String> mappingFiles = getMappingFiles(); return new CommandExecutorImpl(processEngineConfiguration, mappingFiles); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\DefaultCockpitRuntimeDelegate.java
1
请完成以下Java代码
public void setDefault() { setName("Default"); setMark1Percent (50); setAD_PrintColor1_ID (102); // red setMark2Percent (100); setAD_PrintColor2_ID (113); // yellow setMark3Percent (9999); setAD_PrintColor3_ID (103); // green } // setDefault /** * Before Save * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) { if (getMark1Percent() > getMark2Percent()) setMark1Percent(getMark2Percent()); if (getMark2Percent() > getMark3Percent() && getMark3Percent() != 0) setMark2Percent(getMark3Percent()); if (getMark3Percent() > getMark4Percent() && getMark4Percent() != 0) setMark4Percent(getMark4Percent()); // return true; } // beforeSave /** * Get Color * @param percent percent * @return color */ public Color getColor (int percent) { int AD_PrintColor_ID = 0; if (percent <= getMark1Percent() || getMark2Percent() == 0) AD_PrintColor_ID = getAD_PrintColor1_ID(); else if (percent <= getMark2Percent() || getMark3Percent() == 0) AD_PrintColor_ID = getAD_PrintColor2_ID(); else if (percent <= getMark3Percent() || getMark4Percent() == 0) AD_PrintColor_ID = getAD_PrintColor3_ID();
else AD_PrintColor_ID = getAD_PrintColor4_ID(); if (AD_PrintColor_ID == 0) { if (getAD_PrintColor3_ID() != 0) AD_PrintColor_ID = getAD_PrintColor3_ID(); else if (getAD_PrintColor2_ID() != 0) AD_PrintColor_ID = getAD_PrintColor2_ID(); else if (getAD_PrintColor1_ID() != 0) AD_PrintColor_ID = getAD_PrintColor1_ID(); } if (AD_PrintColor_ID == 0) return Color.black; // MPrintColor pc = MPrintColor.get(getCtx(), AD_PrintColor_ID); if (pc != null) return pc.getColor(); return Color.black; } // getColor /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MColorSchema["); sb.append (get_ID()).append ("-").append (getName()).append ("]"); return sb.toString (); } // toString } // MColorSchema
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MColorSchema.java
1
请完成以下Java代码
void updatePickFromHUs(final List<I_M_HU> hus) { if (!isApplicable()) { return; } // NOTE: we update only the HUs for whom we have captured info final ImmutableList<I_M_HU> husToUpdate = retainOnlyHUsWithCapturedInfo(hus); if (husToUpdate.isEmpty()) { return; } else if (husToUpdate.size() > 1) { throw new AdempiereException("Updating weight of more than one pick from HUs is not supported") .setParameter("husToUpdate", husToUpdate); } final I_M_HU hu = husToUpdate.get(0); final CapturedHUInfo capturedHUInfo = getCapturedHUInfo(hu); final Quantity weightNetNew = capturedHUInfo.getWeightNet().subtract(weightToTransfer).toZeroIfNegative(); setWeightNet(hu, weightNetNew); } private ImmutableList<I_M_HU> retainOnlyHUsWithCapturedInfo(final List<I_M_HU> hus) { return hus.stream() .filter(hu -> getCapturedHUInfoOrNull(hu) != null) .collect(ImmutableList.toImmutableList()); } private CapturedHUInfo getCapturedHUInfo(@NonNull final I_M_HU hu) { return Check.assumeNotNull(getCapturedHUInfoOrNull(hu), "capturedHUInfos contains {}: {}", hu, capturedHUInfos); } private CapturedHUInfo getCapturedHUInfoOrNull(@NonNull final I_M_HU hu) { return capturedHUInfos.get(HuId.ofRepoId(hu.getM_HU_ID())); } public void updatePackToHU(@NonNull final I_M_HU hu) { updatePackToHUs(ImmutableList.of(hu)); } public void updatePackToHUs(@NonNull final LUTUResult lutu) { updatePackToHUs(lutu.getAllTUOrCURecords()); } public void updatePackToHUs(@NonNull final List<I_M_HU> hus) { if (!isApplicable()) { return; } if (hus.isEmpty()) { return;
} if (hus.size() == 1) { final I_M_HU hu = hus.get(0); setWeightNet(hu, weightToTransfer); } else { final Quantity catchWeightToDistribute = weightToTransfer.divide(hus.size()); Quantity distributedCatchWeight = weightToTransfer.toZero(); for (int index = 0; index < hus.size(); index++) { final Quantity actualWeightToDistribute = index + 1 == hus.size() ? weightToTransfer.subtract(distributedCatchWeight) : catchWeightToDistribute; distributedCatchWeight = distributedCatchWeight.add(actualWeightToDistribute); setWeightNet(hus.get(index), actualWeightToDistribute); } } } private void setWeightNet(@NonNull final I_M_HU hu, @NonNull final Quantity weightNet) { final IAttributeStorage huAttributes = huContext.getHUAttributeStorageFactory().getAttributeStorage(hu); huAttributes.setSaveOnChange(true); final IWeightable weightable = Weightables.wrap(huAttributes); final Quantity catchWeightConv = uomConversionBL.convertQuantityTo(weightNet, productId, weightable.getWeightNetUOM()); weightable.setWeightNet(catchWeightConv.toBigDecimal()); } // // // @Value @Builder private static class CapturedHUInfo { @NonNull HuId huId; @NonNull Quantity weightNet; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackedHUWeightNetUpdater.java
1
请完成以下Java代码
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); }
/** Set Registername. @param TabName Registername */ @Override public void setTabName (java.lang.String TabName) { set_Value (COLUMNNAME_TabName, TabName); } /** Get Registername. @return Registername */ @Override public java.lang.String getTabName () { return (java.lang.String)get_Value(COLUMNNAME_TabName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_SubTab.java
1
请完成以下Java代码
public int getAD_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Remote Addr. @param Remote_Addr Remote Address */ public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) {
set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Reply. @param Reply Reply or Answer */ public void setReply (String Reply) { set_Value (COLUMNNAME_Reply, Reply); } /** Get Reply. @return Reply or Answer */ public String getReply () { return (String)get_Value(COLUMNNAME_Reply); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AccessLog.java
1
请完成以下Java代码
public class CreateTaskPayload implements Payload { private String id; private String name; private String description; private Date dueDate; private int priority; private String assignee; private List<String> candidateGroups; private List<String> candidateUsers; private String parentTaskId; private String formKey; public CreateTaskPayload() { this.id = UUID.randomUUID().toString(); } public CreateTaskPayload( String name, String description, Date dueDate, int priority, String assignee, List<String> candidateGroups, List<String> candidateUsers, String parentTaskId, String formKey ) { this(); this.name = name; this.description = description; this.dueDate = dueDate; this.priority = priority; this.assignee = assignee; this.candidateGroups = candidateGroups; this.candidateUsers = candidateUsers; this.parentTaskId = parentTaskId; this.formKey = formKey; } @Override public String getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description;
} public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\CreateTaskPayload.java
1
请完成以下Spring Boot application配置
spring: cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址
namespace: 14226a0d-799f-424d-8905-162f6a8bf409 # Nacos 命名空间 dev 的编号
repos\SpringBoot-Labs-master\labx-01-spring-cloud-alibaba-nacos-discovery\labx-01-sca-nacos-discovery-demo02-consumer\src\main\resources\application-dev.yaml
2
请完成以下Java代码
public class StorageAttributesQuery { public static final StorageAttributesQuery ALL = null; public static final StorageAttributesQuery NULL = null; public static StorageAttributesQuery parseString(final String storageAttributesKeys) { throw new UnsupportedOperationException(); // return Splitter.on(",") // .trimResults() // .omitEmptyStrings() // .splitToList(storageAttributesKeys) // .stream() // .map(attributesKeyStr -> toAttributesKeyQuery(attributesKeyStr)) // .collect(ImmutableSet.toImmutableSet()); } // private static StorageAttributeMatcher toAttributesKeyQuery(final String storageAttributesKey) // { // if ("<ALL_STORAGE_ATTRIBUTES_KEYS>".equals(storageAttributesKey))
// { // return StorageAttributeMatcher.ALL; // } // else if ("<OTHER_STORAGE_ATTRIBUTES_KEYS>".equals(storageAttributesKey)) // { // return StorageAttributeMatcher.OTHER; // } // else // { // return StorageAttributeMatcher.ofString(storageAttributesKey); // } // } public static StorageAttributesQuery of(AttributesKey storageAttributesKey) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\commons\src\main\java\de\metas\material\commons\attributes\StorageAttributesQuery.java
1
请完成以下Java代码
protected Object createMessage(InstanceEvent event, Instance instance) { Map<String, Object> messageJson = new HashMap<>(); messageJson.put("msgtype", "text"); Map<String, Object> content = new HashMap<>(); content.put("content", createContent(event, instance)); messageJson.put("text", content); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(messageJson, headers); } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } private String getSign(Long timestamp) { try { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); return URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8); } catch (Exception ex) { log.warn("Failed to sign message", ex); } return ""; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate;
} public String getWebhookUrl() { return webhookUrl; } public void setWebhookUrl(String webhookUrl) { this.webhookUrl = webhookUrl; } @Nullable public String getSecret() { return secret; } public void setSecret(@Nullable String secret) { this.secret = secret; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DingTalkNotifier.java
1
请在Spring Boot框架中完成以下Java代码
public class TaskAttachmentResource extends TaskBaseResource { @ApiOperation(value = "Get an attachment on a task", tags = { "Task Attachments" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the task and attachment were found and the attachment is returned."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a attachment with the given ID.") }) @GetMapping(value = "/runtime/tasks/{taskId}/attachments/{attachmentId}", produces = "application/json") public AttachmentResponse getAttachment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "attachmentId") @PathVariable("attachmentId") String attachmentId) { HistoricTaskInstance task = getHistoricTaskFromRequest(taskId); Attachment attachment = taskService.getAttachment(attachmentId); if (attachment == null || !task.getId().equals(attachment.getTaskId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an attachment with id '" + attachmentId + "'.", Comment.class); } return restResponseFactory.createAttachmentResponse(attachment); } @ApiOperation(value = "Delete an attachment on a task", tags = { "Task Attachments"}, code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the task and attachment were found and the attachment is deleted. Response body is left empty intentionally."), @ApiResponse(code = 404, message = "Indicates the requested task was not found or the tasks does not have a attachment with the given ID.") })
@DeleteMapping(value = "/runtime/tasks/{taskId}/attachments/{attachmentId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteAttachment(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "attachmentId") @PathVariable("attachmentId") String attachmentId) { Task task = getTaskFromRequestWithoutAccessCheck(taskId); Attachment attachment = taskService.getAttachment(attachmentId); if (attachment == null || !task.getId().equals(attachment.getTaskId())) { throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an attachment with id '" + attachmentId + "'.", Comment.class); } if (restApiInterceptor != null) { restApiInterceptor.deleteTaskAttachment(task, attachment); } taskService.deleteAttachment(attachmentId); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskAttachmentResource.java
2
请完成以下Java代码
private BigDecimal computeCurrencyRate(final I_SAP_GLJournal glJournal) { // // Extract data from source Journal final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID()); if (currencyId == null) { // not set yet return null; } final CurrencyId acctCurrencyId = CurrencyId.ofRepoIdOrNull(glJournal.getAcct_Currency_ID()); if (acctCurrencyId == null) { return null; } final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID()); Instant dateAcct = TimeUtil.asInstant(glJournal.getDateAcct()); if (dateAcct == null) { dateAcct = SystemTime.asInstant();
} final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID()); final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID()); return currencyBL.getCurrencyRateIfExists( currencyId, acctCurrencyId, dateAcct, conversionTypeId, adClientId, adOrgId) .map(CurrencyRate::getConversionRate) .orElse(BigDecimal.ZERO); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournal.java
1
请完成以下Java代码
private IQueryBuilder<I_AD_Column> createQueryBuilder() { return queryBL .createQueryBuilder(I_AD_Column.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_Column.COLUMN_IsAutoApplyValidationRule, true) .orderBy(I_AD_Column.COLUMNNAME_AD_Table_ID) .orderBy(I_AD_Column.COLUMN_AD_Column_ID); } @ModelChange( // timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, // ifColumnsChanged = { I_AD_Column.COLUMNNAME_AD_Val_Rule_ID, I_AD_Column.COLUMNNAME_IsAutoApplyValidationRule }) public void resetModelInterceptor(@NonNull final I_AD_Column column) { final String tableName = adTableDAO.retrieveTableName(column.getAD_Table_ID()); valRuleAutoApplierService.unregisterForTableName(tableName); // createAndRegisterForQuery might add it again engine.removeModelChange(tableName, autoApplyValRuleInterceptor); tabCalloutFactory.unregisterTabCalloutForTable(tableName, AD_Column_AutoApplyValRuleTabCallout.class); final IQueryBuilder<I_AD_Column> queryBuilder = createQueryBuilder() .addEqualsFilter(I_AD_Column.COLUMNNAME_AD_Table_ID, column.getAD_Table_ID()); createAndRegisterForQuery(engine, queryBuilder.create()); } private void createAndRegisterForQuery( @NonNull final IModelValidationEngine engine, @NonNull final IQuery<I_AD_Column> query) { final HashSet<String> tableNamesWithRegisteredColumn = new HashSet<>(); final ImmutableSet<AdColumnId> allColumnIds = query.idsAsSet(AdColumnId::ofRepoId); final Collection<MinimalColumnInfo> allColumns = adTableDAO.getMinimalColumnInfosByIds(allColumnIds); final ImmutableListMultimap<AdTableId, MinimalColumnInfo> tableId2columns = Multimaps.index(allColumns, MinimalColumnInfo::getAdTableId); for (final AdTableId adTableId : tableId2columns.keySet()) { final String tableName = adTableDAO.retrieveTableName(adTableId);
final Collection<MinimalColumnInfo> columns = tableId2columns.get(adTableId); final ValRuleAutoApplier valRuleAutoApplier = ValRuleAutoApplier.builder() .adTableDAO(adTableDAO) .adReferenceService(adReferenceService) .tableName(tableName) .columns(columns) .build(); valRuleAutoApplierService.registerApplier(valRuleAutoApplier); tableNamesWithRegisteredColumn.add(tableName); } tableNamesWithRegisteredColumn .forEach(tableNameWithRegisteredColum -> { engine.addModelChange(tableNameWithRegisteredColum, autoApplyValRuleInterceptor); tabCalloutFactory.registerTabCalloutForTable(tableNameWithRegisteredColum, AD_Column_AutoApplyValRuleTabCallout.class); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\interceptor\AD_Column_AutoApplyValRuleConfig.java
1
请完成以下Java代码
public Long getId() { return this.id; } public String getBiography() { return this.biography; } public String getWebsite() { return this.website; } public String getProfilePictureUrl() { return this.profilePictureUrl; } public User getUser() { return this.user; } public void setId(Long id) { this.id = id; } public void setBiography(String biography) { this.biography = biography; } public void setWebsite(String website) { this.website = website; } public void setProfilePictureUrl(String profilePictureUrl) { this.profilePictureUrl = profilePictureUrl;
} public void setUser(User user) { this.user = user; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Profile profile = (Profile) o; return Objects.equals(id, profile.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Profile(id=" + this.getId() + ", biography=" + this.getBiography() + ", website=" + this.getWebsite() + ", profilePictureUrl=" + this.getProfilePictureUrl() + ", user=" + this.getUser() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Profile.java
1
请完成以下Java代码
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); } private Mono<ServerResponse> renderErrorResponse(ServerRequest request) { ErrorAttributeOptions options = ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE); Map<String, Object> errorPropertiesMap = getErrorAttributes(request, options); Throwable throwable = getError(request); HttpStatusCode httpStatus = determineHttpStatus(throwable); errorPropertiesMap.put("status", httpStatus.value()); errorPropertiesMap.remove("error"); return ServerResponse.status(httpStatus) .contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(errorPropertiesMap)); } private HttpStatusCode determineHttpStatus(Throwable throwable) { if (throwable instanceof ResponseStatusException) { return ((ResponseStatusException) throwable).getStatusCode(); } else if (throwable instanceof CustomRequestAuthException) { return HttpStatus.UNAUTHORIZED; } else if (throwable instanceof RateLimitRequestException) { return HttpStatus.TOO_MANY_REQUESTS; } else { return HttpStatus.INTERNAL_SERVER_ERROR; } } }
repos\tutorials-master\spring-cloud-modules\gateway-exception-management\src\main\java\com\baeldung\errorhandling\CustomGlobalExceptionHandler.java
1
请完成以下Java代码
public void updateSubScriptionProgress(final I_M_ShipmentSchedule shipmentSchedule) { final I_C_SubscriptionProgress subscriptionProgress = getSubscriptionRecordOrNull(shipmentSchedule); if (subscriptionProgress == null) { return; } final BigDecimal qtyDelivered = shipmentSchedule.getQtyDelivered(); if (qtyDelivered.compareTo(subscriptionProgress.getQty()) >= 0) { subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Done); InterfaceWrapperHelper.save(subscriptionProgress); return; } final BigDecimal qtyPickList = shipmentSchedule.getQtyPickList(); if (qtyPickList.signum() > 0) { subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_InPicking); InterfaceWrapperHelper.save(subscriptionProgress); return; } subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Open); InterfaceWrapperHelper.save(subscriptionProgress); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_DELETE })
public void updateSubScriptionProgressAfterDelete(final I_M_ShipmentSchedule shipmentSchedule) { final I_C_SubscriptionProgress subscriptionProgress = getSubscriptionRecordOrNull(shipmentSchedule); if (subscriptionProgress == null) { return; } subscriptionProgress.setProcessed(false); subscriptionProgress.setM_ShipmentSchedule_ID(0); subscriptionProgress.setStatus(X_C_SubscriptionProgress.STATUS_Planned); InterfaceWrapperHelper.save(subscriptionProgress); } private I_C_SubscriptionProgress getSubscriptionRecordOrNull(final I_M_ShipmentSchedule shipmentSchedule) { final TableRecordReference ref = TableRecordReference.of(shipmentSchedule.getAD_Table_ID(), shipmentSchedule.getRecord_ID()); if (!I_C_SubscriptionProgress.Table_Name.equals(ref.getTableName())) { return null; } final I_C_SubscriptionProgress subscriptionProgress = ref.getModel( InterfaceWrapperHelper.getContextAware(shipmentSchedule), I_C_SubscriptionProgress.class); return subscriptionProgress; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\M_ShipmentSchedule.java
1
请完成以下Java代码
public org.eevolution.model.I_PP_Order_Node getPP_Order_Node() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class); } @Override public void setPP_Order_Node(org.eevolution.model.I_PP_Order_Node PP_Order_Node) { set_ValueFromPO(COLUMNNAME_PP_Order_Node_ID, org.eevolution.model.I_PP_Order_Node.class, PP_Order_Node); } /** Set Manufacturing Order Activity. @param PP_Order_Node_ID Workflow Node (activity), step or process */ @Override public void setPP_Order_Node_ID (int PP_Order_Node_ID) { if (PP_Order_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, Integer.valueOf(PP_Order_Node_ID)); } /** Get Manufacturing Order Activity. @return Workflow Node (activity), step or process */ @Override public int getPP_Order_Node_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Manufacturing Order Activity Next. @param PP_Order_NodeNext_ID Manufacturing Order Activity Next */ @Override public void setPP_Order_NodeNext_ID (int PP_Order_NodeNext_ID) { if (PP_Order_NodeNext_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Order_NodeNext_ID, Integer.valueOf(PP_Order_NodeNext_ID)); } /** Get Manufacturing Order Activity Next. @return Manufacturing Order Activity Next */ @Override public int getPP_Order_NodeNext_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_NodeNext_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Transition Code. @param TransitionCode Code resulting in TRUE of FALSE */ @Override public void setTransitionCode (java.lang.String TransitionCode) { set_Value (COLUMNNAME_TransitionCode, TransitionCode); } /** Get Transition Code. @return Code resulting in TRUE of FALSE */ @Override public java.lang.String getTransitionCode () { return (java.lang.String)get_Value(COLUMNNAME_TransitionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_NodeNext.java
1
请在Spring Boot框架中完成以下Java代码
public class EventConsumerImpl { private static final Logger LOGGER = LoggerFactory.getLogger(EventConsumerImpl.class); private static final String REQUEST_TOPIC = "sync-prod-con-requests"; private static final String RESPONSE_TOPIC = "sync-prod-con-responses"; private final KafkaTemplate<String, EventWrapper<? extends AsyncEvent>> kafkaTemplate; public EventConsumerImpl(@Autowired KafkaTemplate<String, EventWrapper<? extends AsyncEvent>> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } @KafkaListener(topics = REQUEST_TOPIC) public void consume(EventWrapper<? extends AsyncEvent> message) { LOGGER.info("#### Consumed message -> {}", message.getType()); if (message.getType().equals(TxMessageAsyncEvent.class)) { EventWrapper<TxMessageAsyncEvent> wrapper = (EventWrapper<TxMessageAsyncEvent>)message; TxMessageAsyncEvent txMessageAsyncEvent = wrapper.getEvent(); sendMessage(txMessageAsyncEvent); } else {
LOGGER.error("ERROR: unsupported message type {}", message.getType()); } } public void sendMessage(TxMessageAsyncEvent message) throws EventPublishException { try { String messageKey = message.getId(); LOGGER.info("#### Producing message: {} {}", message.getId(), message.getMessage()); ListenableFuture<SendResult<String, EventWrapper<? extends AsyncEvent>>> send = this.kafkaTemplate.send(RESPONSE_TOPIC, messageKey, new EventWrapper<>(message)); send.get(); } catch (Exception e) { throw new EventPublishException("Kafka publish DataMessage exception", e); } } }
repos\spring-examples-java-17\spring-kafka\kafka-sync-consumer\src\main\java\itx\examples\spring\kafka\service\EventConsumerImpl.java
2
请完成以下Java代码
public class PrimitivesListPerformance { private List<Integer> arrayList = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); private TIntArrayList tList = new TIntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); private cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); private IntArrayList fastUtilList = new IntArrayList(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); private int getValue = 4; @Benchmark public boolean addArrayList() { return arrayList.add(getValue); } @Benchmark public boolean addTroveIntList() { return tList.add(getValue); } @Benchmark public void addColtIntList() { coltList.add(getValue); } @Benchmark public boolean addFastUtilIntList() { return fastUtilList.add(getValue); } @Benchmark public int getArrayList() { return arrayList.get(getValue); } @Benchmark public int getTroveIntList() { return tList.get(getValue); } @Benchmark
public int getColtIntList() { return coltList.get(getValue); } @Benchmark public int getFastUtilIntList() { return fastUtilList.getInt(getValue); } @Benchmark public boolean containsArrayList() { return arrayList.contains(getValue); } @Benchmark public boolean containsTroveIntList() { return tList.contains(getValue); } @Benchmark public boolean containsColtIntList() { return coltList.contains(getValue); } @Benchmark public boolean containsFastUtilIntList() { return fastUtilList.contains(getValue); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\primitive\PrimitivesListPerformance.java
1
请在Spring Boot框架中完成以下Java代码
private static Object normalizeParameterValue(final Object value) { if (TimeUtil.isDateOrTimeObject(value)) { return TimeUtil.asTimestamp(value); } else { return value; } } public void putPInstanceId(final PInstanceId pinstanceId) { map.put(PARAM_AD_PINSTANCE_ID, PInstanceId.toRepoId(pinstanceId)); } public void putOutputType(final OutputType outputType) { put(PARAM_OUTPUTTYPE, outputType); } /** * Gets desired output type * * @return {@link OutputType}; never returns null */ public OutputType getOutputTypeEffective() { final Object outputTypeObj = get(PARAM_OUTPUTTYPE); if (outputTypeObj instanceof OutputType) { return (OutputType)outputTypeObj; } else if (outputTypeObj instanceof String) { return OutputType.valueOf(outputTypeObj.toString()); } else { return OutputType.JasperPrint; } } public void putReportLanguage(String adLanguage) { put(PARAM_REPORT_LANGUAGE, adLanguage); } /** * Extracts {@link Language} parameter * * @return {@link Language}; never returns null */ public Language getReportLanguageEffective() { final Object languageObj = get(PARAM_REPORT_LANGUAGE); Language currLang = null; if (languageObj instanceof String) { currLang = Language.getLanguage((String)languageObj); }
else if (languageObj instanceof Language) { currLang = (Language)languageObj; } if (currLang == null) { currLang = Env.getLanguage(Env.getCtx()); } return currLang; } public void putLocale(@Nullable final Locale locale) { put(JRParameter.REPORT_LOCALE, locale); } @Nullable public Locale getLocale() { return (Locale)get(JRParameter.REPORT_LOCALE); } public void putRecordId(final int recordId) { put(PARAM_RECORD_ID, recordId); } public void putTableId(final int tableId) { put(PARAM_AD_Table_ID, tableId); } public void putBarcodeURL(final String barcodeURL) { put(PARAM_BARCODE_URL, barcodeURL); } @Nullable public String getBarcodeUrl() { final Object barcodeUrl = get(PARAM_BARCODE_URL); return barcodeUrl != null ? barcodeUrl.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java
2
请完成以下Java代码
public List<IQualityInspectionOrder> getAllOrders() { return allOrders; } @Override public BigDecimal getAlreadyInvoicedNetSum() { if (_alreadyInvoicedSum == null) { final IInvoicedSumProvider invoicedSumProvider = qualityBasedConfigProviderService.getInvoicedSumProvider(); _alreadyInvoicedSum = invoicedSumProvider.getAlreadyInvoicedNetSum(_materialTracking); } if (_alreadyInvoicedSum == null) { _alreadyInvoicedSum = BigDecimal.ZERO; } return _alreadyInvoicedSum; } @Override public String toString() { final StringBuilder builder = new StringBuilder();
builder.append("QualityInspectionOrder [_ppOrder="); builder.append(_ppOrder); builder.append(", _qualityInspection="); builder.append(_qualityInspection); builder.append(", _materialTracking="); builder.append(_materialTracking); builder.append(", _qualityBasedConfig="); builder.append(_qualityBasedConfig); builder.append(", _inspectionNumber="); builder.append(_inspectionNumber); builder.append(", _productionMaterials="); builder.append(_productionMaterials); builder.append(", _productionMaterial_Raw="); builder.append(_productionMaterial_Raw); builder.append(", _productionMaterial_Main="); builder.append(_productionMaterial_Main); builder.append(", _productionMaterial_Scrap="); builder.append(_productionMaterial_Scrap); builder.append(", _alreadyInvoicedSum="); builder.append(_alreadyInvoicedSum); // builder.append(", preceedingOrders="); // builder.append(preceedingOrders); builder.append("]"); return builder.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionOrder.java
1
请完成以下Java代码
private Builder setTableAlias(final String sqlTableAlias) { assertNotBuilt(); _tableAlias = sqlTableAlias; return this; } public Builder setTableAliasFromDetailId(@Nullable final DetailId detailId) { if (detailId == null) { setTableAlias(TABLEALIAS_Master); } else { setTableAlias(detailId.getTableAlias()); } return this; } public String getTableAlias() { return _tableAlias; } public Builder setChildToParentLinkColumnNames(@Nullable final IPair<String, String> childToParentLinkColumnNames) { assertNotBuilt(); if (childToParentLinkColumnNames != null) { _sqlLinkColumnName = childToParentLinkColumnNames.getLeft(); _sqlParentLinkColumnName = childToParentLinkColumnNames.getRight(); } else { _sqlLinkColumnName = null; _sqlParentLinkColumnName = null; } return this; } public String getSqlLinkColumnName() { return _sqlLinkColumnName; } public String getSqlParentLinkColumnName() { return _sqlParentLinkColumnName; } public Builder setSqlWhereClause(final String sqlWhereClause) { assertNotBuilt(); Check.assumeNotNull(sqlWhereClause, "Parameter sqlWhereClause is not null"); _sqlWhereClause = sqlWhereClause; return this; } public Builder addField(@NonNull final DocumentFieldDataBindingDescriptor field) { assertNotBuilt(); final SqlDocumentFieldDataBindingDescriptor sqlField = SqlDocumentFieldDataBindingDescriptor.cast(field); _fieldsByFieldName.put(sqlField.getFieldName(), sqlField); return this; } private Map<String, SqlDocumentFieldDataBindingDescriptor> getFieldsByFieldName() { return _fieldsByFieldName; }
public SqlDocumentFieldDataBindingDescriptor getField(final String fieldName) { final SqlDocumentFieldDataBindingDescriptor field = getFieldsByFieldName().get(fieldName); if (field == null) { throw new AdempiereException("Field " + fieldName + " not found in " + this); } return field; } private List<SqlDocumentFieldDataBindingDescriptor> getKeyFields() { return getFieldsByFieldName() .values() .stream() .filter(SqlDocumentFieldDataBindingDescriptor::isKeyColumn) .collect(ImmutableList.toImmutableList()); } private Optional<String> getSqlSelectVersionById() { if (getFieldsByFieldName().get(FIELDNAME_Version) == null) { return Optional.empty(); } final List<SqlDocumentFieldDataBindingDescriptor> keyColumns = getKeyFields(); if (keyColumns.size() != 1) { return Optional.empty(); } final String keyColumnName = keyColumns.get(0).getColumnName(); final String sql = "SELECT " + FIELDNAME_Version + " FROM " + getTableName() + " WHERE " + keyColumnName + "=?"; return Optional.of(sql); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentEntityDataBindingDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public class MultiStepJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job multiStepJob() { // return jobBuilderFactory.get("multiStepJob") // .start(step1()) // .next(step2()) // .next(step3()) // .build(); return jobBuilderFactory.get("multiStepJob2") .start(step1()) .on(ExitStatus.COMPLETED.getExitCode()).to(step2()) .from(step2()) .on(ExitStatus.COMPLETED.getExitCode()).to(step3()) .from(step3()).end() .build(); } private Step step1() { return stepBuilderFactory.get("step1") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤一操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step2() {
return stepBuilderFactory.get("step2") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤二操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step3() { return stepBuilderFactory.get("step3") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤三操作。。。"); return RepeatStatus.FINISHED; }).build(); } }
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\MultiStepJobDemo.java
2
请完成以下Java代码
public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public List<IOParameter> getOutParameters() { return outParameters; } @Override public void addOutParameter(IOParameter outParameter) { this.outParameters.add(outParameter); } @Override public void setOutParameters(List<IOParameter> outParameters) { this.outParameters = outParameters; } public void setValues(Event otherEvent) {
super.setValues(otherEvent); eventDefinitions = new ArrayList<>(); if (otherEvent.getEventDefinitions() != null && !otherEvent.getEventDefinitions().isEmpty()) { for (EventDefinition eventDef : otherEvent.getEventDefinitions()) { eventDefinitions.add(eventDef.clone()); } } inParameters = new ArrayList<>(); if (otherEvent.getInParameters() != null && !otherEvent.getInParameters().isEmpty()) { for (IOParameter parameter : otherEvent.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherEvent.getOutParameters() != null && !otherEvent.getOutParameters().isEmpty()) { for (IOParameter parameter : otherEvent.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\Event.java
1
请完成以下Java代码
public class GlobalExceptionHandler { /** * 统一处理请求参数校验(普通传参) * * @param e ConstraintViolationException * @return FebsResponse */ @ExceptionHandler(value = ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String handleConstraintViolationException(ConstraintViolationException e) { StringBuilder message = new StringBuilder(); Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); for (ConstraintViolation<?> violation : violations) { Path path = violation.getPropertyPath(); String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), "."); message.append(pathArr[1]).append(violation.getMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return message.toString(); } /**
* 统一处理请求参数校验(实体对象传参) * * @param e BindException * @return FebsResponse */ @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String validExceptionHandler(BindException e) { StringBuilder message = new StringBuilder(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); for (FieldError error : fieldErrors) { message.append(error.getField()).append(error.getDefaultMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return message.toString(); } }
repos\SpringAll-master\46.Spring-Boot-Hibernate-Validator\src\main\java\com\example\demo\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
public class Book { long id; String name; String author; public Book(long id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public long getId() { return id; }
public String getName() { return name; } public String getAuthor() { return author; } @Override public String toString() { return String.format("Book [id=%s, name=%s, author=%s]", id, name, author); } }
repos\SpringBootForBeginners-master\01.Spring-Boot-Introduction-In-10-Steps\src\main\java\com\in28minutes\springboot\basics\springbootin10steps\Book.java
1
请完成以下Java代码
public class DefaultHistoryVariableManager implements InternalHistoryVariableManager { protected ProcessEngineConfigurationImpl processEngineConfiguration; public DefaultHistoryVariableManager(ProcessEngineConfigurationImpl processEngineConfiguration) { this.processEngineConfiguration = processEngineConfiguration; } @Override public void recordVariableCreate(VariableInstanceEntity variable, Date createTime) { getHistoryManager().recordVariableCreate(variable, createTime); if (variable.getProcessInstanceId() != null || variable.getExecutionId() != null || variable.getTaskId() != null) { getHistoryManager().recordHistoricDetailVariableCreate(variable, null, false, null, createTime); } } @Override public void recordVariableUpdate(VariableInstanceEntity variable, Date updateTime) { getHistoryManager().recordVariableUpdate(variable, updateTime); if (variable.getProcessInstanceId() != null || variable.getExecutionId() != null || variable.getTaskId() != null) {
getHistoryManager().recordHistoricDetailVariableCreate(variable, null, false, null, updateTime); } } @Override public void recordVariableRemoved(VariableInstanceEntity variable, Date removeTime) { getHistoryManager().recordVariableRemoved(variable); if (variable.getProcessInstanceId() != null || variable.getExecutionId() != null || variable.getTaskId() != null) { getHistoryManager().recordHistoricDetailVariableCreate(variable, null, false, null, removeTime); } } protected HistoryManager getHistoryManager() { return processEngineConfiguration.getHistoryManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\DefaultHistoryVariableManager.java
1
请在Spring Boot框架中完成以下Java代码
public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } /** * A single-line, single-sentence description of this property, if any. * @return the property short description * @see #getDescription() */ public String getShortDescription() { return this.shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } /** * The default value, if any. * @return the default value */ public Object getDefaultValue() { return this.defaultValue; } public void setDefaultValue(Object defaultValue) { this.defaultValue = defaultValue; } /** * Return the hints of this item. * @return the hints */ public Hints getHints() { return this.hints; } /** * The {@link Deprecation} for this property, if any.
* @return the deprecation * @see #isDeprecated() */ public Deprecation getDeprecation() { return this.deprecation; } public void setDeprecation(Deprecation deprecation) { this.deprecation = deprecation; } /** * Specify if the property is deprecated. * @return if the property is deprecated * @see #getDeprecation() */ public boolean isDeprecated() { return this.deprecation != null; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataProperty.java
2
请完成以下Java代码
public int getPackage_UOM_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Package_UOM_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_M_PriceList getUVP_Price_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class); } @Override public void setUVP_Price_List(org.compiere.model.I_M_PriceList UVP_Price_List) { set_ValueFromPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class, UVP_Price_List); } /** Set Price List UVP. @param UVP_Price_List_ID Price List UVP */ @Override public void setUVP_Price_List_ID (int UVP_Price_List_ID) { if (UVP_Price_List_ID < 1) set_Value (COLUMNNAME_UVP_Price_List_ID, null); else set_Value (COLUMNNAME_UVP_Price_List_ID, Integer.valueOf(UVP_Price_List_ID)); } /** Get Price List UVP. @return Price List UVP */ @Override public int getUVP_Price_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UVP_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_PriceList getZBV_Price_List() throws RuntimeException
{ return get_ValueAsPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class); } @Override public void setZBV_Price_List(org.compiere.model.I_M_PriceList ZBV_Price_List) { set_ValueFromPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class, ZBV_Price_List); } /** Set Price List ZBV. @param ZBV_Price_List_ID Price List ZBV */ @Override public void setZBV_Price_List_ID (int ZBV_Price_List_ID) { if (ZBV_Price_List_ID < 1) set_Value (COLUMNNAME_ZBV_Price_List_ID, null); else set_Value (COLUMNNAME_ZBV_Price_List_ID, Integer.valueOf(ZBV_Price_List_ID)); } /** Get Price List ZBV. @return Price List ZBV */ @Override public int getZBV_Price_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ZBV_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_Product.java
1
请完成以下Java代码
public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) { this.hideUserNotFoundExceptions = hideUserNotFoundExceptions; } @Override protected DirContextOperations doAuthentication(UsernamePasswordAuthenticationToken authentication) { try { return getAuthenticator().authenticate(authentication); } catch (PasswordPolicyException ex) { // The only reason a ppolicy exception can occur during a bind is that the // account is locked. throw new LockedException( this.messages.getMessage(ex.getStatus().getErrorCode(), ex.getStatus().getDefaultMessage())); } catch (UsernameNotFoundException ex) { if (this.hideUserNotFoundExceptions) { throw new BadCredentialsException(
this.messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials")); } throw ex; } catch (NamingException ex) { throw new InternalAuthenticationServiceException(ex.getMessage(), ex); } } @Override protected Collection<? extends GrantedAuthority> loadUserAuthorities(DirContextOperations userData, String username, String password) { return getAuthoritiesPopulator().getGrantedAuthorities(userData, username); } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\LdapAuthenticationProvider.java
1
请完成以下Java代码
public static int getId(final Object model) { return getDocument(model).getDocumentIdAsInt(); } public static boolean isNew(final Object model) { return getDocument(model).isNew(); } public <T> T getDynAttribute(final String attributeName) { return getDocument().getDynAttribute(attributeName); } public Object setDynAttribute(final String attributeName, final Object value) { return getDocument().setDynAttribute(attributeName, value); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final DocumentInterfaceWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } @Override public Set<String> getColumnNames() { return document.getFieldNames(); } @Override public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey();
} @Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Java代码
public ListenableFuture<Optional<TsKvEntry>> findLatestOpt(TenantId tenantId, EntityId entityId, String key) { log.trace("findLatestOpt"); return doFindLatest(tenantId, entityId, key); } @Override public ListenableFuture<TsKvEntry> findLatest(TenantId tenantId, EntityId entityId, String key) { return Futures.transform(doFindLatest(tenantId, entityId, key), x -> sqlDao.wrapNullTsKvEntry(key, x.orElse(null)), MoreExecutors.directExecutor()); } public ListenableFuture<Optional<TsKvEntry>> doFindLatest(TenantId tenantId, EntityId entityId, String key) { final TsLatestCacheKey cacheKey = new TsLatestCacheKey(entityId, key); ListenableFuture<TbCacheValueWrapper<TsKvEntry>> cacheFuture = cacheExecutorService.submit(() -> cache.get(cacheKey)); return Futures.transformAsync(cacheFuture, (cacheValueWrap) -> { if (cacheValueWrap != null) { final TsKvEntry tsKvEntry = cacheValueWrap.get(); log.debug("findLatest cache hit [{}][{}][{}]", entityId, key, tsKvEntry); return Futures.immediateFuture(Optional.ofNullable(tsKvEntry)); } log.debug("findLatest cache miss [{}][{}]", entityId, key); ListenableFuture<Optional<TsKvEntry>> daoFuture = sqlDao.findLatestOpt(tenantId, entityId, key); return Futures.transform(daoFuture, daoValue -> { cache.put(cacheKey, daoValue.orElse(null));
return daoValue; }, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor()); } @Override public ListenableFuture<List<TsKvEntry>> findAllLatest(TenantId tenantId, EntityId entityId) { return sqlDao.findAllLatest(tenantId, entityId); } @Override public List<String> findAllKeysByDeviceProfileId(TenantId tenantId, DeviceProfileId deviceProfileId) { return sqlDao.findAllKeysByDeviceProfileId(tenantId, deviceProfileId); } @Override public List<String> findAllKeysByEntityIds(TenantId tenantId, List<EntityId> entityIds) { return sqlDao.findAllKeysByEntityIds(tenantId, entityIds); } @Override public ListenableFuture<List<String>> findAllKeysByEntityIdsAsync(TenantId tenantId, List<EntityId> entityIds) { return sqlDao.findAllKeysByEntityIdsAsync(tenantId, entityIds); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\CachedRedisSqlTimeseriesLatestDao.java
1
请完成以下Java代码
public String getCreateBy() { return createBy; } /** * Set the creates the by. * * @param createBy the creates the by */ public void setCreateBy(String createBy) { this.createBy = createBy; } /** * Get the creates the time. * * @return the creates the time */ public Date getCreateTime() { return createTime; } /** * Set the creates the time. * * @param createTime the creates the time */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * Get the update by. * * @return the update by */ public String getUpdateBy() { return updateBy; } /** * Set the update by. * * @param updateBy the update by */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } /** * Get the update time. * * @return the update time */ public Date getUpdateTime() { return updateTime; } /** * Set the update time. * * @param updateTime the update time */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }
/** * Get the disabled. * * @return the disabled */ public Integer getDisabled() { return disabled; } /** * Set the disabled. * * @param disabled the disabled */ public void setDisabled(Integer disabled) { this.disabled = disabled; } /** * Get the theme. * * @return the theme */ public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. * * @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请在Spring Boot框架中完成以下Java代码
private PublicKeyCredentialCreationOptionsRepository creationOptionsRepository() { if (this.creationOptionsRepository != null) { return this.creationOptionsRepository; } ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); return context.getBeanProvider(PublicKeyCredentialCreationOptionsRepository.class).getIfUnique(); } private <C> Optional<C> getSharedOrBean(H http, Class<C> type) { C shared = http.getSharedObject(type); return Optional.ofNullable(shared).or(() -> getBeanOrNull(type)); } private <T> Optional<T> getBeanOrNull(Class<T> type) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return Optional.empty(); } try { return Optional.of(context.getBean(type)); } catch (NoSuchBeanDefinitionException ex) { return Optional.empty(); } } private MapUserCredentialRepository userCredentialRepository() { return new MapUserCredentialRepository(); }
private PublicKeyCredentialUserEntityRepository userEntityRepository() { return new MapPublicKeyCredentialUserEntityRepository(); } private WebAuthnRelyingPartyOperations webAuthnRelyingPartyOperations( PublicKeyCredentialUserEntityRepository userEntities, UserCredentialRepository userCredentials) { Optional<WebAuthnRelyingPartyOperations> webauthnOperationsBean = getBeanOrNull( WebAuthnRelyingPartyOperations.class); String rpName = (this.rpName != null) ? this.rpName : this.rpId; return webauthnOperationsBean .orElseGet(() -> new Webauthn4JRelyingPartyOperations(userEntities, userCredentials, PublicKeyCredentialRpEntity.builder().id(this.rpId).name(rpName).build(), this.allowedOrigins)); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\WebAuthnConfigurer.java
2
请完成以下Java代码
public class HistoricCaseInstanceMigrationDocumentBuilderImpl implements HistoricCaseInstanceMigrationDocumentBuilder { protected String migrateToCaseDefinitionId; protected String migrateToCaseDefinitionKey; protected Integer migrateToCaseDefinitionVersion; protected String migrateToCaseDefinitionTenantId; @Override public HistoricCaseInstanceMigrationDocumentBuilder setCaseDefinitionToMigrateTo(String caseDefinitionId) { this.migrateToCaseDefinitionId = caseDefinitionId; return this; } @Override public HistoricCaseInstanceMigrationDocumentBuilder setCaseDefinitionToMigrateTo(String caseDefinitionKey, Integer caseDefinitionVersion) { this.migrateToCaseDefinitionKey = caseDefinitionKey; this.migrateToCaseDefinitionVersion = caseDefinitionVersion; return this; }
@Override public HistoricCaseInstanceMigrationDocumentBuilder setTenantId(String caseDefinitionTenantId) { this.migrateToCaseDefinitionTenantId = caseDefinitionTenantId; return this; } @Override public HistoricCaseInstanceMigrationDocument build() { HistoricCaseInstanceMigrationDocumentImpl caseInstanceMigrationDocument = new HistoricCaseInstanceMigrationDocumentImpl(); caseInstanceMigrationDocument.setMigrateToCaseDefinitionId(this.migrateToCaseDefinitionId); caseInstanceMigrationDocument.setMigrateToCaseDefinition(this.migrateToCaseDefinitionKey, this.migrateToCaseDefinitionVersion, this.migrateToCaseDefinitionTenantId); return caseInstanceMigrationDocument; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\HistoricCaseInstanceMigrationDocumentBuilderImpl.java
1
请完成以下Java代码
public Domain findDomainById(TenantId tenantId, DomainId domainId) { log.trace("Executing findDomainInfo [{}] [{}]", tenantId, domainId); return domainDao.findById(tenantId, domainId.getId()); } @Override public PageData<DomainInfo> findDomainInfosByTenantId(TenantId tenantId, PageLink pageLink) { log.trace("Executing findDomainInfosByTenantId [{}]", tenantId); PageData<Domain> domains = domainDao.findByTenantId(tenantId, pageLink); return domains.mapData(this::getDomainInfo); } @Override public DomainInfo findDomainInfoById(TenantId tenantId, DomainId domainId) { log.trace("Executing findDomainInfoById [{}] [{}]", tenantId, domainId); Domain domain = domainDao.findById(tenantId, domainId.getId()); return getDomainInfo(domain); } @Override public boolean isOauth2Enabled(TenantId tenantId) { log.trace("Executing isOauth2Enabled [{}] ", tenantId); return domainDao.countDomainByTenantIdAndOauth2Enabled(tenantId, true) > 0; } @Override public void deleteDomainsByTenantId(TenantId tenantId) { log.trace("Executing deleteDomainsByTenantId, tenantId [{}]", tenantId); domainDao.deleteByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) { deleteDomainsByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findDomainById(tenantId, new DomainId(entityId.getId()))); }
@Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(domainDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteDomainById(tenantId, (DomainId) id); } private DomainInfo getDomainInfo(Domain domain) { if (domain == null) { return null; } List<OAuth2ClientInfo> clients = oauth2ClientDao.findByDomainId(domain.getUuidId()).stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); return new DomainInfo(domain, clients); } @Override public EntityType getEntityType() { return EntityType.DOMAIN; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\domain\DomainServiceImpl.java
1
请完成以下Java代码
protected void onInit(final IModelValidationEngine engine, final org.compiere.model.I_AD_Client client) { listenersBySourceTableName.keySet() .forEach(tableName -> engine.addModelChange(tableName, this)); } @Override public void onModelChange(final Object model, final ModelChangeType changeType) { if (changeType != ModelChangeType.BEFORE_NEW && changeType != ModelChangeType.BEFORE_CHANGE) { return; } // Skip updating the ASI if automatic ASI updating is disabled (08091) if (IModelAttributeSetInstanceListener.DYNATTR_DisableASIUpdateOnModelChange.getValue(model, false)) { return; } final String tableName = InterfaceWrapperHelper.getModelTableName(model); for (final IModelAttributeSetInstanceListener listener : listenersBySourceTableName.get(tableName)) { if (changeType.isNew() || isValueChanged(model, listener.getSourceColumnNames())) { listener.modelChanged(model); } } } /**
* @return true if at least one of the given column names were changed. */ private static boolean isValueChanged(final Object model, final List<String> columnNames) { if (columnNames == IModelAttributeSetInstanceListener.ANY_SOURCE_COLUMN) { return true; } if (columnNames == null || columnNames.isEmpty()) { return false; } for (final String columnName : columnNames) { if (InterfaceWrapperHelper.isValueChanged(model, columnName)) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\interceptor\ModelAttributeSetInstanceListenerInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class MainController { @Autowired private UserRepository userRepository; /** * GET / -> show the index page. */ @RequestMapping("/") public String index() { return "index.html"; } /** * POST /user -> create a new user. *
* @param user A json object representing the user. * @return An http 2xx status in case of success. */ @RequestMapping( value = "/user", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> addUser(@RequestBody User user) { user.setCreateTime(new DateTime()); userRepository.save(user); return new ResponseEntity<>(HttpStatus.OK); } } // class MainController
repos\spring-boot-samples-master\spring-boot-hibernate-joda-time\src\main\java\netgloo\controllers\MainController.java
2
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setParamValue (final java.lang.String ParamValue) { set_Value (COLUMNNAME_ParamValue, ParamValue); } @Override public java.lang.String getParamValue() { return get_ValueAsString(COLUMNNAME_ParamValue); } @Override public org.compiere.model.I_PP_ComponentGenerator getPP_ComponentGenerator() { return get_ValueAsPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class); } @Override public void setPP_ComponentGenerator(final org.compiere.model.I_PP_ComponentGenerator PP_ComponentGenerator) { set_ValueFromPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class, PP_ComponentGenerator); } @Override
public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID) { if (PP_ComponentGenerator_ID < 1) set_Value (COLUMNNAME_PP_ComponentGenerator_ID, null); else set_Value (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID); } @Override public int getPP_ComponentGenerator_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID); } @Override public void setPP_ComponentGenerator_Param_ID (final int PP_ComponentGenerator_Param_ID) { if (PP_ComponentGenerator_Param_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, PP_ComponentGenerator_Param_ID); } @Override public int getPP_ComponentGenerator_Param_ID() { return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_Param_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator_Param.java
1
请完成以下Java代码
static class GatewayHttpClientEnvironmentPostProcessor implements EnvironmentPostProcessor { static final boolean APACHE = ClassUtils.isPresent("org.apache.hc.client5.http.impl.classic.HttpClients", null); static final boolean JETTY = ClassUtils.isPresent("org.eclipse.jetty.client.HttpClient", null); static final boolean REACTOR_NETTY = ClassUtils.isPresent("reactor.netty.http.client.HttpClient", null); static final boolean JDK = ClassUtils.isPresent("java.net.http.HttpClient", null); static final boolean HIGHER_PRIORITY = APACHE || JETTY || REACTOR_NETTY; static final String SPRING_REDIRECTS_PROPERTY = "spring.http.clients.redirects"; static final String SPRING_HTTP_FACTORY_PROPERTY = "spring.http.clients.imperative.factory"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { HttpRedirects redirects = environment.getProperty(SPRING_REDIRECTS_PROPERTY, HttpRedirects.class); if (redirects == null) { // the user hasn't set anything, change the default environment.getPropertySources() .addFirst(new MapPropertySource("gatewayHttpClientProperties", Map.of(SPRING_REDIRECTS_PROPERTY, HttpRedirects.DONT_FOLLOW))); } Factory factory = environment.getProperty(SPRING_HTTP_FACTORY_PROPERTY, Factory.class); boolean setJdkHttpClientProperties = false; if (factory == null && !HIGHER_PRIORITY) { // autodetect setJdkHttpClientProperties = JDK;
} else if (factory == Factory.JDK) { setJdkHttpClientProperties = JDK; } if (setJdkHttpClientProperties) { // TODO: customize restricted headers String restrictedHeaders = System.getProperty("jdk.httpclient.allowRestrictedHeaders"); if (!StringUtils.hasText(restrictedHeaders)) { System.setProperty("jdk.httpclient.allowRestrictedHeaders", "host"); } else if (StringUtils.hasText(restrictedHeaders) && !restrictedHeaders.contains("host")) { System.setProperty("jdk.httpclient.allowRestrictedHeaders", restrictedHeaders + ",host"); } } } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\GatewayServerMvcAutoConfiguration.java
1
请完成以下Java代码
public static Set<String> getDeviceRequestClassnames() { return ImmutableSet.of(DummyDeviceRequest.class.getName()); } @Override public IDeviceResponseGetConfigParams getRequiredConfigParams() { return ImmutableList::of; } @Override public IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler() { return this::handleRequest; } private IDeviceResponse handleRequest(final DeviceRequestConfigureDevice request)
{ IDeviceResponse response = new IDeviceResponse() { }; logger.info("handleRequest: {} => {}", request, response); return response; } private DummyDeviceResponse handleRequest(final DummyDeviceRequest request) { final DummyDeviceResponse response = DummyDeviceConfigPool.generateRandomResponse(); logger.info("handleRequest: {} => {}", request, response); return response; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDevice.java
1
请在Spring Boot框架中完成以下Java代码
public class RabbitConfig { /** * 方法rabbitAdmin的功能描述:动态声明queue、exchange、routing * * @param connectionFactory * @return * @author : yuhao.wang */ @Bean public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) { RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); //声明死信队列(Fanout类型的exchange) Queue deadQueue = new Queue(RabbitConstants.QUEUE_NAME_DEAD_QUEUE); // 死信队列交换机 FanoutExchange deadExchange = new FanoutExchange(RabbitConstants.MQ_EXCHANGE_DEAD_QUEUE); rabbitAdmin.declareQueue(deadQueue); rabbitAdmin.declareExchange(deadExchange); rabbitAdmin.declareBinding(BindingBuilder.bind(deadQueue).to(deadExchange)); // 发放奖励队列交换机 DirectExchange exchange = new DirectExchange(RabbitConstants.MQ_EXCHANGE_SEND_AWARD); //声明发送优惠券的消息队列(Direct类型的exchange)
Queue couponQueue = queue(RabbitConstants.QUEUE_NAME_SEND_COUPON); rabbitAdmin.declareQueue(couponQueue); rabbitAdmin.declareExchange(exchange); rabbitAdmin.declareBinding(BindingBuilder.bind(couponQueue).to(exchange).with(RabbitConstants.MQ_ROUTING_KEY_SEND_COUPON)); return rabbitAdmin; } public Queue queue(String name) { Map<String, Object> args = new HashMap<>(); // 设置死信队列 args.put("x-dead-letter-exchange", RabbitConstants.MQ_EXCHANGE_DEAD_QUEUE); args.put("x-dead-letter-routing-key", RabbitConstants.MQ_ROUTING_KEY_DEAD_QUEUE); // 设置消息的过期时间, 单位是毫秒 args.put("x-message-ttl", 5000); // 是否持久化 boolean durable = true; // 仅创建者可以使用的私有队列,断开后自动删除 boolean exclusive = false; // 当所有消费客户端连接断开后,是否自动删除队列 boolean autoDelete = false; return new Queue(name, durable, exclusive, autoDelete, args); } }
repos\spring-boot-student-master\spring-boot-student-rabbitmq\src\main\java\com\xiaolyuh\config\RabbitConfig.java
2
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_DataImport getC_DataImport() { return get_ValueAsPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class); } @Override public void setC_DataImport(org.compiere.model.I_C_DataImport C_DataImport) { set_ValueFromPO(COLUMNNAME_C_DataImport_ID, org.compiere.model.I_C_DataImport.class, C_DataImport); } /** Set Daten Import. @param C_DataImport_ID Daten Import */ @Override public void setC_DataImport_ID (int C_DataImport_ID) { if (C_DataImport_ID < 1) set_Value (COLUMNNAME_C_DataImport_ID, null); else set_Value (COLUMNNAME_C_DataImport_ID, Integer.valueOf(C_DataImport_ID)); } /** Get Daten Import. @return Daten Import */ @Override public int getC_DataImport_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Data Import Run. @param C_DataImport_Run_ID Data Import Run */ @Override public void setC_DataImport_Run_ID (int C_DataImport_Run_ID) { if (C_DataImport_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DataImport_Run_ID, Integer.valueOf(C_DataImport_Run_ID)); }
/** Get Data Import Run. @return Data Import Run */ @Override public int getC_DataImport_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DataImport_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beleg fertig stellen. @param IsDocComplete Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public void setIsDocComplete (boolean IsDocComplete) { set_Value (COLUMNNAME_IsDocComplete, Boolean.valueOf(IsDocComplete)); } /** Get Beleg fertig stellen. @return Legt fest, ob ggf erstellte Belege (z.B. Produktionsaufträge) auch direkt automatisch fertig gestellt werden sollen. */ @Override public boolean isDocComplete () { Object oo = get_Value(COLUMNNAME_IsDocComplete); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport_Run.java
1
请完成以下Java代码
public class JsonArgumentResolver implements HandlerMethodArgumentResolver { private static final String JSON_BODY_ATTRIBUTE = "JSON_REQUEST_BODY"; @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(JsonArg.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String body = getRequestBody(webRequest); String jsonPath = Objects.requireNonNull(Objects.requireNonNull(parameter.getParameterAnnotation(JsonArg.class)) .value()); Class<?> parameterType = parameter.getParameterType(); return JsonPath.parse(body) .read(jsonPath, parameterType); }
private String getRequestBody(NativeWebRequest webRequest) { HttpServletRequest servletRequest = Objects.requireNonNull(webRequest.getNativeRequest(HttpServletRequest.class)); String jsonBody = (String) servletRequest.getAttribute(JSON_BODY_ATTRIBUTE); if (jsonBody == null) { try { jsonBody = IOUtils.toString(servletRequest.getInputStream()); servletRequest.setAttribute(JSON_BODY_ATTRIBUTE, jsonBody); } catch (IOException e) { throw new RuntimeException(e); } } return jsonBody; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-5\src\main\java\com\baeldung\jsonargs\JsonArgumentResolver.java
1
请完成以下Java代码
public boolean isDeferred() { return deferred; } @Override public String toString() { return getRoot().getStructuralId(null); } /** * Create a bindings. * @param fnMapper the function mapper to use * @param varMapper the variable mapper to use * @return tree bindings */ public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper) { return bind(fnMapper, varMapper, null); } /** * Create a bindings. * @param fnMapper the function mapper to use * @param varMapper the variable mapper to use * @param converter custom type converter * @return tree bindings */ public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper, TypeConverter converter) { Method[] methods = null; if (!functions.isEmpty()) { if (fnMapper == null) { throw new ELException(LocalMessages.get("error.function.nomapper")); } methods = new Method[functions.size()]; for (int i = 0; i < functions.size(); i++) { FunctionNode node = functions.get(i); String image = node.getName(); Method method = null; int colon = image.indexOf(':'); if (colon < 0) { method = fnMapper.resolveFunction("", image); } else { method = fnMapper.resolveFunction(image.substring(0, colon), image.substring(colon + 1)); } if (method == null) {
throw new ELException(LocalMessages.get("error.function.notfound", image)); } if (node.isVarArgs() && method.isVarArgs()) { if (method.getParameterTypes().length > node.getParamCount() + 1) { throw new ELException(LocalMessages.get("error.function.params", image)); } } else { if (method.getParameterTypes().length != node.getParamCount()) { throw new ELException(LocalMessages.get("error.function.params", image)); } } methods[node.getIndex()] = method; } } ValueExpression[] expressions = null; if (identifiers.size() > 0) { expressions = new ValueExpression[identifiers.size()]; for (int i = 0; i < identifiers.size(); i++) { IdentifierNode node = identifiers.get(i); ValueExpression expression = null; if (varMapper != null) { expression = varMapper.resolveVariable(node.getName()); } expressions[node.getIndex()] = expression; } } return new Bindings(methods, expressions, converter); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Tree.java
1
请完成以下Java代码
protected Clock getClock() { return getProcessEngineConfiguration().getClock(); } protected AsyncExecutor getAsyncExecutor() { return getProcessEngineConfiguration().getAsyncExecutor(); } protected FlowableEventDispatcher getEventDispatcher() { return getProcessEngineConfiguration().getEventDispatcher(); } protected HistoryManager getHistoryManager() { return getProcessEngineConfiguration().getHistoryManager(); } protected DeploymentEntityManager getDeploymentEntityManager() { return getProcessEngineConfiguration().getDeploymentEntityManager(); } protected ResourceEntityManager getResourceEntityManager() { return getProcessEngineConfiguration().getResourceEntityManager(); } protected ByteArrayEntityManager getByteArrayEntityManager() { return getProcessEngineConfiguration().getByteArrayEntityManager(); } protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return getProcessEngineConfiguration().getProcessDefinitionEntityManager(); } protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() { return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager(); } protected ModelEntityManager getModelEntityManager() { return getProcessEngineConfiguration().getModelEntityManager(); } protected ExecutionEntityManager getExecutionEntityManager() { return getProcessEngineConfiguration().getExecutionEntityManager(); } protected ActivityInstanceEntityManager getActivityInstanceEntityManager() { return getProcessEngineConfiguration().getActivityInstanceEntityManager(); }
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager(); } protected HistoricDetailEntityManager getHistoricDetailEntityManager() { return getProcessEngineConfiguration().getHistoricDetailEntityManager(); } protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() { return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager(); } protected AttachmentEntityManager getAttachmentEntityManager() { return getProcessEngineConfiguration().getAttachmentEntityManager(); } protected CommentEntityManager getCommentEntityManager() { return getProcessEngineConfiguration().getCommentEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
1
请在Spring Boot框架中完成以下Java代码
public void setPlanItemDefinitionTypes(List<String> planItemDefinitionTypes) { this.planItemDefinitionTypes = planItemDefinitionTypes; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Date getCreatedBefore() { return createdBefore; } public void setCreatedBefore(Date createdBefore) { this.createdBefore = createdBefore; } public Date getCreatedAfter() { return createdAfter; } public void setCreatedAfter(Date createdAfter) { this.createdAfter = createdAfter; } public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; }
public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public Boolean getIncludeEnded() { return includeEnded; } public void setIncludeEnded(Boolean includeEnded) { this.includeEnded = includeEnded; } public Boolean getIncludeLocalVariables() { return includeLocalVariables; } public void setIncludeLocalVariables(boolean includeLocalVariables) { this.includeLocalVariables = includeLocalVariables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public void setCaseInstanceIds(Set<String> caseInstanceIds) { this.caseInstanceIds = caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceQueryRequest.java
2
请完成以下Java代码
public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!contains(o)) return false; } return true; } @Override public boolean addAll(Collection<? extends TermFrequency> c) { for (TermFrequency termFrequency : c) { add(termFrequency); } return !c.isEmpty(); } @Override public boolean removeAll(Collection<?> c) { for (Object o : c) { if (!remove(o)) return false; } return true; } @Override public boolean retainAll(Collection<?> c) { return termFrequencyMap.values().retainAll(c); } @Override public void clear() { termFrequencyMap.clear(); } /** * 提取关键词(非线程安全) * * @param termList * @param size * @return */ @Override public List<String> getKeywords(List<Term> termList, int size) { clear(); add(termList);
Collection<TermFrequency> topN = top(size); List<String> r = new ArrayList<String>(topN.size()); for (TermFrequency termFrequency : topN) { r.add(termFrequency.getTerm()); } return r; } /** * 提取关键词(线程安全) * * @param document 文档内容 * @param size 希望提取几个关键词 * @return 一个列表 */ public static List<String> getKeywordList(String document, int size) { return new TermFrequencyCounter().getKeywords(document, size); } @Override public String toString() { final int max = 100; return top(Math.min(max, size())).toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java
1
请完成以下Java代码
public OrderId getSalesOrderId() { final OrderAndLineId salesOrderAndLineId = getPurchaseCandidate().getSalesOrderAndLineIdOrNull(); return salesOrderAndLineId != null ? salesOrderAndLineId.getOrderId() : null; } @Nullable public ForecastLineId getForecastLineId() { return getPurchaseCandidate().getForecastLineId(); } private Quantity getQtyToPurchase() { return getPurchaseCandidate().getQtyToPurchase(); } public boolean purchaseMatchesRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) == 0; } private boolean purchaseMatchesOrExceedsRequiredQty() { return getPurchasedQty().compareTo(getQtyToPurchase()) >= 0; } public void setPurchaseOrderLineId(@NonNull final OrderAndLineId purchaseOrderAndLineId) { this.purchaseOrderAndLineId = purchaseOrderAndLineId; } public void markPurchasedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.markProcessed(); } } public void markReqCreatedIfNeeded() { if (purchaseMatchesOrExceedsRequiredQty()) { purchaseCandidate.setReqCreated(true); } } @Nullable public BigDecimal getPrice() { return purchaseCandidate.getPriceEnteredEff(); } @Nullable public UomId getPriceUomId() { return purchaseCandidate.getPriceUomId(); } @Nullable public Percent getDiscount() { return purchaseCandidate.getDiscountEff();
} @Nullable public String getExternalPurchaseOrderUrl() { return purchaseCandidate.getExternalPurchaseOrderUrl(); } @Nullable public ExternalId getExternalHeaderId() { return purchaseCandidate.getExternalHeaderId(); } @Nullable public ExternalSystemId getExternalSystemId() { return purchaseCandidate.getExternalSystemId(); } @Nullable public ExternalId getExternalLineId() { return purchaseCandidate.getExternalLineId(); } @Nullable public String getPOReference() { return purchaseCandidate.getPOReference(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseOrderItem.java
1
请在Spring Boot框架中完成以下Java代码
public class Id { @JsonCreator public static Id of(final String valueAsString) { return new Id(valueAsString); } public static Id random() { return new Id(UUID.randomUUID().toString()); } private final String valueAsString; private Id(@NonNull final String valueAsString) { if (valueAsString.isEmpty()) { throw new IllegalArgumentException("value shall not be empty"); }
this.valueAsString = valueAsString; } /** * @deprecated please use {@link #getValueAsString()} */ @Override @Deprecated public String toString() { return getValueAsString(); } @JsonValue public String toJson() { return getValueAsString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\types\Id.java
2
请完成以下Java代码
public static ImmutableSet<ShipmentScheduleId> fromIntSet(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(ShipmentScheduleId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } int repoId; private ShipmentScheduleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipmentSchedule_ID"); } @Override @JsonValue public int getRepoId() { return repoId; }
public static int toRepoId(@Nullable final ShipmentScheduleId id) { return id != null ? id.getRepoId() : -1; } public TableRecordReference toTableRecordReference() { return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, getRepoId()); } public static boolean equals(@Nullable final ShipmentScheduleId id1, @Nullable final ShipmentScheduleId id2) {return Objects.equals(id1, id2);} public static TableRecordReferenceSet toTableRecordReferenceSet(@NonNull final Collection<ShipmentScheduleId> ids) { return TableRecordReferenceSet.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\ShipmentScheduleId.java
1
请完成以下Java代码
protected String doIt() throws Exception { final Multimap<PurchaseRow, PurchaseRow> lineRows2availabilityRows = extractLineRow2availabilityRows(); Check.errorIf(hasMultipleAvailabilityRowsPerLineRow(lineRows2availabilityRows), "The selected rows contain > 1 availability row for one line row; lineRows2availabilityRows={}", lineRows2availabilityRows); lineRows2availabilityRows.forEach(this::updateLineAndGroupRow); return MSG_OK; } private static boolean hasMultipleAvailabilityRowsPerLineRow( @NonNull final Multimap<PurchaseRow, PurchaseRow> lineRows2availabilityRows) { return lineRows2availabilityRows .asMap() .entrySet() .stream() .anyMatch(lineRow2availabilityRows -> lineRow2availabilityRows.getValue().size() > 1); } public void updateLineAndGroupRow(@NonNull final PurchaseRow lineRow, @NonNull final PurchaseRow availabilityRow) { final PurchaseRowId lineRowId = lineRow.getRowId(); final PurchaseRowChangeRequest lineChangeRequest = createPurchaseRowChangeRequest(availabilityRow); patchViewRow(lineRowId, lineChangeRequest); } private Multimap<PurchaseRow, PurchaseRow> extractLineRow2availabilityRows() { final PurchaseView view = getView(); final ListMultimap<PurchaseRow, PurchaseRow> lineRow2AvailabilityRows = getSelectedRowIds().stream() .map(PurchaseRowId::fromDocumentId) // map to PurchaseRowIds .filter(PurchaseRowId::isAvailabilityRowId) .filter(availabilityRowId -> availabilityRowId.getAvailabilityType().equals(Type.AVAILABLE)) .map(availabilityRowId -> ImmutablePair.of( // map to pair (availabilityRowId, availabilityRow) availabilityRowId, view.getById(availabilityRowId.toDocumentId()))) .filter(availabilityRowId2row -> isPositive(availabilityRowId2row.getRight().getQtyToPurchase())) .map(availabilityRowId2row -> ImmutablePair.of( // map to pair (lineRow, availabilityRow)
view.getById(availabilityRowId2row.getLeft().toLineRowId().toDocumentId()), availabilityRowId2row.getRight())) .filter(lineRow2availabilityRow -> !lineRow2availabilityRow.getLeft().isProcessed()) .collect(Multimaps.toMultimap( IPair::getLeft, IPair::getRight, MultimapBuilder.hashKeys().arrayListValues()::build)); return ImmutableMultimap.copyOf(lineRow2AvailabilityRows); } private static final boolean isPositive(final Quantity qty) { return qty != null && qty.signum() > 0; } private static PurchaseRowChangeRequest createPurchaseRowChangeRequest(final PurchaseRow availabilityRow) { final PurchaseRowChangeRequestBuilder requestBuilder = PurchaseRowChangeRequest.builder(); if (availabilityRow.getDatePromised() != null) { requestBuilder.purchaseDatePromised(availabilityRow.getDatePromised()); } requestBuilder.qtyToPurchase(availabilityRow.getQtyToPurchase()); return requestBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\process\WEBUI_SalesOrder_Apply_Availability_Row.java
1
请完成以下Java代码
public String toString() { return "InvocationContext [" + "method=" + method + ", args=" + Arrays.toString(methodArgs) + ", target=" + target + "]"; } @Override public Object proceed() throws Throwable { if (!method.isAccessible()) { method.setAccessible(true); } try { return method.invoke(target, methodArgs); } catch (InvocationTargetException ite) { // unwrap the target implementation's exception to that it can be caught throw ite.getTargetException(); } } @Override public Object call() throws Exception { try { final Object result = proceed(); return result == null ? NullResult : result; } catch (Exception e)
{ throw e; } catch (Throwable e) { Throwables.propagateIfPossible(e); throw Throwables.propagate(e); } } @Override public Object getTarget() { return target; } @Override public Object[] getParameters() { return methodArgs; } @Override public Method getMethod() { return method; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\InvocationContext.java
1
请在Spring Boot框架中完成以下Java代码
public class GroupMembershipCollectionResource extends BaseGroupResource { @ApiOperation(value = "Add a member to a group", tags = { "Groups" }, code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the group was found and the member has been added."), @ApiResponse(code = 400, message = "Indicates the userId was not included in the request body."), @ApiResponse(code = 404, message = "Indicates the requested group was not found."), @ApiResponse(code = 409, message = "Indicates the requested user is already a member of the group.") }) @PostMapping(value = "/groups/{groupId}/members", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public MembershipResponse createMembership(@ApiParam(name = "groupId") @PathVariable String groupId, @RequestBody MembershipRequest memberShip) { Group group = getGroupFromRequest(groupId);
if (memberShip.getUserId() == null) { throw new FlowableIllegalArgumentException("UserId cannot be null."); } // Check if user is member of group since API doesn't return typed exception if (identityService.createUserQuery().memberOfGroup(group.getId()).userId(memberShip.getUserId()).count() > 0) { throw new FlowableConflictException("User '" + memberShip.getUserId() + "' is already part of group '" + group.getId() + "'."); } identityService.createMembership(memberShip.getUserId(), group.getId()); return restResponseFactory.createMembershipResponse(memberShip.getUserId(), group.getId()); } }
repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\group\GroupMembershipCollectionResource.java
2
请完成以下Java代码
public class BankTransactionCodeStructure5 { @XmlElement(name = "Cd", required = true) protected String cd; @XmlElement(name = "Fmly", required = true) protected BankTransactionCodeStructure6 fmly; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; } /** * Gets the value of the fmly property. * * @return
* possible object is * {@link BankTransactionCodeStructure6 } * */ public BankTransactionCodeStructure6 getFmly() { return fmly; } /** * Sets the value of the fmly property. * * @param value * allowed object is * {@link BankTransactionCodeStructure6 } * */ public void setFmly(BankTransactionCodeStructure6 value) { this.fmly = 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_02\BankTransactionCodeStructure5.java
1
请完成以下Java代码
public void setErrorCode (final @Nullable java.lang.String ErrorCode) { set_Value (COLUMNNAME_ErrorCode, ErrorCode); } @Override public java.lang.String getErrorCode() { return get_ValueAsString(COLUMNNAME_ErrorCode); } @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setMsgTip (final @Nullable java.lang.String MsgTip) { set_Value (COLUMNNAME_MsgTip, MsgTip); } @Override public java.lang.String getMsgTip() { return get_ValueAsString(COLUMNNAME_MsgTip); } /** * MsgType AD_Reference_ID=103 * Reference name: AD_Message Type */ public static final int MSGTYPE_AD_Reference_ID=103; /** Fehler = E */ public static final String MSGTYPE_Fehler = "E"; /** Information = I */ public static final String MSGTYPE_Information = "I"; /** Menü = M */ public static final String MSGTYPE_Menue = "M"; @Override public void setMsgType (final java.lang.String MsgType)
{ set_Value (COLUMNNAME_MsgType, MsgType); } @Override public java.lang.String getMsgType() { return get_ValueAsString(COLUMNNAME_MsgType); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message.java
1
请完成以下Java代码
static Map<String, Object> getParametersIfMatchesAuthorizationCodeGrantRequest(HttpServletRequest request, String... exclusions) { if (!matchesAuthorizationCodeGrantRequest(request)) { return Collections.emptyMap(); } MultiValueMap<String, String> multiValueParameters = "GET".equals(request.getMethod()) ? getQueryParameters(request) : getFormParameters(request); for (String exclusion : exclusions) { multiValueParameters.remove(exclusion); } Map<String, Object> parameters = new HashMap<>(); multiValueParameters.forEach( (key, value) -> parameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0]))); return parameters; } static boolean matchesAuthorizationCodeGrantRequest(HttpServletRequest request) { return AuthorizationGrantType.AUTHORIZATION_CODE.getValue() .equals(request.getParameter(OAuth2ParameterNames.GRANT_TYPE)) && request.getParameter(OAuth2ParameterNames.CODE) != null; } static boolean matchesPkceTokenRequest(HttpServletRequest request) { return matchesAuthorizationCodeGrantRequest(request) && request.getParameter(PkceParameterNames.CODE_VERIFIER) != null; } static void validateAndAddDPoPParametersIfAvailable(HttpServletRequest request, Map<String, Object> additionalParameters) { final String dPoPProofHeaderName = OAuth2AccessToken.TokenType.DPOP.getValue(); String dPoPProof = request.getHeader(dPoPProofHeaderName);
if (StringUtils.hasText(dPoPProof)) { if (Collections.list(request.getHeaders(dPoPProofHeaderName)).size() != 1) { throwError(OAuth2ErrorCodes.INVALID_REQUEST, dPoPProofHeaderName, ACCESS_TOKEN_REQUEST_ERROR_URI); } else { additionalParameters.put("dpop_proof", dPoPProof); additionalParameters.put("dpop_method", request.getMethod()); additionalParameters.put("dpop_target_uri", request.getRequestURL().toString()); } } } static void throwError(String errorCode, String parameterName, String errorUri) { OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, errorUri); throw new OAuth2AuthenticationException(error); } static String normalizeUserCode(String userCode) { Assert.hasText(userCode, "userCode cannot be empty"); StringBuilder sb = new StringBuilder(userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", "")); Assert.isTrue(sb.length() == 8, "userCode must be exactly 8 alpha/numeric characters"); sb.insert(4, '-'); return sb.toString(); } static boolean validateUserCode(String userCode) { return (userCode != null && userCode.toUpperCase(Locale.ENGLISH).replaceAll("[^A-Z\\d]+", "").length() == 8); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2EndpointUtils.java
1
请完成以下Java代码
public class CleanupTestMain { public static void main(String[] args) { } public static void cleanLB() { // try { // @Cleanup InputStream inputStream = new FileInputStream(new File("")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } } public static void clean() { InputStream inputStream = null;
try { inputStream = new FileInputStream(new File("")); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
repos\spring-boot-quick-master\quick-lombok\src\main\java\com\lombok\CleanupTestMain.java
1
请完成以下Java代码
public ByteArrayEntity getEntity() { ensureInitialized(); return entity; } public void delete() { if (!deleted && id != null) { if (entity != null) { // if the entity has been loaded already, // we might as well use the safer optimistic locking delete. Context.getCommandContext().getByteArrayEntityManager().delete(entity); } else { Context.getCommandContext().getByteArrayEntityManager().deleteByteArrayById(id); } entity = null; id = null; deleted = true; } }
private void ensureInitialized() { if (id != null && entity == null) { entity = Context.getCommandContext().getByteArrayEntityManager().findById(id); name = entity.getName(); } } public boolean isDeleted() { return deleted; } @Override public String toString() { return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]"); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayRef.java
1
请完成以下Java代码
public void setOutboundHttpEP (final String OutboundHttpEP) { set_Value (COLUMNNAME_OutboundHttpEP, OutboundHttpEP); } @Override public String getOutboundHttpEP() { return get_ValueAsString(COLUMNNAME_OutboundHttpEP); } @Override public void setOutboundHttpMethod (final String OutboundHttpMethod) { set_Value (COLUMNNAME_OutboundHttpMethod, OutboundHttpMethod); } @Override public String getOutboundHttpMethod() { return get_ValueAsString(COLUMNNAME_OutboundHttpMethod); } @Override public void setPassword (final @Nullable String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public String getPassword() { return get_ValueAsString(COLUMNNAME_Password); } @Override public void setSasSignature (final @Nullable String SasSignature) { set_Value (COLUMNNAME_SasSignature, SasSignature); } @Override public String getSasSignature()
{ return get_ValueAsString(COLUMNNAME_SasSignature); } /** * Type AD_Reference_ID=542016 * Reference name: ExternalSystem_Outbound_Endpoint_EndpointType */ public static final int TYPE_AD_Reference_ID=542016; /** HTTP = HTTP */ public static final String TYPE_HTTP = "HTTP"; /** SFTP = SFTP */ public static final String TYPE_SFTP = "SFTP"; /** FILE = FILE */ public static final String TYPE_FILE = "FILE"; /** EMAIL = EMAIL */ public static final String TYPE_EMAIL = "EMAIL"; /** TCP = TCP */ public static final String TYPE_TCP = "TCP"; @Override public void setType (final String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setValue (final String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Warehouse_Group_ID (final int M_Warehouse_Group_ID) { if (M_Warehouse_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_Group_ID, M_Warehouse_Group_ID); }
@Override public int getM_Warehouse_Group_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_Group_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_Group.java
1
请完成以下Java代码
public class TrieEntry extends AbstractMap.SimpleEntry<String, V> implements Comparable<TrieEntry> { public TrieEntry(String key, V value) { super(key, value); } @Override public int compareTo(TrieEntry o) { return getKey().compareTo(o.getKey()); } } @Override public String toString() {
if (child == null) { return "BaseNode{" + "status=" + status + ", c=" + c + ", value=" + value + '}'; } return "BaseNode{" + "child=" + child.length + ", status=" + status + ", c=" + c + ", value=" + value + '}'; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\BaseNode.java
1
请完成以下Java代码
public class DatabaseUtil { /** * Checks if the currently used database is of a given database type. * * @param databaseTypes to check for * @return true if any of the provided types match the used one. Otherwise false. */ public static boolean checkDatabaseType(String... databaseTypes) { return checkDatabaseType(Context.getCommandContext().getProcessEngineConfiguration(), databaseTypes); } /** * Checks if the currently used database is of a given database type. *
* @param configuration for the Process Engine, when a Context is not available * @param databaseTypes to check for * @return true if any of the provided types match the used one. Otherwise false. */ public static boolean checkDatabaseType(ProcessEngineConfigurationImpl configuration, String... databaseTypes) { String dbType = configuration.getDatabaseType(); return Arrays.stream(databaseTypes).anyMatch(dbType::equals); } /** * @return true if the currently used database is known to roll back transactions on SQL errors. */ public static boolean checkDatabaseRollsBackTransactionOnError() { return checkDatabaseType(DbSqlSessionFactory.POSTGRES); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\DatabaseUtil.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> queryPermissionUrlWithStar() { return this.baseMapper.queryPermissionUrlWithStar(); } @Override public boolean hasPermission(String username, SysPermission sysPermission) { int count = baseMapper.queryCountByUsername(username,sysPermission); if(count>0){ return true; }else{ return false; } } @Override public boolean hasPermission(String username, String url) { SysPermission sysPermission = new SysPermission(); sysPermission.setUrl(url); int count = baseMapper.queryCountByUsername(username,sysPermission); if(count>0){
return true; }else{ return false; } } @Override public List<SysPermission> queryDepartPermissionList(String departId) { return sysPermissionMapper.queryDepartPermissionList(departId); } @Override public boolean checkPermDuplication(String id, String url,Boolean alwaysShow) { QueryWrapper<SysPermission> qw=new QueryWrapper(); qw.lambda().eq(true,SysPermission::getUrl,url).ne(oConvertUtils.isNotEmpty(id),SysPermission::getId,id).eq(true,SysPermission::isAlwaysShow,alwaysShow); return count(qw)==0; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysPermissionServiceImpl.java
2
请完成以下Java代码
public long findExecutionCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectExecutionCountByNativeQuery", parameterMap); } @Override public void updateExecutionTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().update("updateExecutionTenantIdForDeployment", params); } @Override public void updateProcessInstanceLockTime(String processInstanceId, Date lockDate, Date expirationTime) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("id", processInstanceId); params.put("lockTime", lockDate); params.put("expirationTime", expirationTime);
int result = getDbSqlSession().update("updateProcessInstanceLockTime", params); if (result == 0) { throw new ActivitiOptimisticLockingException("Could not lock process instance"); } } @Override public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) { getDbSqlSession().update("updateExecutionRelatedEntityCountEnabled", newValue); } @Override public void clearProcessInstanceLockTime(String processInstanceId) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("id", processInstanceId); getDbSqlSession().update("clearProcessInstanceLockTime", params); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java
1
请完成以下Java代码
public void setAD_Issue_ID (final int AD_Issue_ID) { if (AD_Issue_ID < 1) set_Value (COLUMNNAME_AD_Issue_ID, null); else set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID); } @Override public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setExportSequenceNumber (final int ExportSequenceNumber) { set_Value (COLUMNNAME_ExportSequenceNumber, ExportSequenceNumber); } @Override public int getExportSequenceNumber() { return get_ValueAsInt(COLUMNNAME_ExportSequenceNumber); } /** * ExportStatus AD_Reference_ID=541161 * Reference name: API_ExportStatus */ public static final int EXPORTSTATUS_AD_Reference_ID=541161; /** PENDING = PENDING */ public static final String EXPORTSTATUS_PENDING = "PENDING"; /** EXPORTED = EXPORTED */ public static final String EXPORTSTATUS_EXPORTED = "EXPORTED"; /** EXPORTED_AND_FORWARDED = EXPORTED_AND_FORWARDED */ public static final String EXPORTSTATUS_EXPORTED_AND_FORWARDED = "EXPORTED_AND_FORWARDED"; /** EXPORTED_FORWARD_ERROR = EXPORTED_FORWARD_ERROR */ public static final String EXPORTSTATUS_EXPORTED_FORWARD_ERROR = "EXPORTED_FORWARD_ERROR"; /** EXPORT_ERROR = EXPORT_ERROR */ public static final String EXPORTSTATUS_EXPORT_ERROR = "EXPORT_ERROR"; /** DONT_EXPORT = DONT_EXPORT */ public static final String EXPORTSTATUS_DONT_EXPORT = "DONT_EXPORT"; @Override public void setExportStatus (final java.lang.String ExportStatus) { set_Value (COLUMNNAME_ExportStatus, ExportStatus); } @Override public java.lang.String getExportStatus() { return get_ValueAsString(COLUMNNAME_ExportStatus); } @Override
public void setForwardedData (final @Nullable java.lang.String ForwardedData) { set_Value (COLUMNNAME_ForwardedData, ForwardedData); } @Override public java.lang.String getForwardedData() { return get_ValueAsString(COLUMNNAME_ForwardedData); } @Override public void setM_ShipmentSchedule_ExportAudit_ID (final int M_ShipmentSchedule_ExportAudit_ID) { if (M_ShipmentSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, M_ShipmentSchedule_ExportAudit_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { set_Value (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit.java
1
请完成以下Java代码
private AttributeAggregator getAttributeAggregator(@NonNull final I_M_Attribute attribute) { return attributeAggregators.computeIfAbsent( AttributeCode.ofString(attribute.getValue()), attributeCode -> new AttributeAggregator(attributeCode, AttributeValueType.ofCode(attribute.getAttributeValueType())) ); } void updateAggregatedValuesTo(@NonNull final IAttributeSet to) { attributeAggregators.values() .forEach(attributeAggregator -> attributeAggregator.updateAggregatedValueTo(to)); } private static boolean isAggregable(@NonNull final I_M_Attribute attribute) { return !Weightables.isWeightableAttribute(AttributeCode.ofString(attribute.getValue())); } // // // @RequiredArgsConstructor private static class AttributeAggregator { private final AttributeCode attributeCode; private final AttributeValueType attributeValueType; private final HashSet<Object> values = new HashSet<>(); void collect(@NonNull final IAttributeSet from) { final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>() { @Nullable @Override public Object string() { return from.getValueAsString(attributeCode); } @Override public Object number() { return from.getValueAsBigDecimal(attributeCode); } @Nullable @Override public Object date() {
return from.getValueAsDate(attributeCode); } @Nullable @Override public Object list() { return from.getValueAsString(attributeCode); } }); values.add(value); } void updateAggregatedValueTo(@NonNull final IAttributeSet to) { if (values.size() == 1 && to.hasAttribute(attributeCode)) { to.setValue(attributeCode, values.iterator().next()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java
1
请完成以下Java代码
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { CmmnModel model = conversionHelper.getCmmnModel(); model.setId(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_ID)); model.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); model.setExpressionLanguage(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPRESSION_LANGUAGE)); model.setExporter(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER)); model.setExporterVersion(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EXPORTER_VERSION)); model.setAuthor(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_AUTHOR)); model.setTargetNamespace(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_TARGET_NAMESPACE)); String creationDateString = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_CREATION_DATE); if (StringUtils.isNotEmpty(creationDateString)) { try { Date creationDate = new SimpleDateFormat(XSD_DATETIME_FORMAT).parse(creationDateString); model.setCreationDate(creationDate); } catch (ParseException e) { LOGGER.warn("Ignoring creationDate attribute: invalid date format", e); } } for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (StringUtils.isNotEmpty(prefix)) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); } } for (int i = 0; i < xtr.getAttributeCount(); i++) { ExtensionAttribute extensionAttribute = new ExtensionAttribute(); extensionAttribute.setName(xtr.getAttributeLocalName(i)); extensionAttribute.setValue(xtr.getAttributeValue(i));
String namespace = xtr.getAttributeNamespace(i); if (model.getNamespaces().containsValue(namespace)) { if (StringUtils.isNotEmpty(namespace)) { extensionAttribute.setNamespace(namespace); } if (StringUtils.isNotEmpty(xtr.getAttributePrefix(i))) { extensionAttribute.setNamespacePrefix(xtr.getAttributePrefix(i)); } model.addDefinitionsAttribute(extensionAttribute); } } return null; } @Override protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) { } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\DefinitionsXmlConverter.java
1
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_Value (COLUMNNAME_C_Project_ID, null); else set_Value (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public void setExternalProjectOwner (final java.lang.String ExternalProjectOwner) { set_Value (COLUMNNAME_ExternalProjectOwner, ExternalProjectOwner); } @Override public java.lang.String getExternalProjectOwner() { return get_ValueAsString(COLUMNNAME_ExternalProjectOwner); } @Override public void setExternalReference (final java.lang.String ExternalReference) { set_Value (COLUMNNAME_ExternalReference, ExternalReference); } @Override public java.lang.String getExternalReference() { return get_ValueAsString(COLUMNNAME_ExternalReference); } @Override public void setExternalReferenceURL (final @Nullable java.lang.String ExternalReferenceURL) { set_Value (COLUMNNAME_ExternalReferenceURL, ExternalReferenceURL); } @Override public java.lang.String getExternalReferenceURL() { return get_ValueAsString(COLUMNNAME_ExternalReferenceURL); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } /**
* ProjectType AD_Reference_ID=541118 * Reference name: ExternalProjectType */ public static final int PROJECTTYPE_AD_Reference_ID=541118; /** Budget = Budget */ public static final String PROJECTTYPE_Budget = "Budget"; /** Development = Effort */ public static final String PROJECTTYPE_Development = "Effort"; @Override public void setProjectType (final java.lang.String ProjectType) { set_Value (COLUMNNAME_ProjectType, ProjectType); } @Override public java.lang.String getProjectType() { return get_ValueAsString(COLUMNNAME_ProjectType); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setS_ExternalProjectReference_ID (final int S_ExternalProjectReference_ID) { if (S_ExternalProjectReference_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, S_ExternalProjectReference_ID); } @Override public int getS_ExternalProjectReference_ID() { return get_ValueAsInt(COLUMNNAME_S_ExternalProjectReference_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalProjectReference.java
2
请完成以下Java代码
private static Font createSafeFont() { // 使用逻辑字体名称,在所有平台都可用 String[] safeFontNames = {Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, "Dialog"}; for (String fontName : safeFontNames) { try { Font font = new Font(fontName, Font.BOLD, FONT_SIZE); if (font.getFamily() != null) { return font; } } catch (Exception e) { // 继续尝试下一个字体 } } // 最后的回退方案 return new Font(Font.MONOSPACED, Font.BOLD, FONT_SIZE); } /** * 创建错误图像(当正常绘制失败时使用) */ private static BufferedImage createErrorImage(String verifyCode) { BufferedImage errorImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = null; try { graphics = (Graphics2D) errorImage.getGraphics(); // 白色背景 graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, WIDTH, HEIGHT); // 黑色边框 graphics.setColor(Color.BLACK); graphics.drawRect(0, 0, WIDTH - 1, HEIGHT - 1); // 尝试绘制验证码 try { graphics.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20)); graphics.setColor(Color.BLUE); for (int i = 0; i < verifyCode.length(); i++) { graphics.drawString(String.valueOf(verifyCode.charAt(i)), i * CHAR_SPACING + CHAR_X_OFFSET, CHAR_Y_OFFSET);
} } catch (Exception fontException) { // 如果连基本字体都失败,显示ERROR graphics.setColor(Color.RED); graphics.drawString("ERROR", 10, 20); } } finally { if (graphics != null) { graphics.dispose(); } } return errorImage; } /** * 获取指定范围内的随机颜色 * * @param minColorValue 最小颜色值 * @param maxColorValue 最大颜色值 * @param random 随机数生成器 * @return 随机颜色 */ private static Color getRandomColor(int minColorValue, int maxColorValue, Random random) { // 确保颜色值在有效范围内 int min = Math.max(0, Math.min(minColorValue, 255)); int max = Math.max(min, Math.min(maxColorValue, 255)); int range = max - min; if (range == 0) { return new Color(min, min, min); } int red = min + random.nextInt(range); int green = min + random.nextInt(range); int blue = min + random.nextInt(range); return new Color(red, green, blue); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\RandImageUtil.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<User> getUserWithAuthorities() { return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { userRepository .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) .forEach(user -> { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user);
this.clearUserCaches(user); }); } /** * @return a list of all the authorities */ public List<String> getAuthorities() { return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList()); } private void clearUserCaches(User user) { Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)).evict(user.getLogin()); Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(user.getEmail()); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\service\UserService.java
2
请完成以下Java代码
public BigDecimal getTtlNetNtryAmt() { return ttlNetNtryAmt; } /** * Sets the value of the ttlNetNtryAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTtlNetNtryAmt(BigDecimal value) { this.ttlNetNtryAmt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = 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_02\NumberAndSumOfTransactions2.java
1
请完成以下Java代码
public void setMember(String member) { this.member = member; } @CamundaQueryParam("memberOfTenant") public void setMemberOfTenant(String tenantId) { this.tenantId = tenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected GroupQuery createNewQuery(ProcessEngine engine) { return engine.getIdentityService().createGroupQuery(); } @Override protected void applyFilters(GroupQuery query) { if (id != null) { query.groupId(id); } if (ids != null) { query.groupIdIn(ids); } if (name != null) { query.groupName(name); } if (nameLike != null) { query.groupNameLike(nameLike);
} if (type != null) { query.groupType(type); } if (member != null) { query.groupMember(member); } if (tenantId != null) { query.memberOfTenant(tenantId); } } @Override protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) { query.orderByGroupName(); } else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) { query.orderByGroupType(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java
1
请完成以下Java代码
public <T extends I_PP_Order_BOMLine> List<T> retrieveOrderBOMLines( @NonNull final Collection<PPOrderId> orderIds, @NonNull final Class<T> orderBOMLineClass) { if (orderIds.isEmpty()) { return ImmutableList.of(); } return queryBL.createQueryBuilder(orderBOMLineClass) .addInArrayFilter(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID, orderIds) .addOnlyActiveRecordsFilter() .orderBy(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID) .orderBy(I_PP_Order_BOMLine.COLUMNNAME_Line) // .create() .listImmutable(orderBOMLineClass); } @Override public I_PP_Order_BOMLine retrieveOrderBOMLine(@NonNull final I_PP_Order ppOrder, @NonNull final I_M_Product product) { return queryBL.createQueryBuilder(I_PP_Order_BOMLine.class, ppOrder) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID()) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_M_Product_ID, product.getM_Product_ID()) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_PP_Order_BOMLine.class); } @Override public void deleteOrderBOMLinesByOrderId(@NonNull final PPOrderId orderId) { final List<I_PP_Order_BOMLine> lines = queryBL .createQueryBuilder(I_PP_Order_BOMLine.class) .addEqualsFilter(I_PP_Order_BOMLine.COLUMN_PP_Order_ID, orderId) // .addOnlyActiveRecordsFilter() .create() .list(); for (final I_PP_Order_BOMLine line : lines) { line.setProcessed(false); InterfaceWrapperHelper.delete(line); } } @Override public int retrieveNextLineNo(@NonNull final PPOrderId orderId) { Integer maxLine = queryBL .createQueryBuilder(I_PP_Order_BOMLine.class) .addEqualsFilter(I_PP_Order_BOMLine.COLUMNNAME_PP_Order_ID, orderId) .create() .aggregate(I_PP_Order_BOMLine.COLUMNNAME_Line, Aggregate.MAX, Integer.class); if (maxLine == null) { maxLine = 0; } final int nextLine = maxLine + 10; return nextLine; } @Override public void save(@NonNull final I_PP_Order_BOM orderBOM) { saveRecord(orderBOM); } @Override public void save(@NonNull final I_PP_Order_BOMLine orderBOMLine) {
saveRecord(orderBOMLine); } @Override public void deleteByOrderId(@NonNull final PPOrderId orderId) { final I_PP_Order_BOM orderBOM = getByOrderIdOrNull(orderId); if (orderBOM != null) { InterfaceWrapperHelper.delete(orderBOM); } } @Override public void markBOMLinesAsProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(true); save(orderBOMLine); } } @Override public void markBOMLinesAsNotProcessed(@NonNull final PPOrderId orderId) { for (final I_PP_Order_BOMLine orderBOMLine : retrieveOrderBOMLines(orderId)) { orderBOMLine.setProcessed(false); save(orderBOMLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMDAO.java
1
请完成以下Java代码
private void addBeanValidationExample() { var nameField = new TextField("Name"); var emailField = new TextField("Email"); var phoneField = new TextField("Phone"); var saveButton = new Button("Save"); var binder = new BeanValidationBinder<>(Contact.class); binder.forField(nameField).bind(Contact::getName, Contact::setName); binder.forField(emailField).bind(Contact::getEmail, Contact::setEmail); binder.forField(phoneField).bind(Contact::getPhone, Contact::setPhone); var contact = new Contact("John Doe", "john@doe.com", "123-456-7890"); binder.setBean(contact); saveButton.addClickListener(e -> { if (binder.validate().isOk()) { Notification.show("Saved " + contact); } }); add(new VerticalLayout( new H2("Bean Validation Example"), nameField, emailField, phoneField, saveButton )); } private void addCustomValidationExample() { var nameField = new TextField("Name");
var emailField = new TextField("Email"); var phoneField = new TextField("Phone"); var saveButton = new Button("Save"); var binder = new Binder<>(Contact.class); binder.forField(nameField) .asRequired() .bind(Contact::getName, Contact::setName); binder.forField(emailField) .withValidator(email -> email.contains("@"), "Not a valid email address") .bind(Contact::getEmail, Contact::setEmail); binder.forField(phoneField) .withValidator(phone -> phone.matches("\\d{3}-\\d{3}-\\d{4}"), "Not a valid phone number") .bind(Contact::getPhone, Contact::setPhone); var contact = new Contact("John Doe", "john@doe.com", "123-456-7890"); binder.setBean(contact); saveButton.addClickListener(e -> { if (binder.validate().isOk()) { Notification.show("Saved " + contact); } }); add(new VerticalLayout( new H2("Custom Validation Example"), nameField, emailField, phoneField, saveButton )); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\introduction\FormView.java
1
请完成以下Spring Boot application配置
# Application properties that need to be # embedded within the web application can be included here server: port: 8443 ssl: key-store: classpath:/etc/cas/thekeystore key-store-password: changeit spring: main: allow-bean-definition-overriding: true #cas: # authn: # accept: # users: # jdbc: # query[0]: # sql: SELECT * FROM users WHERE email = ? # url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC # dialect: org.hibernate.di
alect.MySQLDialect # user: root # password: root # ddlAuto: none # driverClass: com.mysql.cj.jdbc.Driver # fieldPassword: password # passwordEncoder: # type: NONE
repos\tutorials-master\security-modules\cas\cas-server\src\main\resources\application.yml
2