instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class AmqpServer { /* Please note that - CachingConnectionFactory - RabbitAdmin - AmqpTemplate are automatically declared by SpringBoot. */ @Bean CabBookingService bookingService() { return new CabBookingServiceImpl(); } @Bean Queue queue() { return new Queue("remotingQueue"); } @Bean AmqpInvokerServiceExporter exporter(CabBookingService implementation, AmqpTemplate template) { AmqpInvokerServiceExporter exporter = new AmqpInvokerServiceExporter();
exporter.setServiceInterface(CabBookingService.class); exporter.setService(implementation); exporter.setAmqpTemplate(template); return exporter; } @Bean SimpleMessageListenerContainer listener(ConnectionFactory factory, AmqpInvokerServiceExporter exporter, Queue queue) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(factory); container.setMessageListener(exporter); container.setQueueNames(queue.getName()); return container; } public static void main(String[] args) { SpringApplication.run(AmqpServer.class, args); } }
repos\tutorials-master\spring-remoting-modules\remoting-amqp\remoting-amqp-server\src\main\java\com\baeldung\server\AmqpServer.java
2
请完成以下Java代码
public boolean isAnagramCounting(String string1, String string2) { if (string1.length() != string2.length()) { return false; } int count[] = new int[CHARACTER_RANGE]; for (int i = 0; i < string1.length(); i++) { count[string1.charAt(i)]++; count[string2.charAt(i)]--; } for (int i = 0; i < CHARACTER_RANGE; i++) { if (count[i] != 0) { return false; } } return true; } public boolean isAnagramMultiset(String string1, String string2) { if (string1.length() != string2.length()) { return false; } Multiset<Character> multiset1 = HashMultiset.create(); Multiset<Character> multiset2 = HashMultiset.create(); for (int i = 0; i < string1.length(); i++) {
multiset1.add(string1.charAt(i)); multiset2.add(string2.charAt(i)); } return multiset1.equals(multiset2); } public boolean isLetterBasedAnagramMultiset(String string1, String string2) { return isAnagramMultiset(preprocess(string1), preprocess(string2)); } private String preprocess(String source) { return source.replaceAll("[^a-zA-Z]", "").toLowerCase(); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\anagram\Anagram.java
1
请完成以下Java代码
private static ImmutableList<Object> normalizeMultipleValues(@NonNull final Collection<?> ids) { if (ids instanceof ImmutableList) { // consider it already normalized //noinspection unchecked return (ImmutableList<Object>)ids; } else { return ids.stream() .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } } public static boolean equals(@Nullable final IdsToFilter obj1, @Nullable final IdsToFilter obj2) { return Objects.equals(obj1, obj2); } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue != null; } public boolean isMultipleValues() { return multipleValues != null; } @Nullable public Object getSingleValueAsObject() { if (noValue) { return null; } else if (singleValue != null) { return singleValue; } else { throw new AdempiereException("Not a single value instance: " + this); } } public ImmutableList<Object> getMultipleValues() { if (multipleValues != null) { return multipleValues; } else { throw new AdempiereException("Not a multiple values instance: " + this); } } @Nullable public Integer getSingleValueAsInteger(@Nullable final Integer defaultValue) { final Object value = getSingleValueAsObject(); if (value == null) { return defaultValue; } else if (value instanceof Number) { return ((Number)value).intValue(); } else { final String valueStr = StringUtils.trimBlankToNull(value.toString()); if (valueStr == null) { return defaultValue; } else { return Integer.parseInt(valueStr); } } } @Nullable public String getSingleValueAsString()
{ final Object value = getSingleValueAsObject(); return value != null ? value.toString() : null; } public Stream<IdsToFilter> streamSingleValues() { if (noValue) { return Stream.empty(); } else if (singleValue != null) { return Stream.of(this); } else { Objects.requireNonNull(multipleValues); return multipleValues.stream().map(IdsToFilter::ofSingleValue); } } public ImmutableList<Object> toImmutableList() { if (noValue) { return ImmutableList.of(); } else if (singleValue != null) { return ImmutableList.of(singleValue); } else { Objects.requireNonNull(multipleValues); return multipleValues; } } public IdsToFilter mergeWith(@NonNull final IdsToFilter other) { if (other.isNoValue()) { return this; } else if (isNoValue()) { return other; } else { final ImmutableSet<Object> multipleValues = Stream.concat(toImmutableList().stream(), other.toImmutableList().stream()) .distinct() .collect(ImmutableSet.toImmutableSet()); return ofMultipleValues(multipleValues); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\IdsToFilter.java
1
请在Spring Boot框架中完成以下Java代码
private UpsertPurchaseCandidateProcessor getUpsertPurchaseCahndidateProcessor() { return UpsertPurchaseCandidateProcessor.builder() .externalSystemRequest(enabledByExternalSystemRequest) .pInstanceLogger(pInstanceLogger) .build(); } private void updateContextAfterSuccess(@NonNull final Exchange exchange) { final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); final PurchaseOrderRow purchaseOrderRow = exchange.getProperty(PROPERTY_CURRENT_CSV_ROW, PurchaseOrderRow.class); final JsonExternalId externalHeaderId = JsonExternalId.of(purchaseOrderRow.getExternalHeaderId()); if (!importOrdersRouteContext.getPurchaseCandidatesWithError().contains(externalHeaderId)) { importOrdersRouteContext.getPurchaseCandidatesToProcess().add(externalHeaderId); } } private void updateContextAfterError(@NonNull final Exchange exchange) { final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); final PurchaseOrderRow csvRow = exchange.getProperty(PROPERTY_CURRENT_CSV_ROW, PurchaseOrderRow.class); final Exception ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); final RuntimeCamelException augmentedEx = new RuntimeCamelException("Exception processing file " + exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY) + " and row '" + csvRow + "'", ex); exchange.setProperty(Exchange.EXCEPTION_CAUGHT, augmentedEx); if (csvRow == null || Check.isBlank(csvRow.getExternalHeaderId())) { importOrdersRouteContext.errorInUnknownRow(); return; } final JsonExternalId externalHeaderId = JsonExternalId.of(csvRow.getExternalHeaderId()); importOrdersRouteContext.getPurchaseCandidatesToProcess().remove(externalHeaderId); importOrdersRouteContext.getPurchaseCandidatesWithError().add(externalHeaderId); } private void enqueueCandidatesProcessor(@NonNull final Exchange exchange)
{ final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); if (importOrdersRouteContext.isDoNotProcessAtAll()) { final Object fileName = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY); throw new RuntimeCamelException("No purchase order candidates from file " + fileName.toString() + " can be imported to metasfresh"); } final JsonPurchaseCandidatesRequest.JsonPurchaseCandidatesRequestBuilder builder = JsonPurchaseCandidatesRequest.builder(); for (final JsonExternalId externalId : importOrdersRouteContext.getPurchaseCandidatesToProcess()) { final JsonPurchaseCandidateReference reference = JsonPurchaseCandidateReference.builder() .externalSystemCode(importOrdersRouteContext.getExternalSystemCode()) .externalHeaderId(externalId) .build(); builder.purchaseCandidate(reference); } exchange.getIn().setBody(builder.build()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\GetPurchaseOrderFromFileRouteBuilder.java
2
请完成以下Java代码
protected boolean validateAtLeastOneExecutable(BpmnModel bpmnModel, List<ValidationError> errors) { int nrOfExecutableDefinitions = 0; for (Process process : bpmnModel.getProcesses()) { if (process.isExecutable()) { nrOfExecutableDefinitions++; } } if (nrOfExecutableDefinitions == 0) { addError(errors, Problems.ALL_PROCESS_DEFINITIONS_NOT_EXECUTABLE); } return nrOfExecutableDefinitions > 0; } protected List<Process> getProcessesWithSameId(final List<Process> processes) {
List<Process> filteredProcesses = processes .stream() .filter(process -> process.getName() != null) .collect(Collectors.toList()); return getDuplicatesMap(filteredProcesses) .values() .stream() .filter(duplicates -> duplicates.size() > 1) .flatMap(Collection::stream) .collect(Collectors.toList()); } private static Map<String, List<Process>> getDuplicatesMap(List<Process> processes) { return processes.stream().collect(Collectors.groupingBy(Process::getId)); } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\BpmnModelValidator.java
1
请在Spring Boot框架中完成以下Java代码
public void setLocation(String location) { this.location = location; } public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class StoreProperties { private boolean allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION; private boolean autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT; private float diskUsageCriticalPercentage = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE; private float diskUsageWarningPercentage = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE; private int compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD; private int queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE; private int writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE; private long maxOplogSize = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE; private long timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL; private DirectoryProperties[] directoryProperties = {}; public boolean isAllowForceCompaction() { return this.allowForceCompaction; } public void setAllowForceCompaction(boolean allowForceCompaction) { this.allowForceCompaction = allowForceCompaction; } public boolean isAutoCompact() { return this.autoCompact; } public void setAutoCompact(boolean autoCompact) { this.autoCompact = autoCompact; } public int getCompactionThreshold() { return this.compactionThreshold; } public void setCompactionThreshold(int compactionThreshold) { this.compactionThreshold = compactionThreshold; } public DirectoryProperties[] getDirectory() { return this.directoryProperties; } public void setDirectory(DirectoryProperties[] directoryProperties) { this.directoryProperties = directoryProperties; } public float getDiskUsageCriticalPercentage() { return this.diskUsageCriticalPercentage; } public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) { this.diskUsageCriticalPercentage = diskUsageCriticalPercentage; } public float getDiskUsageWarningPercentage() { return this.diskUsageWarningPercentage;
} public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) { this.diskUsageWarningPercentage = diskUsageWarningPercentage; } public long getMaxOplogSize() { return this.maxOplogSize; } public void setMaxOplogSize(long maxOplogSize) { this.maxOplogSize = maxOplogSize; } public int getQueueSize() { return this.queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public long getTimeInterval() { return this.timeInterval; } public void setTimeInterval(long timeInterval) { this.timeInterval = timeInterval; } public int getWriteBufferSize() { return this.writeBufferSize; } public void setWriteBufferSize(int writeBufferSize) { this.writeBufferSize = writeBufferSize; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } @Transactional public void testSoftDeletes() { System.out.println("Authors: " + authorRepository.count()); System.out.println("Books: " + bookRepository.count()); System.out.println("Deleted Authors: " + authorRepository.countDeleted()); System.out.println("Deleted Books: " + bookRepository.countDeleted()); Author author = authorRepository.fetchByName("Mark Janel"); // id 1 authorRepository.delete(author);
Book book = bookRepository.fetchByTitle("Carrie"); // id 4 bookRepository.delete(book); System.out.println("Authors: " + authorRepository.count()); System.out.println("Books: " + bookRepository.count()); System.out.println("Deleted Authors: " + authorRepository.countDeleted()); System.out.println("Deleted Books: " + bookRepository.countDeleted()); authorRepository.undeleteById(1L); bookRepository.undeleteById(4L); System.out.println("Authors: " + authorRepository.count()); System.out.println("Books: " + bookRepository.count()); System.out.println("Deleted Authors: " + authorRepository.countDeleted()); System.out.println("Deleted Books: " + bookRepository.countDeleted()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletesSpringStyle\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public List<FreeTextType> getFreeText() { if (freeText == null) { freeText = new ArrayList<FreeTextType>(); } return this.freeText; } /** * Reference to the consignment. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference;
} /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDERSExtensionType.java
2
请完成以下Java代码
public class RemoveLeadingAndTrailingZeroes { public static String removeLeadingZeroesWithStringBuilder(String s) { StringBuilder sb = new StringBuilder(s); while (sb.length() > 1 && sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.toString(); } public static String removeTrailingZeroesWithStringBuilder(String s) { StringBuilder sb = new StringBuilder(s); while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') { sb.setLength(sb.length() - 1); } return sb.toString(); } public static String removeLeadingZeroesWithSubstring(String s) { int index = 0; for (; index < s.length() - 1; index++) { if (s.charAt(index) != '0') { break; } } return s.substring(index); } public static String removeTrailingZeroesWithSubstring(String s) { int index = s.length() - 1; for (; index > 0; index--) { if (s.charAt(index) != '0') { break; } } return s.substring(0, index + 1); } public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) { String stripped = StringUtils.stripStart(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) { return "0"; } return stripped; } public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) { String stripped = StringUtils.stripEnd(s, "0"); if (stripped.isEmpty() && !s.isEmpty()) { return "0"; } return stripped; } public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) { String stripped = CharMatcher.is('0') .trimLeadingFrom(s); if (stripped.isEmpty() && !s.isEmpty()) { return "0"; } return stripped; } public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) { String stripped = CharMatcher.is('0') .trimTrailingFrom(s); if (stripped.isEmpty() && !s.isEmpty()) { return "0"; } return stripped; } public static String removeLeadingZeroesWithRegex(String s) { return s.replaceAll("^0+(?!$)", ""); } public static String removeTrailingZeroesWithRegex(String s) { return s.replaceAll("(?!^)0+$", ""); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\removeleadingtrailingchar\RemoveLeadingAndTrailingZeroes.java
1
请完成以下Java代码
public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { return null; // nothing } @Override public String modelChange(final PO po, final int type) { if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE) { if (isDocument()) { if (!acceptDocument(po)) { return null; } if (po.is_ValueChanged(IDocument.COLUMNNAME_DocStatus) && Services.get(IDocumentBL.class).isDocumentReversedOrVoided(po)) { voidDocOutbound(po); } } if (isJustProcessed(po, type)) { createDocOutbound(po); } } return null; } @Override public String docValidate(@NonNull final PO po, final int timing) { Check.assume(isDocument(), "PO '{}' is a document", po); if (!acceptDocument(po)) { return null; } if (timing == ModelValidator.TIMING_AFTER_COMPLETE && !Services.get(IDocumentBL.class).isReversalDocument(po)) { createDocOutbound(po); } if (timing == ModelValidator.TIMING_AFTER_VOID || timing == ModelValidator.TIMING_AFTER_REVERSEACCRUAL
|| timing == ModelValidator.TIMING_AFTER_REVERSECORRECT) { voidDocOutbound(po); } return null; } /** * @return true if the given PO was just processed */ private boolean isJustProcessed(final PO po, final int changeType) { if (!po.isActive()) { return false; } final boolean isNew = changeType == ModelValidator.TYPE_BEFORE_NEW || changeType == ModelValidator.TYPE_AFTER_NEW; final int idxProcessed = po.get_ColumnIndex(DocOutboundProducerValidator.COLUMNNAME_Processed); final boolean processedColumnAvailable = idxProcessed > 0; final boolean processed = processedColumnAvailable ? po.get_ValueAsBoolean(idxProcessed) : true; if (processedColumnAvailable) { if (isNew) { return processed; } else if (po.is_ValueChanged(idxProcessed)) { return processed; } else { return false; } } else // Processed column is not available { // If is not available, we always consider the record as processed right after it was created // This condition was introduced because we need to archive/print records which does not have such a column (e.g. letters) return isNew; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\DocOutboundProducerValidator.java
1
请完成以下Java代码
public int getAD_Tree_ID() { return get_ValueAsInt(COLUMNNAME_AD_Tree_ID); } @Override public void setC_Element_ID (final int C_Element_ID) { if (C_Element_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Element_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Element_ID, C_Element_ID); } @Override public int getC_Element_ID() { return get_ValueAsInt(COLUMNNAME_C_Element_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * ElementType AD_Reference_ID=116 * Reference name: C_Element Type */ public static final int ELEMENTTYPE_AD_Reference_ID=116; /** Account = A */ public static final String ELEMENTTYPE_Account = "A"; /** UserDefined = U */ public static final String ELEMENTTYPE_UserDefined = "U"; @Override public void setElementType (final java.lang.String ElementType) { set_ValueNoCheck (COLUMNNAME_ElementType, ElementType); } @Override public java.lang.String getElementType() { return get_ValueAsString(COLUMNNAME_ElementType); } @Override public void setIsBalancing (final boolean IsBalancing) { set_Value (COLUMNNAME_IsBalancing, IsBalancing); } @Override public boolean isBalancing() { return get_ValueAsBoolean(COLUMNNAME_IsBalancing);
} @Override public void setIsNaturalAccount (final boolean IsNaturalAccount) { set_Value (COLUMNNAME_IsNaturalAccount, IsNaturalAccount); } @Override public boolean isNaturalAccount() { return get_ValueAsBoolean(COLUMNNAME_IsNaturalAccount); } @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); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Element.java
1
请完成以下Java代码
public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.exists(cacheKey.getKeyBytes()); } }); if (!exists.booleanValue()) { return null; } return redisCacheElement; } /** * 刷新缓存数据 */ private void refreshCache(Object key, String cacheKeyStr) { Long ttl = this.redisOperations.getExpire(cacheKeyStr); if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) { // 尽量少的去开启线程,因为线程池是有限的 ThreadTaskUtils.run(new Runnable() { @Override public void run() { // 加一个分布式锁,只放一个请求去刷新缓存 RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock"); try { if (redisLock.lock()) { // 获取锁之后再判断一下过期时间,看是否需要加载数据 Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr); if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) { // 通过获取代理方法信息重新加载缓存数据 CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), cacheKeyStr); } } } catch (Exception e) { logger.info(e.getMessage(), e);
} finally { redisLock.unlock(); } } }); } } public long getExpirationSecondTime() { return expirationSecondTime; } /** * 获取RedisCacheKey * * @param key * @return */ public RedisCacheKey getRedisCacheKey(Object key) { return new RedisCacheKey(key).usePrefix(this.prefix) .withKeySerializer(redisOperations.getKeySerializer()); } /** * 获取RedisCacheKey * * @param key * @return */ public String getCacheKey(Object key) { return new String(getRedisCacheKey(key).getKeyBytes()); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCache.java
1
请在Spring Boot框架中完成以下Java代码
public void setLastName(String lastName) { this.lastName = lastName; } @ApiModelProperty(example = "Fred Smith") public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getPassword() { return passWord; } public void setPassword(String passWord) { this.passWord = passWord; }
@JsonInclude(JsonInclude.Include.NON_NULL) @ApiModelProperty(example = "companyTenantId") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "http://localhost:8182/identity/users/testuser/picture") public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserResponse.java
2
请完成以下Java代码
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException { PROPERTY_FILE_NAME = propertyFileName; if (sessionFactory == null) { ServiceRegistry serviceRegistry = configureServiceRegistry(); sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor) .build(); } return sessionFactory; } public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException { return getSessionFactory().withOptions() .interceptor(interceptor) .openSession(); } private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.interceptors"); metadataSources.addAnnotatedClass(User.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder(); } private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties(); return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\HibernateUtil.java
1
请完成以下Java代码
public UserOperationLogQuery orderByTimestamp() { return orderBy(OperationLogQueryProperty.TIMESTAMP); } public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet; }
public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请完成以下Java代码
public Collection<ELResolver> getPostDefaultELResolvers() { return postDefaultELResolvers; } public EventRegistryEngineConfiguration setPostDefaultELResolvers(Collection<ELResolver> postDefaultELResolvers) { this.postDefaultELResolvers = postDefaultELResolvers; return this; } public EventRegistryEngineConfiguration addPostDefaultELResolver(ELResolver elResolver) { if (this.postDefaultELResolvers == null) { this.postDefaultELResolvers = new ArrayList<>(); } this.postDefaultELResolvers.add(elResolver); return this; } public EventJsonConverter getEventJsonConverter() { return eventJsonConverter; } public EventRegistryEngineConfiguration setEventJsonConverter(EventJsonConverter eventJsonConverter) { this.eventJsonConverter = eventJsonConverter; return this; } public ChannelJsonConverter getChannelJsonConverter() { return channelJsonConverter; }
public EventRegistryEngineConfiguration setChannelJsonConverter(ChannelJsonConverter channelJsonConverter) { this.channelJsonConverter = channelJsonConverter; return this; } public boolean isEnableEventRegistryChangeDetectionAfterEngineCreate() { return enableEventRegistryChangeDetectionAfterEngineCreate; } public EventRegistryEngineConfiguration setEnableEventRegistryChangeDetectionAfterEngineCreate(boolean enableEventRegistryChangeDetectionAfterEngineCreate) { this.enableEventRegistryChangeDetectionAfterEngineCreate = enableEventRegistryChangeDetectionAfterEngineCreate; return this; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRegistryEngineConfiguration.java
1
请完成以下Java代码
public final synchronized boolean isRunning() { return frame != null && !frame.isDisposed(); } /** * Start listening to subscribed topics and display the events. * * If this was already started, this method does nothing. */ public synchronized void start() { if (!EventBusConfig.isEnabled()) { logger.info("Not starting because it's not enabled"); return; } try { if (frame != null && frame.isDisposed()) { frame = null; } if (frame == null) { frame = new SwingEventNotifierFrame(); } } catch (Exception e) { logger.warn("Failed starting the notification frame: " + frame, e); } } /** * Stop listening events and destroy the whole popup. *
* If this was already started, this method does nothing. */ public synchronized void stop() { if (frame == null) { return; } try { frame.dispose(); } catch (Exception e) { logger.warn("Failed disposing the notification frame: " + frame, e); } } public synchronized Set<String> getSubscribedTopicNames() { if (frame != null && !frame.isDisposed()) { return frame.getSubscribedTopicNames(); } else { return ImmutableSet.of(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierService.java
1
请完成以下Java代码
public CountResultDto getFiltersCount(UriInfo uriInfo) { FilterQuery query = getQueryFromQueryParameters(uriInfo.getQueryParameters()); return new CountResultDto(query.count()); } @Override public FilterDto createFilter(FilterDto filterDto) { FilterService filterService = getProcessEngine().getFilterService(); String resourceType = filterDto.getResourceType(); Filter filter; if (EntityTypes.TASK.equals(resourceType)) { filter = filterService.newTaskFilter(); } else { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unable to create filter with invalid resource type '" + resourceType + "'"); } try { filterDto.updateFilter(filter, getProcessEngine()); } catch (NotValidException e) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, e, "Unable to create filter with invalid content"); } filterService.saveFilter(filter); return FilterDto.fromFilter(filter); } protected FilterQuery getQueryFromQueryParameters(MultivaluedMap<String, String> queryParameters) { ProcessEngine engine = getProcessEngine(); FilterQueryDto queryDto = new FilterQueryDto(getObjectMapper(), queryParameters); return queryDto.toQuery(engine); }
@Override public ResourceOptionsDto availableOperations(UriInfo context) { UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(FilterRestService.PATH); ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); // GET / URI baseUri = baseUriBuilder.build(); resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); // GET /count URI countUri = baseUriBuilder.clone().path("/count").build(); resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); // POST /create if (isAuthorized(CREATE)) { URI createUri = baseUriBuilder.clone().path("/create").build(); resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); } return resourceOptionsDto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\FilterRestServiceImpl.java
1
请完成以下Java代码
public int getMKTG_Consent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Consent_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_Value (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_Value (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Consent.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricTaskLogEntry(long logEntryNumber) { getDbSqlSession().delete("deleteHistoricTaskLogEntryByLogNumber", logEntryNumber, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByProcessDefinitionId(String processDefinitionId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByProcessDefinitionId", processDefinitionId, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByScopeDefinitionId(String scopeType, String scopeDefinitionId) { Map<String, String> params = new HashMap<>(2); params.put("scopeDefinitionId", scopeDefinitionId); params.put("scopeType", scopeType); getDbSqlSession().delete("deleteHistoricTaskLogEntriesByScopeDefinitionId", params, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesByTaskId(String taskId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByTaskId", taskId, HistoricTaskLogEntryEntityImpl.class); } @Override public void bulkDeleteHistoricTaskLogEntriesForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForTaskIds", createSafeInValuesList(taskIds), HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances", null, HistoricTaskLogEntryEntityImpl.class);
} @Override public void deleteHistoricTaskLogEntriesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances", null, HistoricTaskLogEntryEntityImpl.class); } @Override public long findHistoricTaskLogEntriesCountByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricTaskLogEntriesCountByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override public List<HistoricTaskLogEntry> findHistoricTaskLogEntriesByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return getDbSqlSession().selectListWithRawParameter("selectHistoricTaskLogEntriesByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MyBatisHistoricTaskLogEntryDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public R update(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.updateById(topMenu)); } /** * 新增或修改 顶部菜单表 */ @PostMapping("/submit") @ApiOperationSupport(order = 6) @Operation(summary = "新增或修改", description = "传入topMenu") public R submit(@Valid @RequestBody TopMenu topMenu) { return R.status(topMenuService.saveOrUpdate(topMenu)); } /** * 删除 顶部菜单表 */ @PostMapping("/remove") @ApiOperationSupport(order = 7) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { return R.status(topMenuService.deleteLogic(Func.toLongList(ids))); }
/** * 设置顶部菜单 */ @PostMapping("/grant") @ApiOperationSupport(order = 8) @Operation(summary = "顶部菜单配置", description = "传入topMenuId集合以及menuId集合") public R grant(@RequestBody GrantVO grantVO) { CacheUtil.clear(SYS_CACHE); CacheUtil.clear(MENU_CACHE); CacheUtil.clear(MENU_CACHE); boolean temp = topMenuService.grant(grantVO.getTopMenuIds(), grantVO.getMenuIds()); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\TopMenuController.java
2
请完成以下Java代码
public static void main(String[] args) throws IOException { MyJiraClient myJiraClient = new MyJiraClient("user.name", "pass", "http://jira.company.com"); final String issueKey = myJiraClient.createIssue("ABCD", 1L, "Issue created from JRJC"); myJiraClient.updateIssueDescription(issueKey, "This is description from my Jira Client"); Issue issue = myJiraClient.getIssue(issueKey); System.out.println(issue.getDescription()); myJiraClient.voteForAnIssue(issue); System.out.println(myJiraClient.getTotalVotesCount(issueKey)); myJiraClient.addComment(issue, "This is comment from my Jira Client"); List<Comment> comments = myJiraClient.getAllComments(issueKey); comments.forEach(c -> System.out.println(c.getBody())); myJiraClient.deleteIssue(issueKey, true); myJiraClient.restClient.close(); } private String createIssue(String projectKey, Long issueType, String issueSummary) { IssueRestClient issueClient = restClient.getIssueClient(); IssueInput newIssue = new IssueInputBuilder(projectKey, issueType, issueSummary).build(); return issueClient.createIssue(newIssue).claim().getKey(); } private Issue getIssue(String issueKey) { return restClient.getIssueClient().getIssue(issueKey).claim(); } private void voteForAnIssue(Issue issue) { restClient.getIssueClient().vote(issue.getVotesUri()).claim(); } private int getTotalVotesCount(String issueKey) { BasicVotes votes = getIssue(issueKey).getVotes(); return votes == null ? 0 : votes.getVotes();
} private void addComment(Issue issue, String commentBody) { restClient.getIssueClient().addComment(issue.getCommentsUri(), Comment.valueOf(commentBody)); } private List<Comment> getAllComments(String issueKey) { return StreamSupport.stream(getIssue(issueKey).getComments().spliterator(), false) .collect(Collectors.toList()); } private void updateIssueDescription(String issueKey, String newDescription) { IssueInput input = new IssueInputBuilder().setDescription(newDescription).build(); restClient.getIssueClient().updateIssue(issueKey, input).claim(); } private void deleteIssue(String issueKey, boolean deleteSubtasks) { restClient.getIssueClient().deleteIssue(issueKey, deleteSubtasks).claim(); } private JiraRestClient getJiraRestClient() { return new AsynchronousJiraRestClientFactory() .createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password); } private URI getJiraUri() { return URI.create(this.jiraUrl); } }
repos\tutorials-master\saas-modules\jira-rest-integration\src\main\java\com\baeldung\saas\jira\MyJiraClient.java
1
请完成以下Java代码
private static void search() { int[] anArray = new int[] {5, 2, 1, 4, 8}; for (int i = 0; i < anArray.length; i++) { if (anArray[i] == 4) { System.out.println("Found at index " + i); break; } } Arrays.sort(anArray); int index = Arrays.binarySearch(anArray, 4); System.out.println("Found at index " + index); } private static void merge() { int[] anArray = new int[] {5, 2, 1, 4, 8}; int[] anotherArray = new int[] {10, 4, 9, 11, 2};
int[] resultArray = new int[anArray.length + anotherArray.length]; for (int i = 0; i < resultArray.length; i++) { resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]); } for (int element : resultArray) { System.out.println(element); } Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length])); for (int element : resultArray) { System.out.println(element); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\array\ArrayReferenceGuide.java
1
请在Spring Boot框架中完成以下Java代码
public class PayPalCreateLogRequest { String requestPath; String requestMethod; ImmutableMap<String, String> requestHeaders; String requestBodyAsJson; int responseStatusCode; ImmutableMap<String, String> responseHeaders; String responseBodyAsJson; PaymentReservationId paymentReservationId; PaymentReservationCaptureId paymentReservationCaptureId; OrderId salesOrderId; InvoiceId salesInvoiceId; PaymentId paymentId; PayPalOrderId internalPayPalOrderId; public static class PayPalCreateLogRequestBuilder { public PayPalCreateLogRequestBuilder request(@NonNull final HttpRequest<?> request) { requestPath(request.path()); requestMethod(request.verb()); requestHeaders(toMap(request.headers())); requestBodyAsJson(toJsonString(request.requestBody())); return this; } public PayPalCreateLogRequestBuilder response(@NonNull final HttpResponse<?> response) { responseStatusCode(response.statusCode()); responseHeaders(toMap(response.headers())); responseBodyAsJson(toJsonString(response.result())); return this; } public PayPalCreateLogRequestBuilder response(@NonNull final Throwable ex) { if (ex instanceof HttpException) { final HttpException httpException = (HttpException)ex; responseStatusCode(httpException.statusCode()); responseHeaders(toMap(httpException.headers())); responseBodyAsJson(httpException.getMessage()); } else { responseStatusCode(0); responseHeaders(ImmutableMap.of()); responseBodyAsJson(Util.dumpStackTraceToString(ex)); } return this;
} private static ImmutableMap<String, String> toMap(final Headers headers) { if (headers == null) { return ImmutableMap.of(); } final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (final String header : headers) { final String value = headers.header(header); final String headerNorm = CoalesceUtil.coalesce(header, ""); final String valueNorm = CoalesceUtil.coalesce(value, ""); builder.put(headerNorm, valueNorm); } return builder.build(); } private static String toJsonString(final Object obj) { if (obj == null) { return ""; } try { return new Json().serialize(obj); } catch (final Exception ex) { return obj.toString(); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\logs\PayPalCreateLogRequest.java
2
请完成以下Java代码
public void setPostal (final @Nullable java.lang.String Postal) { set_Value (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setSiteName (final @Nullable java.lang.String SiteName) {
set_ValueNoCheck (COLUMNNAME_SiteName, SiteName); } @Override public java.lang.String getSiteName() { return get_ValueAsString(COLUMNNAME_SiteName); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) { set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_119_v.java
1
请完成以下Java代码
public void setQtyProcessed_OnDate (final @Nullable BigDecimal QtyProcessed_OnDate) { set_Value (COLUMNNAME_QtyProcessed_OnDate, QtyProcessed_OnDate); } @Override public BigDecimal getQtyProcessed_OnDate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed_OnDate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToProcess (final @Nullable BigDecimal QtyToProcess) { set_Value (COLUMNNAME_QtyToProcess, QtyToProcess); } @Override public BigDecimal getQtyToProcess() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(final org.compiere.model.I_S_Resource S_Resource) {
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource); } @Override public void setS_Resource_ID (final int S_Resource_ID) { if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation); } @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_Value (COLUMNNAME_WorkStation_ID, null); else set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Candidate.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtAuthApplication implements CommandLineRunner { @Autowired UserService userService; public static void main(String[] args) { SpringApplication.run(JwtAuthApplication.class, args); } @Bean public ModelMapper modelMapper() { return new ModelMapper(); } @Override
public void run(String... params) throws Exception { User admin = new User(); admin.setUsername("admin"); admin.setPassword("admin"); admin.setEmail("admin@email.com"); admin.setRoles(new ArrayList<Role>(Arrays.asList(Role.ROLE_ADMIN))); userService.signup(admin); User client = new User(); client.setUsername("client"); client.setPassword("client"); client.setEmail("client@email.com"); client.setRoles(new ArrayList<Role>(Arrays.asList(Role.ROLE_CLIENT))); userService.signup(client); } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\JwtAuthApplication.java
2
请完成以下Java代码
public class AD_User_ExpireLocks extends JavaProcess { @Override protected String doIt() throws Exception { final int accountLockExpire = Services.get(ISysConfigBL.class).getIntValue("USERACCOUNT_LOCK_EXPIRE", 30); final String sql = "SELECT * FROM AD_User" + " WHERE IsAccountLocked = 'Y'"; PreparedStatement pstmt = null; ResultSet rs = null; int no = 0; try { pstmt = DB.prepareStatement(sql, get_TrxName()); rs = pstmt.executeQuery(); while (rs.next()) { final int AD_User_IDToUnlock = rs.getInt(org.compiere.model.I_AD_User.COLUMNNAME_AD_User_ID); no = no + unlockUser(accountLockExpire, AD_User_IDToUnlock); } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return "Unlock accounts: " + no; } // doIt private int unlockUser(final int accountLockExpire, final int AD_User_IDToUnlock) { final int result[] = { 0 }; Services.get(ITrxManager.class).runInNewTrx(new TrxRunnable() { @Override
public void run(final String localTrxName) throws Exception { final org.compiere.model.I_AD_User user = InterfaceWrapperHelper.create(getCtx(), AD_User_IDToUnlock, I_AD_User.class, localTrxName); final Timestamp curentLogin = (new Timestamp(System.currentTimeMillis())); final long loginFailureTime = user.getLoginFailureDate().getTime(); final long newloginFailureTime = loginFailureTime + (1000 * 60 * accountLockExpire); final Timestamp acountUnlock = new Timestamp(newloginFailureTime); if (curentLogin.compareTo(acountUnlock) > 0) { user.setLoginFailureCount(0); user.setIsAccountLocked(false); InterfaceWrapperHelper.save(user); result[0] = 1; } } }); return result[0]; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_ExpireLocks.java
1
请完成以下Java代码
public static JsonArray getArray(JsonObject json, String memberName) { if (json != null && memberName != null && json.has(memberName)) { return getArray(json.get(memberName)); } else { return createArray(); } } public static JsonArray getArray(JsonElement json) { if (json != null && json.isJsonArray()) { return json.getAsJsonArray(); } else { return createArray(); } } public static JsonObject getObject(JsonObject json, String memberName) { if (json != null && memberName != null && json.has(memberName)) { return getObject(json.get(memberName)); } else { return createObject(); } } public static JsonObject getObject(JsonElement json) { if (json != null && json.isJsonObject()) { return json.getAsJsonObject(); } else { return createObject(); } } public static JsonObject createObject() { return new JsonObject(); } public static JsonArray createArray() { return new JsonArray(); } public static Gson getGsonMapper() { return gsonMapper; }
public static Gson createGsonMapper() { return new GsonBuilder() .serializeNulls() .registerTypeAdapter(Map.class, new JsonDeserializer<Map<String,Object>>() { public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, JsonElement> entry : getObject(json).entrySet()) { if (entry != null) { String key = entry.getKey(); JsonElement jsonElement = entry.getValue(); if (jsonElement != null && jsonElement.isJsonNull()) { map.put(key, null); } else if (jsonElement != null && jsonElement.isJsonPrimitive()) { Object rawValue = asPrimitiveObject((JsonPrimitive) jsonElement); if (rawValue != null) { map.put(key, rawValue); } } } } return map; } }) .create(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\JsonUtil.java
1
请完成以下Java代码
public void setEnvironment(@Nullable Environment environment) { this.environment = environment; } protected Optional<Environment> getEnvironment() { return Optional.ofNullable(this.environment); } public @NonNull CrudRepository<T, ID> getRepository() { return this.repository; } protected <S, R> R doRepositoryOp(S entity, Function<S, R> repositoryOperation) { try { return repositoryOperation.apply(entity); } catch (Throwable cause) { throw newCacheRuntimeException(() -> String.format(DATA_ACCESS_ERROR, entity), cause); } } @Override
public T load(LoaderHelper<ID, T> helper) throws CacheLoaderException { return null; } protected abstract CacheRuntimeException newCacheRuntimeException( Supplier<String> messageSupplier, Throwable cause); @SuppressWarnings("unchecked") public <U extends RepositoryCacheLoaderWriterSupport<T, ID>> U with(Environment environment) { setEnvironment(environment); return (U) this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\support\RepositoryCacheLoaderWriterSupport.java
1
请在Spring Boot框架中完成以下Java代码
public Mono<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() { removeNotActivatedUsersReactively().blockLast(); } @Transactional public Flux<User> removeNotActivatedUsersReactively() {
return userRepository .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore( LocalDateTime.ofInstant(Instant.now().minus(3, ChronoUnit.DAYS), ZoneOffset.UTC) ) .flatMap(user -> userRepository.delete(user).thenReturn(user)) .doOnNext(user -> log.debug("Deleted User: {}", user)); } /** * Gets a list of all the authorities. * @return a list of all the authorities. */ @Transactional(readOnly = true) public Flux<String> getAuthorities() { return authorityRepository.findAll().map(Authority::getName); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultSecuritySettingsService implements SecuritySettingsService { private final AdminSettingsService adminSettingsService; public static final int DEFAULT_MOBILE_SECRET_KEY_LENGTH = 64; @Cacheable(cacheNames = SECURITY_SETTINGS_CACHE, key = "'securitySettings'") @Override public SecuritySettings getSecuritySettings() { AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "securitySettings"); SecuritySettings securitySettings; if (adminSettings != null) { try { securitySettings = JacksonUtil.convertValue(adminSettings.getJsonValue(), SecuritySettings.class); } catch (Exception e) { throw new RuntimeException("Failed to load security settings!", e); } } else { securitySettings = new SecuritySettings(); securitySettings.setPasswordPolicy(new UserPasswordPolicy()); securitySettings.getPasswordPolicy().setMinimumLength(6); securitySettings.getPasswordPolicy().setMaximumLength(72); securitySettings.setMobileSecretKeyLength(DEFAULT_MOBILE_SECRET_KEY_LENGTH); securitySettings.setPasswordResetTokenTtl(24); securitySettings.setUserActivationTokenTtl(24); } return securitySettings; }
@CacheEvict(cacheNames = SECURITY_SETTINGS_CACHE, key = "'securitySettings'") @Override public SecuritySettings saveSecuritySettings(SecuritySettings securitySettings) { ConstraintValidator.validateFields(securitySettings); AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "securitySettings"); if (adminSettings == null) { adminSettings = new AdminSettings(); adminSettings.setTenantId(TenantId.SYS_TENANT_ID); adminSettings.setKey("securitySettings"); } adminSettings.setJsonValue(JacksonUtil.valueToTree(securitySettings)); AdminSettings savedAdminSettings = adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminSettings); try { return JacksonUtil.convertValue(savedAdminSettings.getJsonValue(), SecuritySettings.class); } catch (Exception e) { throw new RuntimeException("Failed to load security settings!", e); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\settings\DefaultSecuritySettingsService.java
2
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; public BookstoreService(AuthorRepository authorRepository) { this.authorRepository = authorRepository; } public void persistAuthorWithBooks() { Author author = new Author() .name("Joana Nimar") .age(34) .genre("History") .addBook(new Book() .title("A History of Ancient Prague") .isbn("001-JN"))
.addBook(new Book() .title("A People's History") .isbn("002-JN")); authorRepository.save(author); } @Transactional(readOnly = true) public void displayAuthorWithBooks() { Author author = authorRepository.findByName("Joana Nimar"); System.out.println(author + " Books: " + author.getBooks()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFluentApiAdditionalMethods\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public DmnDeploymentBuilder addDmnBytes(String resourceName, byte[] dmnBytes) { if (dmnBytes == null) { throw new FlowableException("dmn bytes is null"); } DmnResourceEntity resource = resourceEntityManager.create(); resource.setName(resourceName); resource.setBytes(dmnBytes); deployment.addResource(resource); return this; } @Override public DmnDeploymentBuilder addDmnModel(String resourceName, DmnDefinition dmnDefinition) { DmnXMLConverter dmnXMLConverter = new DmnXMLConverter(); String dmn20Xml = new String(dmnXMLConverter.convertToXML(dmnDefinition), StandardCharsets.UTF_8); addString(resourceName, dmn20Xml); return this; } @Override public DmnDeploymentBuilder name(String name) { deployment.setName(name); return this; } @Override public DmnDeploymentBuilder category(String category) { deployment.setCategory(category); return this; } @Override public DmnDeploymentBuilder disableSchemaValidation() { this.isDmn20XsdValidationEnabled = false; return this; } @Override public DmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this;
} @Override public DmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public DmnDeploymentBuilder enableDuplicateFiltering() { isDuplicateFilterEnabled = true; return this; } @Override public DmnDeployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public DmnDeploymentEntity getDeployment() { return deployment; } public boolean isDmnXsdValidationEnabled() { return isDmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\repository\DmnDeploymentBuilderImpl.java
2
请完成以下Java代码
public static Rabbit createRabbitUsingClassNewInstance() throws InstantiationException, IllegalAccessException { Rabbit rabbit = Rabbit.class.newInstance(); return rabbit; } public static Rabbit createRabbitUsingConstructorNewInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Rabbit rabbit = Rabbit.class.getConstructor().newInstance(); return rabbit; } public static ClonableRabbit createRabbitUsingClone(ClonableRabbit originalRabbit) throws CloneNotSupportedException { ClonableRabbit clonedRabbit = (ClonableRabbit) originalRabbit.clone(); return clonedRabbit; } public static SerializableRabbit createRabbitUsingDeserialization(File file) throws IOException, ClassNotFoundException { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis);) { return (SerializableRabbit) ois.readObject(); } } public static Rabbit createRabbitUsingSupplier() { Supplier<Rabbit> rabbitSupplier = Rabbit::new;
Rabbit rabbit = rabbitSupplier.get(); return rabbit; } public static Rabbit[] createRabbitArray() { Rabbit[] rabbitArray = new Rabbit[10]; return rabbitArray; } public static RabbitType createRabbitTypeEnum() { return RabbitType.PET; //any RabbitType could be returned here, PET is just an example. } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\objectcreation\utils\CreateRabbits.java
1
请在Spring Boot框架中完成以下Java代码
public RouterFunction<ServerResponse> and(RouterFunction<ServerResponse> other) { return this.provider.getRouterFunction().and(other); } @Override public RouterFunction<?> andOther(RouterFunction<?> other) { return this.provider.getRouterFunction().andOther(other); } @Override public RouterFunction<ServerResponse> andRoute(RequestPredicate predicate, HandlerFunction<ServerResponse> handlerFunction) { return this.provider.getRouterFunction().andRoute(predicate, handlerFunction); } @Override public RouterFunction<ServerResponse> andNest(RequestPredicate predicate, RouterFunction<ServerResponse> routerFunction) { return this.provider.getRouterFunction().andNest(predicate, routerFunction); } @Override public <S extends ServerResponse> RouterFunction<S> filter( HandlerFilterFunction<ServerResponse, S> filterFunction) { return this.provider.getRouterFunction().filter(filterFunction); } @Override public void accept(RouterFunctions.Visitor visitor) { this.provider.getRouterFunction().accept(visitor); }
@Override public RouterFunction<ServerResponse> withAttribute(String name, Object value) { return this.provider.getRouterFunction().withAttribute(name, value); } @Override public RouterFunction<ServerResponse> withAttributes(Consumer<Map<String, Object>> attributesConsumer) { return this.provider.getRouterFunction().withAttributes(attributesConsumer); } @Override public Optional<HandlerFunction<ServerResponse>> route(ServerRequest request) { return this.provider.getRouterFunction().route(request); } @Override public String toString() { return this.provider.getRouterFunction().toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcPropertiesBeanDefinitionRegistrar.java
2
请完成以下Java代码
public static MStatus[] getClosed (Properties ctx) { int AD_Client_ID = Env.getAD_Client_ID(ctx); String sql = "SELECT * FROM R_Status " + "WHERE AD_Client_ID=? AND IsActive='Y' AND IsClosed='Y' " + "ORDER BY Value"; ArrayList<MStatus> list = new ArrayList<MStatus>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt(1, AD_Client_ID); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add(new MStatus (ctx, rs, null)); rs.close (); pstmt.close (); pstmt = null; } catch (SQLException ex) { s_log.error(sql, ex); } try { if (pstmt != null) pstmt.close (); } catch (SQLException ex1) { } pstmt = null; MStatus[] retValue = new MStatus[list.size()]; list.toArray(retValue); return retValue; } // get /** Static Logger */ private static Logger s_log = LogManager.getLogger(MStatus.class); /** Cache */ static private CCache<Integer,MStatus> s_cache = new CCache<Integer,MStatus> ("R_Status", 10); /** Default Cache (Key=Client) */ static private CCache<Integer,MStatus> s_cacheDefault = new CCache<Integer,MStatus>("R_Status", 10); /************************************************************************** * Default Constructor * @param ctx context * @param R_Status_ID is * @param trxName trx */ public MStatus (Properties ctx, int R_Status_ID, String trxName) { super (ctx, R_Status_ID, trxName); if (R_Status_ID == 0)
{ // setValue (null); // setName (null); setIsClosed (false); // N setIsDefault (false); setIsFinalClose (false); // N setIsOpen (false); setIsWebCanUpdate (true); } } // MStatus /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MStatus (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MStatus /** * Before Save * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) { if (isOpen() && isClosed()) setIsClosed(false); if (isFinalClose() && !isClosed()) setIsFinalClose(false); // if (!isWebCanUpdate() && getUpdate_Status_ID() != 0) setUpdate_Status_ID(0); if (getTimeoutDays() == 0 && getNext_Status_ID() != 0) setNext_Status_ID(0); // return true; } // beforeSave /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MStatus["); sb.append(get_ID()).append("-").append(getName()) .append ("]"); return sb.toString (); } // toString } // MStatus
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MStatus.java
1
请在Spring Boot框架中完成以下Java代码
public RestIdentityLink createIdentityLink(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId, @RequestBody RestIdentityLink identityLink) { ProcessDefinition processDefinition = getProcessDefinitionFromRequestWithoutAccessCheck(processDefinitionId); if (identityLink.getGroup() == null && identityLink.getUser() == null) { throw new FlowableIllegalArgumentException("A group or a user is required to create an identity link."); } if (identityLink.getGroup() != null && identityLink.getUser() != null) { throw new FlowableIllegalArgumentException("Only one of user or group can be used to create an identity link."); } if (restApiInterceptor != null) { restApiInterceptor.createProcessDefinitionIdentityLink(processDefinition, identityLink); }
if (identityLink.getGroup() != null) { repositoryService.addCandidateStarterGroup(processDefinition.getId(), identityLink.getGroup()); } else { repositoryService.addCandidateStarterUser(processDefinition.getId(), identityLink.getUser()); } // Always candidate for process-definition. User-provided value is // ignored identityLink.setType(IdentityLinkType.CANDIDATE); return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), null, processDefinition.getId(), null); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionIdentityLinkCollectionResource.java
2
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToOne Preference preference; public String getName() { return name; } public void setName(String name) { this.name = name; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Preference getPreference() { return preference; } public void setPreference(Preference preference) { this.preference = preference; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\model\User.java
2
请完成以下Java代码
public class StreamIndices { public static List<String> getEvenIndexedStrings(String[] names) { List<String> evenIndexedNames = IntStream.range(0, names.length) .filter(i -> i % 2 == 0) .mapToObj(i -> names[i]) .collect(Collectors.toList()); return evenIndexedNames; } public List<String> getEvenIndexedStringsVersionTwo(List<String> names) { List<String> evenIndexedNames = EntryStream.of(names) .filterKeyValue((index, name) -> index % 2 == 0) .values() .toList(); return evenIndexedNames; } public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) { List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream()) .filter(i -> i.getIndex() % 2 == 0) .collect(Collectors.toList()); return list; } public static List<Indexed<String>> getOddIndexedStrings(List<String> names) { List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream()) .filter(i -> i.getIndex() % 2 == 1) .collect(Collectors.toList()); return list; } public static List<String> getOddIndexedStrings(String[] names) { List<String> oddIndexedNames = IntStream.range(0, names.length) .filter(i -> i % 2 == 1) .mapToObj(i -> names[i]) .collect(Collectors.toList()); return oddIndexedNames; } public static List<String> getOddIndexedStringsVersionTwo(String[] names) { List<String> oddIndexedNames = Stream.of(names) .zipWithIndex() .filter(tuple -> tuple._2 % 2 == 1)
.map(tuple -> tuple._1) .toJavaList(); return oddIndexedNames; } public static List<String> getEvenIndexedStringsUsingAtomicInteger(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } public static List<String> getEvenIndexedStringsAtomicIntegerParallel(String[] names) { AtomicInteger index = new AtomicInteger(0); return Arrays.stream(names) .parallel() .filter(name -> index.getAndIncrement() % 2 == 0) .collect(Collectors.toList()); } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\StreamIndices.java
1
请完成以下Java代码
protected final String doIt() { newPaymentsViewAllocateCommand() .run(); // NOTE: the payment and invoice rows will be automatically invalidated (via a cache reset), // when the payment allocation is processed return MSG_OK; } @Override protected void postProcess(final boolean success) { // FIXME: until https://github.com/metasfresh/me03/issues/3388 is fixed, // as a workaround we have to invalidate the whole views invalidatePaymentsAndInvoicesViews(); } protected final PaymentsViewAllocateCommand newPaymentsViewAllocateCommand() {
final PaymentsViewAllocateCommandBuilder builder = PaymentsViewAllocateCommand.builder() .moneyService(moneyService) .invoiceProcessingServiceCompanyService(invoiceProcessingServiceCompanyService) // .paymentRows(getPaymentRowsSelectedForAllocation()) .invoiceRows(getInvoiceRowsSelectedForAllocation()) .allowPurchaseSalesInvoiceCompensation(paymentAllocationBL.isPurchaseSalesInvoiceCompensationAllowed()); customizePaymentsViewAllocateCommandBuilder(builder); return builder.build(); } protected void customizePaymentsViewAllocateCommandBuilder(@NonNull final PaymentsViewAllocateCommandBuilder builder) { // nothing on this level } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_Allocate_Template.java
1
请在Spring Boot框架中完成以下Java代码
public void setFREETEXTCODE(String value) { this.freetextcode = value; } /** * Gets the value of the freetextlanguage property. * * @return * possible object is * {@link String } * */ public String getFREETEXTLANGUAGE() { return freetextlanguage; } /** * Sets the value of the freetextlanguage property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTLANGUAGE(String value) { this.freetextlanguage = value; } /** * Gets the value of the freetextfunction property. * * @return * possible object is * {@link String }
* */ public String getFREETEXTFUNCTION() { return freetextfunction; } /** * Sets the value of the freetextfunction property. * * @param value * allowed object is * {@link String } * */ public void setFREETEXTFUNCTION(String value) { this.freetextfunction = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTEXT1.java
2
请完成以下Java代码
protected final void assertConfigurable() { if (!_configurable) { throw new HUException("This producer is not configurable anymore: " + this); } } @Override public final IHUProducerAllocationDestination setHUClearanceStatusInfo(final ClearanceStatusInfo huClearanceStatusInfo) { assertConfigurable(); _huClearanceStatusInfo = huClearanceStatusInfo; return this; } public final ClearanceStatusInfo getHUClearanceStatusInfo() { return _huClearanceStatusInfo; } private void destroyCurrentHU(final HUListCursor currentHUCursor, final IHUContext huContext) { final I_M_HU hu = currentHUCursor.current(); if (hu == null) { return; // shall not happen }
currentHUCursor.closeCurrent(); // close the current position of this cursor // since _createdNonAggregateHUs is just a subset of _createdHUs, we don't know if 'hu' was in there to start with. All we care is that it's not in _createdNonAggregateHUs after this method. _createdNonAggregateHUs.remove(hu); final boolean removedFromCreatedHUs = _createdHUs.remove(hu); Check.assume(removedFromCreatedHUs, "Cannot destroy {} because it wasn't created by us", hu); // Delete only those HUs which were internally created by THIS producer if (DYNATTR_Producer.getValue(hu) == this) { final Supplier<IAutoCloseable> getDontDestroyParentLUClosable = () -> { final I_M_HU lu = handlingUnitsBL.getLoadingUnitHU(hu); return lu != null ? huContext.temporarilyDontDestroyHU(HuId.ofRepoId(lu.getM_HU_ID())) : () -> { }; }; try (final IAutoCloseable ignored = getDontDestroyParentLUClosable.get()) { handlingUnitsBL.destroyIfEmptyStorage(huContext, hu); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractProducerDestination.java
1
请完成以下Java代码
private static final class ManagedOperationInfo { private final String description; private final Method operation; private ManagedOperationInfo(String description, Method operation) { this.description = description; this.operation = operation; } public String getDescription() { return description; } public Method getOperation() {
return operation; } @Override public String toString() { return "ManagedOperationInfo: [" + operation + "]"; } } private static final class MBeanAttributesAndOperations { private Map<String, ManagedAttributeInfo> attributes; private Set<ManagedOperationInfo> operations; } }
repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\MBeanInfoAssembler.java
1
请在Spring Boot框架中完成以下Java代码
public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket postsApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.urunov.controller")) .paths(regex("/api.*")) .build() .apiInfo(metaData()); } private ApiInfo metaData() { return new ApiInfoBuilder() .title("Full Stack: Spring Boot and React JS for the Shopping Mall") .description("\"Shopping Mall")
.version("1.0.0") .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") .contact(new Contact("Urunov Hamdamboy", "https://github.com/urunov/", "myindexu@gamil.com")) .build(); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\configure\SwaggerConfig.java
2
请完成以下Java代码
public Interface newInstance(ModelTypeInstanceContext instanceContext) { return new InterfaceImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .required() .build(); implementationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION_REF) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); operationCollection = sequenceBuilder.elementCollection(Operation.class) .required() .build(); typeBuilder.build(); } public InterfaceImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) {
nameAttribute.setValue(this, name); } public String getImplementationRef() { return implementationRefAttribute.getValue(this); } public void setImplementationRef(String implementationRef) { implementationRefAttribute.setValue(this, implementationRef); } public Collection<Operation> getOperations() { return operationCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\InterfaceImpl.java
1
请完成以下Java代码
public String getID() { if (m_key == -1) return null; return String.valueOf(m_key); } // getID /** * Equals * * @param obj object * @return true if equal */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof KeyNamePair) {
KeyNamePair pp = (KeyNamePair)obj; if (pp.getKey() == m_key && pp.getName() != null && pp.getName().equals(getName())) return true; return false; } return false; } // equals @Override public int hashCode() { return Objects.hash(m_key); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\KeyNamePair.java
1
请完成以下Java代码
public class ConversationLinkImpl extends BaseElementImpl implements ConversationLink { protected static Attribute<String> nameAttribute; protected static AttributeReference<InteractionNode> sourceRefAttribute; protected static AttributeReference<InteractionNode> targetRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ConversationLink.class, BPMN_ELEMENT_CONVERSATION_LINK) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<ConversationLink>() { public ConversationLink newInstance(ModelTypeInstanceContext instanceContext) { return new ConversationLinkImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF) .required() .qNameAttributeReference(InteractionNode.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF) .required() .qNameAttributeReference(InteractionNode.class) .build(); typeBuilder.build(); } public ConversationLinkImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); }
public void setName(String name) { nameAttribute.setValue(this, name); } public InteractionNode getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(InteractionNode source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public InteractionNode getTarget() { return targetRefAttribute.getReferenceTargetElement(this); } public void setTarget(InteractionNode target) { targetRefAttribute.setReferenceTargetElement(this, target); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConversationLinkImpl.java
1
请完成以下Java代码
public String getDeviceId() { return deviceId; } public void updateDeviceIdPlus(String deviceIdNew) { this.deviceId = this.deviceId.equals("+") ? deviceIdNew : this.deviceId; } /** * Returns the Host Application ID if this is a Host topic * * @return the Host Application ID */ public String getHostApplicationId() { return hostApplicationId; } /** * Returns the message type. * * @return the message type */ public SparkplugMessageType getType() { return type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (hostApplicationId == null) { sb.append(getNamespace()).append("/").append(getGroupId()).append("/").append(getType()).append("/") .append(getEdgeNodeId()); if (getDeviceId() != null) { sb.append("/").append(getDeviceId()); } } else { sb.append(getNamespace()).append("/").append(getType()).append("/").append(hostApplicationId); }
return sb.toString(); } /** * @param type the type to check * @return true if this topic's type matches the passes in type, false otherwise */ public boolean isType(SparkplugMessageType type) { return this.type != null && this.type.equals(type); } public boolean isNode() { return this.deviceId == null; } public String getNodeDeviceName() { return isNode() ? edgeNodeId : deviceId; } public static boolean isValidIdElementToUTF8(String deviceIdElement) { if (deviceIdElement == null) { return false; } String regex = "^(?!.*//)[^+#]*$"; return deviceIdElement.matches(regex); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugTopic.java
1
请在Spring Boot框架中完成以下Java代码
public void setDocumentTitle(String value) { this.documentTitle = value; } /** * The language used throughout the document. Codes according to ISO 639-2 must be used. * * @return * possible object is * {@link String } * */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } /** * @Deprecated. Indicates whether prices in this document are provided in gross or in net. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsGrossPrice() {
return isGrossPrice; } /** * Sets the value of the isGrossPrice property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsGrossPrice(Boolean value) { this.isGrossPrice = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DocumentType.java
2
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractVisitInterval insuranceContractVisitInterval = (InsuranceContractVisitInterval) o; return Objects.equals(this.frequency, insuranceContractVisitInterval.frequency) && Objects.equals(this.amount, insuranceContractVisitInterval.amount) && Objects.equals(this.timePeriod, insuranceContractVisitInterval.timePeriod) && Objects.equals(this.annotation, insuranceContractVisitInterval.annotation); } @Override public int hashCode() { return Objects.hash(frequency, amount, timePeriod, annotation); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractVisitInterval {\n");
sb.append(" frequency: ").append(toIndentedString(frequency)).append("\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractVisitInterval.java
2
请完成以下Java代码
public class TomcatDataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<DataSource> { public TomcatDataSourcePoolMetadata(DataSource dataSource) { super(dataSource); } @Override public @Nullable Integer getActive() { ConnectionPool pool = getDataSource().getPool(); return (pool != null) ? pool.getActive() : 0; } @Override public @Nullable Integer getIdle() { return getDataSource().getNumIdle(); } @Override public @Nullable Integer getMax() {
return getDataSource().getMaxActive(); } @Override public @Nullable Integer getMin() { return getDataSource().getMinIdle(); } @Override public @Nullable String getValidationQuery() { return getDataSource().getValidationQuery(); } @Override public @Nullable Boolean getDefaultAutoCommit() { return getDataSource().isDefaultAutoCommit(); } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\TomcatDataSourcePoolMetadata.java
1
请完成以下Java代码
void printOddNum(int num) { try { semOdd.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println(Thread.currentThread().getName() + ":"+ num); semEven.release(); } } class Even implements Runnable { private final SharedPrinter sp; private final int max; Even(SharedPrinter sp, int max) { this.sp = sp; this.max = max; } @Override public void run() { for (int i = 2; i <= max; i = i + 2) { sp.printEvenNum(i); } } }
class Odd implements Runnable { private SharedPrinter sp; private int max; Odd(SharedPrinter sp, int max) { this.sp = sp; this.max = max; } @Override public void run() { for (int i = 1; i <= max; i = i + 2) { sp.printOddNum(i); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\evenandodd\PrintEvenOddSemaphore.java
1
请完成以下Java代码
private List<Connector> getConnectors() { List<Connector> connectors = new ArrayList<>(); for (Service service : this.tomcat.getServer().findServices()) { Collections.addAll(connectors, service.findConnectors()); } return connectors; } private void close(Connector connector) { connector.pause(); connector.getProtocolHandler().closeServerSocketGraceful(); } private void awaitInactiveOrAborted() { try { for (Container host : this.tomcat.getEngine().findChildren()) { for (Container context : host.findChildren()) { while (!this.aborted && isActive(context)) { Thread.sleep(50); } } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } }
private boolean isActive(Container context) { try { if (((StandardContext) context).getInProgressAsyncCount() > 0) { return true; } for (Container wrapper : context.findChildren()) { if (((StandardWrapper) wrapper).getCountAllocated() > 0) { return true; } } return false; } catch (Exception ex) { throw new RuntimeException(ex); } } void abort() { this.aborted = true; } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\GracefulShutdown.java
1
请完成以下Java代码
private RelatedProcessDescriptor createIssueTopLevelHusDescriptor() { return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClassIfUnique(WEBUI_PP_Order_HUEditor_IssueTopLevelHUs.class)) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } private RelatedProcessDescriptor createSelectHuAsSourceHuDescriptor() { return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClassIfUnique(WEBUI_PP_Order_HUEditor_Create_M_Source_HUs.class)) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } private RelatedProcessDescriptor createIssueTUsDescriptor() { return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClassIfUnique(WEBUI_PP_Order_HUEditor_IssueTUs.class)) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } @Override protected PPOrderLinesView getView() { return PPOrderLinesView.cast(super.getView()); } @Override protected PPOrderLineRow getSingleSelectedRow() { return PPOrderLineRow.cast(super.getSingleSelectedRow()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_Launcher.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() {
return author; } public void setAuthor(String author) { this.author = author; } public boolean isAlreadySaved() { return alreadySaved; } public void setAlreadySaved(boolean alreadySaved) { this.alreadySaved = alreadySaved; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\returnedvalueofsave\entity\BaeldungArticle.java
1
请完成以下Java代码
public List<AppDeploymentResponse> createAppDeploymentResponseList(List<AppDeployment> deployments) { AppRestUrlBuilder urlBuilder = createUrlBuilder(); List<AppDeploymentResponse> responseList = new ArrayList<>(deployments.size()); for (AppDeployment deployment : deployments) { responseList.add(createAppDeploymentResponse(deployment, urlBuilder)); } return responseList; } public AppDeploymentResponse createAppDeploymentResponse(AppDeployment deployment) { return createAppDeploymentResponse(deployment, createUrlBuilder()); } public AppDeploymentResponse createAppDeploymentResponse(AppDeployment deployment, AppRestUrlBuilder urlBuilder) { return new AppDeploymentResponse(deployment, urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT, deployment.getId())); } public List<AppDeploymentResourceResponse> createDeploymentResourceResponseList(String deploymentId, List<String> resourceList, ContentTypeResolver contentTypeResolver) { AppRestUrlBuilder urlBuilder = createUrlBuilder(); // Add additional metadata to the artifact-strings before returning List<AppDeploymentResourceResponse> responseList = new ArrayList<>(resourceList.size()); for (String resourceId : resourceList) { String contentType = contentTypeResolver.resolveContentType(resourceId); responseList.add(createDeploymentResourceResponse(deploymentId, resourceId, contentType, urlBuilder)); } return responseList; } public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType) { return createDeploymentResourceResponse(deploymentId, resourceId, contentType, createUrlBuilder()); } public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType, AppRestUrlBuilder urlBuilder) { // Create URL's
String resourceUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE, deploymentId, resourceId); String resourceContentUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE_CONTENT, deploymentId, resourceId); // Determine type String type = "resource"; if (resourceId.endsWith(".app")) { type = "appDefinition"; } return new AppDeploymentResourceResponse(resourceId, resourceUrl, resourceContentUrl, contentType, type); } protected AppRestUrlBuilder createUrlBuilder() { return AppRestUrlBuilder.fromCurrentRequest(); } }
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\AppRestResponseFactory.java
1
请完成以下Java代码
public Builder reuseRefreshTokens(boolean reuseRefreshTokens) { return setting(ConfigurationSettingNames.Token.REUSE_REFRESH_TOKENS, reuseRefreshTokens); } /** * Set the time-to-live for a refresh token. Must be greater than * {@code Duration.ZERO}. * @param refreshTokenTimeToLive the time-to-live for a refresh token * @return the {@link Builder} for further configuration */ public Builder refreshTokenTimeToLive(Duration refreshTokenTimeToLive) { Assert.notNull(refreshTokenTimeToLive, "refreshTokenTimeToLive cannot be null"); Assert.isTrue(refreshTokenTimeToLive.getSeconds() > 0, "refreshTokenTimeToLive must be greater than Duration.ZERO"); return setting(ConfigurationSettingNames.Token.REFRESH_TOKEN_TIME_TO_LIVE, refreshTokenTimeToLive); } /** * Sets the {@link SignatureAlgorithm JWS} algorithm for signing the * {@link OidcIdToken ID Token}. * @param idTokenSignatureAlgorithm the {@link SignatureAlgorithm JWS} algorithm * for signing the {@link OidcIdToken ID Token} * @return the {@link Builder} for further configuration */ public Builder idTokenSignatureAlgorithm(SignatureAlgorithm idTokenSignatureAlgorithm) { Assert.notNull(idTokenSignatureAlgorithm, "idTokenSignatureAlgorithm cannot be null"); return setting(ConfigurationSettingNames.Token.ID_TOKEN_SIGNATURE_ALGORITHM, idTokenSignatureAlgorithm); }
/** * Set to {@code true} if access tokens must be bound to the client * {@code X509Certificate} received during client authentication when using the * {@code tls_client_auth} or {@code self_signed_tls_client_auth} method. * @param x509CertificateBoundAccessTokens {@code true} if access tokens must be * bound to the client {@code X509Certificate}, {@code false} otherwise * @return the {@link Builder} for further configuration */ public Builder x509CertificateBoundAccessTokens(boolean x509CertificateBoundAccessTokens) { return setting(ConfigurationSettingNames.Token.X509_CERTIFICATE_BOUND_ACCESS_TOKENS, x509CertificateBoundAccessTokens); } /** * Builds the {@link TokenSettings}. * @return the {@link TokenSettings} */ @Override public TokenSettings build() { return new TokenSettings(getSettings()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\TokenSettings.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isCompletable() { return completable; } public void setCompletable(boolean completable) { this.completable = completable; } public String getEntryCriterionId() { return entryCriterionId; } public void setEntryCriterionId(String entryCriterionId) { this.entryCriterionId = entryCriterionId; } public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getCompletedBy() { return completedBy; }
public void setCompletedBy(String completedBy) { this.completedBy = completedBy; } public String getExtraValue() { return extraValue; } public void setExtraValue(String extraValue) { this.extraValue = extraValue; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java
2
请完成以下Java代码
public void setEditable (boolean edit) { m_textArea.setEditable(edit); } /** * Is Text Editable * @return true if editable */ public boolean isEditable() { return m_textArea.isEditable(); } /** * Set Text Line Wrap * @param wrap */ public void setLineWrap (boolean wrap) { m_textArea.setLineWrap (wrap); } /** * Set Text Wrap Style Word * @param word */ public void setWrapStyleWord (boolean word) { m_textArea.setWrapStyleWord (word); } /** * Set Opaque * @param isOpaque */ @Override public void setOpaque (boolean isOpaque) { // JScrollPane & Viewport is always not Opaque if (m_textArea == null) // during init of JScrollPane super.setOpaque(isOpaque); else m_textArea.setOpaque(isOpaque); } // setOpaque /** * Set Text Margin * @param m insets */ public void setMargin (Insets m) { if (m_textArea != null) m_textArea.setMargin(m); } // setMargin /** * AddFocusListener * @param l */ @Override public void addFocusListener (FocusListener l) { if (m_textArea == null) // during init super.addFocusListener(l); else m_textArea.addFocusListener(l); } /** * Add Text Mouse Listener * @param l */ @Override public void addMouseListener (MouseListener l) { m_textArea.addMouseListener(l); } /** * Add Text Key Listener
* @param l */ @Override public void addKeyListener (KeyListener l) { m_textArea.addKeyListener(l); } /** * Add Text Input Method Listener * @param l */ @Override public void addInputMethodListener (InputMethodListener l) { m_textArea.addInputMethodListener(l); } /** * Get text Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textArea.getInputMethodRequests(); } /** * Set Text Input Verifier * @param l */ @Override public void setInputVerifier (InputVerifier l) { m_textArea.setInputVerifier(l); } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } } // CTextArea
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java
1
请完成以下Java代码
public String getUsername() { return username; } /** * @param username */ public void setUsername(String username) { this.username = username == null ? null : username.trim(); } /** * @return PASSWD */ public String getPasswd() { return passwd; } /** * @param passwd */ public void setPasswd(String passwd) { this.passwd = passwd == null ? null : passwd.trim(); } /** * @return CREATE_TIME */ public Date getCreateTime() { return createTime; }
/** * @param createTime */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @return STATUS */ public String getStatus() { return status; } /** * @param status */ public void setStatus(String status) { this.status = status == null ? null : status.trim(); } }
repos\SpringAll-master\27.Spring-Boot-Mapper-PageHelper\src\main\java\com\springboot\bean\User.java
1
请完成以下Java代码
public boolean handlesThrowable() { for (PatternFormatter formatter : this.formatters) { if (formatter.handlesThrowable()) { return true; } } return super.handlesThrowable(); } @Override public void format(LogEvent event, StringBuilder toAppendTo) { StringBuilder buf = new StringBuilder(); for (PatternFormatter formatter : this.formatters) { formatter.format(event, buf); } if (!buf.isEmpty()) { AnsiElement element = this.styling; if (element == null) { // Assume highlighting element = LEVELS.get(event.getLevel().intLevel()); element = (element != null) ? element : AnsiColor.GREEN; } appendAnsiString(toAppendTo, buf.toString(), element); } } protected void appendAnsiString(StringBuilder toAppendTo, String in, AnsiElement element) { toAppendTo.append(AnsiOutput.toString(element, in));
} /** * Creates a new instance of the class. Required by Log4J2. * @param config the configuration * @param options the options * @return a new instance, or {@code null} if the options are invalid */ public static @Nullable ColorConverter newInstance(@Nullable Configuration config, @Nullable String[] options) { if (options.length < 1) { LOGGER.error("Incorrect number of options on style. Expected at least 1, received {}", options.length); return null; } if (options[0] == null) { LOGGER.error("No pattern supplied on style"); return null; } PatternParser parser = PatternLayout.createPatternParser(config); List<PatternFormatter> formatters = parser.parse(options[0]); AnsiElement element = (options.length != 1) ? ELEMENTS.get(options[1]) : null; return new ColorConverter(formatters, element); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\ColorConverter.java
1
请完成以下Java代码
protected static RequestMatcher transformPathMatcher(PathMatcherConfig pathMatcherConfig, String applicationPath) { RequestFilter requestMatcher = new RequestFilter( pathMatcherConfig.getPath(), applicationPath, pathMatcherConfig.getParsedMethods()); RequestAuthorizer requestAuthorizer = RequestAuthorizer.AUTHORIZE_ANNONYMOUS; if (pathMatcherConfig.getAuthorizer() != null) { String authorizeCls = pathMatcherConfig.getAuthorizer(); requestAuthorizer = (RequestAuthorizer) ReflectUtil.instantiate(authorizeCls); } return new RequestMatcher(requestMatcher, requestAuthorizer); } /** * Iterate over a number of filter rules and match them against * the given request. * * @param requestMethod * @param requestUri * @param filterRules * * @return the checked request with authorization information attached */
public static Authorization authorize(String requestMethod, String requestUri, List<SecurityFilterRule> filterRules) { Authorization authorization; for (SecurityFilterRule filterRule : filterRules) { authorization = filterRule.authorize(requestMethod, requestUri); if (authorization != null) { return authorization; } } // grant if no filter disallows it return Authorization.granted(Authentication.ANONYMOUS); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\util\FilterRules.java
1
请完成以下Java代码
private void refreshCachedProperties() { PropertySources propertySources = environment.getPropertySources(); propertySources.forEach(this::refreshPropertySource); } @SuppressWarnings("rawtypes") private void refreshPropertySource(PropertySource<?> propertySource) { if (propertySource instanceof CompositePropertySource) { CompositePropertySource cps = (CompositePropertySource) propertySource; cps.getPropertySources().forEach(this::refreshPropertySource); } else if (propertySource instanceof EncryptablePropertySource) { EncryptablePropertySource eps = (EncryptablePropertySource) propertySource; eps.refresh(); } } private Class<?> getClassSafe(String className) { try {
return ClassUtils.forName(className, null); } catch (ClassNotFoundException e) { return null; } } /** {@inheritDoc} */ @Override public void afterPropertiesSet() throws Exception { Stream .concat(EVENT_CLASS_NAMES.stream(), this.config.getRefreshedEventClasses().stream()) .map(this::getClassSafe).filter(Objects::nonNull) .collect(Collectors.toCollection(() -> this.eventClasses)); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\RefreshScopeRefreshedEventListener.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Book{" + "id=" + id + ", name=" + name + ", title=" + title + ", isbn=" + isbn + ", price=" + price + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDeadlockExample\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public class MybatisEventLogEntryDataManager extends AbstractDataManager<EventLogEntryEntity> implements EventLogEntryDataManager { public MybatisEventLogEntryDataManager(ProcessEngineConfigurationImpl processEngineConfiguration) { super(processEngineConfiguration); } @Override public Class<? extends EventLogEntryEntity> getManagedEntityClass() { return EventLogEntryEntityImpl.class; } @Override public EventLogEntryEntity create() { return new EventLogEntryEntityImpl(); } @Override @SuppressWarnings("unchecked") public List<EventLogEntry> findAllEventLogEntries() { return getDbSqlSession().selectList("selectAllEventLogEntries"); } @Override @SuppressWarnings("unchecked")
public List<EventLogEntry> findEventLogEntries(long startLogNr, long pageSize) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("startLogNr", startLogNr); if (pageSize > 0) { params.put("endLogNr", startLogNr + pageSize + 1); } return getDbSqlSession().selectList("selectEventLogEntries", params); } @Override @SuppressWarnings("unchecked") public List<EventLogEntry> findEventLogEntriesByProcessInstanceId(String processInstanceId) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("processInstanceId", processInstanceId); return getDbSqlSession().selectList("selectEventLogEntriesByProcessInstanceId", params); } @Override public void deleteEventLogEntry(long logNr) { getDbSqlSession().getSqlSession().delete("deleteEventLogEntry", logNr); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisEventLogEntryDataManager.java
1
请完成以下Spring Boot application配置
server.port=80 # \u6570\u636E\u6E90\u914D\u7F6E #https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter spring.datasource.druid.url=jdbc:mysql://localhost:3306/ssb_test spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.username=root spring.datasource.druid.password=root # \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927 spring.datasource.druid.initial-size=5 spring.datasource.druid.min-idle=5 spring.datasource.druid.max-active=20 # \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4 spring.datasource.druid.max-wait=60000 # \u914D\u7F6E\u95F4\u9694\u591A\u4E45\u624D\u8FDB\u884C\u4E00\u6B21\u68C0\u6D4B\uFF0C\u68C0\u6D4B\u9700\u8981\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.druid.time-between-eviction-runs-millis=60000 # \u914D\u7F6E\u4E00\u4E2A\u8FDE\u63A5\u5728\u6C60\u4E2D\u6700\u5C0F\u751F\u5B58\u7684\u65F6\u95F4\uFF0C\u5355\u4F4D\u662F\u6BEB\u79D2 spring.datasource.druid.min-evictable-idle-time-millis=300000 #\u68C0\u6D4B\u8FDE\u63A5\u662F\u5426\u6709\u6548\u7684sql spring.datasource.druid.validation-query=SELECT 'x' spring.datasource.druid.validation-query-timeout=60000 spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false # PSCache Mysql\u4E0B\u5EFA\u8BAE\u5173\u95ED spring.datasource.druid.pool-prepared-statements=false spring.datasource.druid.max-pool-prepared-statement-per-connection-size=-1 #spring.datasource.druid.max-open-prepared-statements= #\u7B49\u4EF7\u4E8E\u4E0A\u9762\u7684max-pool-prepared-statement-per-connection-size # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters\uFF0C\u53BB\u6389\u540E\u76D1\u63A7\u754C\u9762sql\u65E0\u6CD5\u7EDF\u8BA1\uFF0C'wall'\u7528\u4E8E\u9632\u706B\u5899 spring.datasource.druid.filters=stat,wall,log4j # WebStatFilter\u914D\u7F6E\uFF0C\u8BF4\u660E\u8BF7\u53C2\u8003Druid Wiki\uFF0C\u914D\u7F6E_\u914D\u7F6EWebStatFilter #\u542F\u52A8\u9879\u76EE\u540E\u8BBF\u95EE http://127.0.0.1:8080/druid #\u662F\u5426\u542F\u7528StatFilter\u9ED8\u8BA4\u503Ctrue spring.datasource.druid.web-stat-filter.enabled=true spring.datasource.druid.web-stat-filter.url-pattern=/* spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/* #\u7F3A\u7701sessionStatMaxCount\u662F1000\u4E2A spring.datasource.druid.web-stat-filter.session-stat-max-count=1000 #\u5173\u95EDsession\u7EDF\u8BA1\u529F\u80FD spring.datasource.druid.web-stat-filter.session-stat-enable=false #\u914D\u7F6EprincipalSessionName\uFF0C\u4F7F\u5F97druid\u80FD\u591F\u77E5\u9053\u5F53\u524D\u7684session\u7684\u7528\u6237\u662F\u8C01 #\u5982\u679C\u4F60session\u4E2D\u4FDD\u5B58\u7684\u662F\u975Estring\u7C7B\u578B\u7684\u5BF9\u8C61\uFF0C\u9700\u8981\u91CD\u8F7DtoString\u65B9\u6CD5 spring.datasource.druid.web-stat-filter.principalSessionName=xxx.user #\u5982\u679Cuser\u4FE1\u606F\u4FDD\u5B58\u5728cookie\u4E2D\uFF0C\u4F60\u53EF\u4EE5\u914D\u7F6EprincipalCookieName\uFF0C\u4F7F\u5F97druid\u77E5\u9053\u5F53\u524D\u7684user\u662F\u8C01 spring.datasource.druid.web-stat-filter.principalCookieName=xxx.user #druid 0.2.7\u7248\u672C\u5F00\u59CB\u652F\u6301profile\uFF0C\u914D\u7F6EprofileEnable\u80FD\u591F\u76D1\u63A7\u5355\u4E2Aurl\u8C03\u7528\u7684sql\u5217\u8868\u3002 spring.datasource.druid.web-stat-filter.profile-enable=false # StatViewServlet\u914D\u7F6E\uFF0C\u8BF4\u660E\u8BF7\u53C2\u8003Dru
id Wiki\uFF0C\u914D\u7F6E_StatViewServlet\u914D\u7F6E #\u662F\u5426\u542F\u7528StatViewServlet\u9ED8\u8BA4\u503Ctrue spring.datasource.druid.stat-view-servlet.enabled=true spring.datasource.druid.stat-view-servlet.urlPattern=/druid/* #\u7981\u7528HTML\u9875\u9762\u4E0A\u7684\u201CReset All\u201D\u529F\u80FD spring.datasource.druid.stat-view-servlet.resetEnable=false #\u7528\u6237\u540D spring.datasource.druid.stat-view-servlet.loginUsername=admin #\u5BC6\u7801 spring.datasource.druid.stat-view-servlet.loginPassword=admin #IP\u767D\u540D\u5355(\u6CA1\u6709\u914D\u7F6E\u6216\u8005\u4E3A\u7A7A\uFF0C\u5219\u5141\u8BB8\u6240\u6709\u8BBF\u95EE) spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,192.168.163.1 #IP\u9ED1\u540D\u5355 (\u5B58\u5728\u5171\u540C\u65F6\uFF0Cdeny\u4F18\u5148\u4E8Eallow) spring.datasource.druid.stat-view-servlet.deny=192.168.1.73 #mybatis #entity\u626B\u63CF\u7684\u5305\u540D mybatis.type-aliases-package=com.xiaolyuh.domain.model #Mapper.xml\u6240\u5728\u7684\u4F4D\u7F6E mybatis.mapper-locations=classpath*:/mybaits/*Mapper.xml #\u5F00\u542FMyBatis\u7684\u4E8C\u7EA7\u7F13\u5B58 mybatis.configuration.cache-enabled=true #pagehelper pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql #\u65E5\u5FD7\u914D\u7F6E logging.level.com.xiaolyuh=debug logging.level.org.springframework.web=debug logging.level.org.springframework.transaction=debug logging.level.org.mybatis=debug debug=false
repos\spring-boot-student-master\spring-boot-student-drools\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public static List toList() { TradeStatusEnum[] ary = TradeStatusEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); map.put("name", ary[i].name()); list.add(map); } return list; } public static TradeStatusEnum getEnum(String name) { TradeStatusEnum[] arry = TradeStatusEnum.values(); for (int i = 0; i < arry.length; i++) { if (arry[i].name().equalsIgnoreCase(name)) { return arry[i]; } } return null; } /**
* 取枚举的json字符串 * * @return */ public static String getJsonStr() { TradeStatusEnum[] enums = TradeStatusEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (TradeStatusEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\TradeStatusEnum.java
2
请完成以下Java代码
public void save(@NonNull final BankStatementImportFile bankStatementImportFile) { final I_C_BankStatement_Import_File bankStatementImportFileRecord = getRecordById(bankStatementImportFile.getBankStatementImportFileId()); bankStatementImportFileRecord.setProcessed(bankStatementImportFile.isProcessed()); bankStatementImportFileRecord.setFileName(bankStatementImportFile.getFilename()); bankStatementImportFileRecord.setImported(TimeUtil.asTimestamp(bankStatementImportFile.getImportedTimestamp())); bankStatementImportFileRecord.setIsMatchAmounts(bankStatementImportFile.isMatchAmounts()); saveRecord(bankStatementImportFileRecord); } @NonNull private I_C_BankStatement_Import_File getRecordById(@NonNull final BankStatementImportFileId bankStatementImportFileId) { final I_C_BankStatement_Import_File record = InterfaceWrapperHelper.load(bankStatementImportFileId, I_C_BankStatement_Import_File.class); if (record == null) { throw new AdempiereException("No I_C_BankStatement_Import_File found for id!") .appendParametersToMessage() .setParameter("C_BankStatement_Import_File_ID", bankStatementImportFileId); }
return record; } @NonNull private static BankStatementImportFile ofRecord(@NonNull final I_C_BankStatement_Import_File record) { return BankStatementImportFile.builder() .bankStatementImportFileId(BankStatementImportFileId.ofRepoId(record.getC_BankStatement_Import_File_ID())) .filename(record.getFileName()) .importedTimestamp(TimeUtil.asInstant(record.getImported())) .isMatchAmounts(record.isMatchAmounts()) .processed(record.isProcessed()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\BankStatementImportFileRepository.java
1
请完成以下Java代码
public long getSecondaryCacheExpirationSecondTime(String name) { if (StringUtils.isEmpty(name)) { return 0; } SecondaryCacheSetting secondaryCacheSetting = null; if (!CollectionUtils.isEmpty(secondaryCacheSettings)) { secondaryCacheSetting = secondaryCacheSettings.get(name); } Long expiration = secondaryCacheSetting != null ? secondaryCacheSetting.getExpirationSecondTime() : defaultExpiration; return expiration < 0 ? 0 : expiration; } /** * 获取自动刷新时间 * * @return */ private long getSecondaryCachePreloadSecondTime(String name) { // 自动刷新时间,默认是0 SecondaryCacheSetting secondaryCacheSetting = null; if (!CollectionUtils.isEmpty(secondaryCacheSettings)) { secondaryCacheSetting = secondaryCacheSettings.get(name); } Long preloadSecondTime = secondaryCacheSetting != null ? secondaryCacheSetting.getPreloadSecondTime() : 0; return preloadSecondTime < 0 ? 0 : preloadSecondTime; } /** * 获取是否使用二级缓存,默认是true */ public boolean getUsedFirstCache(String name) { SecondaryCacheSetting secondaryCacheSetting = null; if (!CollectionUtils.isEmpty(secondaryCacheSettings)) { secondaryCacheSetting = secondaryCacheSettings.get(name); } return secondaryCacheSetting != null ? secondaryCacheSetting.getUsedFirstCache() : true; } /** * 获取是否强制刷新(走数据库),默认是false */ public boolean getForceRefresh(String name) { SecondaryCacheSetting secondaryCacheSetting = null; if (!CollectionUtils.isEmpty(secondaryCacheSettings)) { secondaryCacheSetting = secondaryCacheSettings.get(name);
} return secondaryCacheSetting != null ? secondaryCacheSetting.getForceRefresh() : false; } public void setCaffeineSpec(CaffeineSpec caffeineSpec) { Caffeine<Object, Object> cacheBuilder = Caffeine.from(caffeineSpec); if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) { this.cacheBuilder = cacheBuilder; refreshKnownCaches(); } } private Caffeine<Object, Object> getCaffeine(String name) { if (!CollectionUtils.isEmpty(firstCacheSettings)) { FirstCacheSetting firstCacheSetting = firstCacheSettings.get(name); if (firstCacheSetting != null && StringUtils.isNotBlank(firstCacheSetting.getCacheSpecification())) { // 根据缓存名称获取一级缓存配置 return Caffeine.from(CaffeineSpec.parse(firstCacheSetting.getCacheSpecification())); } } return this.cacheBuilder; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\layering\LayeringCacheManager.java
1
请完成以下Java代码
public abstract class AbstractResourceWriter implements ResourceWriter { /** * @inheritDoc */ @Override public void write(@NonNull Resource resource, byte[] data) { ResourceUtils.asWritableResource(resource) .filter(this::isAbleToHandle) .map(this::preProcess) .map(it -> { try (OutputStream out = it.getOutputStream()) { doWrite(out, data); return true; } catch (IOException cause) { throw new ResourceWriteException(String.format("Failed to write to Resource [%s]", it.getDescription()), cause); } }) .orElseThrow(() -> new UnhandledResourceException(String.format("Unable to handle Resource [%s]", ResourceUtils.nullSafeGetDescription(resource)))); } /** * Determines whether this writer is able to handle and write to the target {@link Resource}. * * The default implementation determines that the {@link Resource} can be handled if the {@link Resource} handle * is not {@literal null}. * * @param resource {@link Resource} to evaluate. * @return a boolean value indicating whether this writer is able to handle and write to the target {@link Resource}. * @see org.springframework.core.io.Resource */ @SuppressWarnings("unused") protected boolean isAbleToHandle(@Nullable Resource resource) { return resource != null; } /** * Writes the given data to the target {@link Resource} (intentionally) by using the {@link OutputStream} * returned by {@link WritableResource#getOutputStream()}. *
* However, other algorithm/strategy implementations are free to write to the {@link Resource} as is appropriate * for the given context (e.g. cloud environment). In those cases, implementors should override * the {@link #write(Resource, byte[])} method. * * @param resourceOutputStream {@link OutputStream} returned from {@link WritableResource#getOutputStream()} * used to write the given data to the locations identified by the target {@link Resource}. * @param data array of bytes containing the data to write. * @throws IOException if an I/O error occurs while writing to the target {@link Resource}. * @see java.io.OutputStream */ protected abstract void doWrite(OutputStream resourceOutputStream, byte[] data) throws IOException; /** * Pre-processes the target {@link WritableResource} before writing to the {@link WritableResource}. * * @param resource {@link WritableResource} to pre-process; never {@literal null}. * @return the given, target {@link WritableResource}. * @see org.springframework.core.io.WritableResource */ protected @NonNull WritableResource preProcess(@NonNull WritableResource resource) { return resource; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\io\AbstractResourceWriter.java
1
请完成以下Java代码
public boolean accept(final I_C_Queue_WorkPackage workpackage) { if (packageQuery.getProcessed() != null && packageQuery.getProcessed() != workpackage.isProcessed()) { return false; } if (packageQuery.getReadyForProcessing() != null && packageQuery.getReadyForProcessing() != workpackage.isReadyForProcessing()) { return false; } if (packageQuery.getError() != null && packageQuery.getError() != workpackage.isError()) { return false; } if (!workpackage.isActive()) { return false; } // Only packages that have not been skipped, // or where 'retryTimeoutMillis' has already passed since they were skipped. final Timestamp nowMinusTimeOut = new Timestamp(SystemTime.millis() - packageQuery.getSkippedTimeoutMillis()); final Timestamp skippedAt = workpackage.getSkippedAt(); if (skippedAt != null && skippedAt.compareTo(nowMinusTimeOut) > 0) { return false; } // Only work packages for given process final Set<QueuePackageProcessorId> packageProcessorIds = packageQuery.getPackageProcessorIds(); if (packageProcessorIds != null) {
if (packageProcessorIds.isEmpty()) { slogger.warn("There were no package processor Ids set in the package query. This could be a posible development error" +"\n Package query: "+packageQuery); } final QueuePackageProcessorId packageProcessorId = QueuePackageProcessorId.ofRepoId(workpackage.getC_Queue_PackageProcessor_ID()); if (!packageProcessorIds.contains(packageProcessorId)) { return false; } } final String priorityFrom = packageQuery.getPriorityFrom(); if (priorityFrom != null && priorityFrom.compareTo(workpackage.getPriority()) > 0) { return false; } return true; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\PlainQueueDAO.java
1
请完成以下Java代码
public VariableProvider variableProvider() { return new CompositeVariableProvider(toScalaList(inputVariableContext, contextVariableWrapper)); } }; Either either = feelEngine.evalUnaryTests(expression, context); if (either instanceof Right) { Right right = (Right) either; Object value = right.value(); return BoxesRunTime.unboxToBoolean(value); } else { Left left = (Left) either; Failure failure = (Failure) left.value(); String message = failure.message(); throw LOGGER.evaluationException(message); } } protected List<CustomValueMapper> getValueMappers() { SpinValueMapperFactory spinValueMapperFactory = new SpinValueMapperFactory(); CustomValueMapper javaValueMapper = new JavaValueMapper(); CustomValueMapper spinValueMapper = spinValueMapperFactory.createInstance(); if (spinValueMapper != null) { return toScalaList(javaValueMapper, spinValueMapper); } else { return toScalaList(javaValueMapper); } }
@SafeVarargs protected final <T> List<T> toScalaList(T... elements) { java.util.List<T> listAsJava = Arrays.asList(elements); return toList(listAsJava); } protected <T> List<T> toList(java.util.List list) { return ListHasAsScala(list).asScala().toList(); } protected org.camunda.feel.FeelEngine buildFeelEngine(CustomFunctionTransformer transformer, CompositeValueMapper valueMapper) { return new Builder() .functionProvider(transformer) .valueMapper(valueMapper) .enableExternalFunctions(false) .build(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\ScalaFeelEngine.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricTaskInstancesForNonExistingProcessInstances() { getHistoricTaskInstanceEntityManager().deleteHistoricTaskInstancesForNonExistingProcessInstances(); } @Override public void deleteHistoricTaskInstancesForNonExistingCaseInstances() { getHistoricTaskInstanceEntityManager().deleteHistoricTaskInstancesForNonExistingCaseInstances(); } @Override public NativeHistoricTaskLogEntryQuery createNativeHistoricTaskLogEntryQuery(CommandExecutor commandExecutor) { return new NativeHistoricTaskLogEntryQueryImpl(commandExecutor, configuration); } protected HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() { return configuration.getHistoricTaskLogEntryEntityManager(); } protected void createHistoricIdentityLink(String taskId, String type, String userId, AbstractEngineConfiguration engineConfiguration) {
HistoricIdentityLinkService historicIdentityLinkService = getIdentityLinkServiceConfiguration(engineConfiguration).getHistoricIdentityLinkService(); HistoricIdentityLinkEntity historicIdentityLinkEntity = historicIdentityLinkService.createHistoricIdentityLink(); historicIdentityLinkEntity.setTaskId(taskId); historicIdentityLinkEntity.setType(type); historicIdentityLinkEntity.setUserId(userId); historicIdentityLinkEntity.setCreateTime(configuration.getClock().getCurrentTime()); historicIdentityLinkService.insertHistoricIdentityLink(historicIdentityLinkEntity, false); } public HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() { return configuration.getHistoricTaskInstanceEntityManager(); } protected IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration(AbstractEngineConfiguration engineConfiguration) { return (IdentityLinkServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_IDENTITY_LINK_SERVICE_CONFIG); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskServiceImpl.java
2
请完成以下Java代码
public VariableType getVariableType() { return variableType; } public void setVariableType(VariableType variableType) { this.variableType = variableType; } @Override public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; }
@Override public String getSubScopeId() { return ScopeTypes.BPMN.equals(scopeType) ? executionId : null; } @Override public String getScopeDefinitionId() { return ScopeTypes.BPMN.equals(scopeType) ? processDefinitionId : null; } @Override public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiVariableEventImpl.java
1
请完成以下Java代码
public String getTrckNb() { return trckNb; } /** * Sets the value of the trckNb property. * * @param value * allowed object is * {@link String } * */ public void setTrckNb(String value) { this.trckNb = value; } /** * Gets the value of the trckVal property. * * @return * possible object is * {@link String } * */ public String getTrckVal() { return trckVal;
} /** * Sets the value of the trckVal property. * * @param value * allowed object is * {@link String } * */ public void setTrckVal(String value) { this.trckVal = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TrackData1.java
1
请完成以下Java代码
public void setPricingSystem_Value (final @Nullable java.lang.String PricingSystem_Value) { set_Value (COLUMNNAME_PricingSystem_Value, PricingSystem_Value); } @Override public java.lang.String getPricingSystem_Value() { return get_ValueAsString(COLUMNNAME_PricingSystem_Value); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override
public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java
1
请完成以下Java代码
public void createOperationLogEntry(CommandContext commandContext, MessageCorrelationResultImpl result, List<PropertyChange> propChanges, boolean isSummary) { String processInstanceId = null; String processDefinitionId = null; if(result.getProcessInstance() != null) { if(!isSummary) { processInstanceId = result.getProcessInstance().getId(); } processDefinitionId = result.getProcessInstance().getProcessDefinitionId(); } commandContext.getOperationLogManager() .logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_CORRELATE_MESSAGE, processInstanceId, processDefinitionId, null, propChanges); } @Override public Map<MessageCorrelationResultImpl, List<PropertyChange>> getPropChangesForOperation(List<MessageCorrelationResultImpl> results) { Map<MessageCorrelationResultImpl, List<PropertyChange>> resultPropChanges = new HashMap<>(); for (MessageCorrelationResultImpl messageCorrelationResultImpl : results) { List<PropertyChange> propChanges = getGenericPropChangesForOperation(); ProcessInstance processInstance = messageCorrelationResultImpl.getProcessInstance(); if(processInstance != null) { propChanges.add(new PropertyChange("processInstanceId", null, processInstance.getId())); } resultPropChanges.put(messageCorrelationResultImpl, propChanges); } return resultPropChanges; }
@Override public List<PropertyChange> getSummarizingPropChangesForOperation(List<MessageCorrelationResultImpl> results) { List<PropertyChange> propChanges = getGenericPropChangesForOperation(); propChanges.add(new PropertyChange("nrOfInstances", null, results.size())); return propChanges; } protected List<PropertyChange> getGenericPropChangesForOperation() { ArrayList<PropertyChange> propChanges = new ArrayList<>(); propChanges.add(new PropertyChange("messageName", null, messageName)); if(variablesCount > 0) { propChanges.add(new PropertyChange("nrOfVariables", null, variablesCount)); } return propChanges; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\CorrelateAllMessageCmd.java
1
请完成以下Java代码
public JsonOLCandCreateBulkRequest withOrgSyncAdvise(@Nullable final SyncAdvise syncAdvise) { return syncAdvise != null ? map(request -> request.withOrgSyncAdvise(syncAdvise)) : this; } public JsonOLCandCreateBulkRequest withBPartnersSyncAdvise(@Nullable final SyncAdvise syncAdvise) { return syncAdvise != null ? map(request -> request.withBPartnersSyncAdvise(syncAdvise)) : this; } public JsonOLCandCreateBulkRequest withProductsSyncAdvise(@Nullable final SyncAdvise syncAdvise) { return syncAdvise != null
? map(request -> request.withProductsSyncAdvise(syncAdvise)) : this; } private JsonOLCandCreateBulkRequest map(@NonNull final UnaryOperator<JsonOLCandCreateRequest> mapper) { if (requests.isEmpty()) { return this; } final ImmutableList<JsonOLCandCreateRequest> newRequests = this.requests.stream() .map(mapper) .collect(ImmutableList.toImmutableList()); return new JsonOLCandCreateBulkRequest(newRequests); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v1\request\JsonOLCandCreateBulkRequest.java
1
请完成以下Java代码
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; } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Window Internal Name. @param WindowInternalName Window Internal Name */ @Override public void setWindowInternalName (java.lang.String WindowInternalName) { set_Value (COLUMNNAME_WindowInternalName, WindowInternalName); } /** Get Window Internal Name. @return Window Internal Name */ @Override public java.lang.String getWindowInternalName () { return (java.lang.String)get_Value(COLUMNNAME_WindowInternalName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_I_DataEntry_Record.java
1
请完成以下Java代码
public class PartyIdentificationSEPA3 { @XmlElement(name = "Id", required = true) protected PartySEPA2 id; /** * Gets the value of the id property. * * @return * possible object is * {@link PartySEPA2 } * */ public PartySEPA2 getId() { return id;
} /** * Sets the value of the id property. * * @param value * allowed object is * {@link PartySEPA2 } * */ public void setId(PartySEPA2 value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PartyIdentificationSEPA3.java
1
请完成以下Java代码
public String getGender() { return gender; } /** * Sets the value of the gender property. * * @param value * allowed object is * {@link String } * */ public void setGender(String value) { this.gender = value; } /** * Gets the value of the created property. * * @return * possible object is * {@link String }
* */ public Calendar getCreated() { return created; } /** * Sets the value of the created property. * * @param value * allowed object is * {@link String } * */ public void setCreated(Calendar value) { this.created = value; } }
repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\gen\UserResponse.java
1
请完成以下Java代码
public void setIsWriteOffApplied (boolean IsWriteOffApplied) { set_Value (COLUMNNAME_IsWriteOffApplied, Boolean.valueOf(IsWriteOffApplied)); } /** Get Massenaustritt Applied. @return Massenaustritt Applied */ @Override public boolean isWriteOffApplied () { Object oo = get_Value(COLUMNNAME_IsWriteOffApplied); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line_Source.java
1
请完成以下Java代码
public static ByteArrayOtherStream createByteArrayOtherStream(String path) { try { InputStream is = HanLP.Config.IOAdapter == null ? new FileInputStream(path) : HanLP.Config.IOAdapter.open(path); return createByteArrayOtherStream(is); } catch (Exception e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); return null; } } public static ByteArrayOtherStream createByteArrayOtherStream(InputStream is) throws IOException { if (is == null) return null; int size = is.available(); size = Math.max(102400, size); // 有些网络InputStream实现会返回0,直到read的时候才知道到底是不是0 int bufferSize = Math.min(1048576, size); // 最终缓冲区在100KB到1MB之间 byte[] bytes = new byte[bufferSize]; if (IOUtil.readBytesFromOtherInputStream(is, bytes) == 0) { throw new IOException("读取了空文件,或参数InputStream已经到了文件尾部"); } return new ByteArrayOtherStream(bytes, bufferSize, is); } @Override protected void ensureAvailableBytes(int size) { if (offset + size > bufferSize) { try { int wantedBytes = offset + size - bufferSize; // 实际只需要这么多 wantedBytes = Math.max(wantedBytes, is.available()); // 如果非阻塞IO能读到更多,那越多越好 wantedBytes = Math.min(wantedBytes, offset); // 但不能超过脏区的大小 byte[] bytes = new byte[wantedBytes]; int readBytes = IOUtil.readBytesFromOtherInputStream(is, bytes); assert readBytes > 0 : "已到达文件尾部!"; System.arraycopy(this.bytes, offset, this.bytes, offset - wantedBytes, bufferSize - offset); System.arraycopy(bytes, 0, this.bytes, bufferSize - wantedBytes, wantedBytes); offset -= wantedBytes; } catch (IOException e)
{ throw new RuntimeException(e); } } } @Override public void close() { super.close(); if (is == null) { return; } try { is.close(); } catch (IOException e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayOtherStream.java
1
请完成以下Java代码
public class OpenIdConnectUserDetails implements UserDetails { private static final long serialVersionUID = 1L; private String userId; private String username; private OAuth2AccessToken token; public OpenIdConnectUserDetails(Map<String, String> userInfo, OAuth2AccessToken token) { this.userId = userInfo.get("sub"); this.username = userInfo.get("email"); this.token = token; } @Override public String getUsername() { return username; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public OAuth2AccessToken getToken() { return token; } public void setToken(OAuth2AccessToken token) { this.token = token; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() {
return null; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectUserDetails.java
1
请完成以下Java代码
public void setId(Integer id) { this.id = id; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Book book = (Book) o; return id.equals(book.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\tutorials-master\graphql-modules\graphql-spqr\src\main\java\com\baeldung\spqr\Book.java
1
请完成以下Java代码
public int getRole() { return role; } public void setRole(int role) { this.role = role; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } // plugin
public boolean validPermission(int jobGroup){ if (this.role == 1) { return true; } else { if (StringUtils.hasText(this.permission)) { for (String permissionItem : this.permission.split(",")) { if (String.valueOf(jobGroup).equals(permissionItem)) { return true; } } } return false; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobUser.java
1
请完成以下Java代码
public class CustomFunction { protected List<String> params; protected Function<List<Object>, Object> function; protected boolean hasVarargs; public CustomFunction() { params = Collections.emptyList(); } /** * Creates a fluent builder to configure a custom function * * @return builder to apply configurations on */ public static CustomFunctionBuilder create() { return new CustomFunctionBuilderImpl(); } public List<String> getParams() { return params; } public void setParams(List<String> params) { this.params = params; }
public Function<List<Object>, Object> getFunction() { return function; } public void setFunction(Function<List<Object>, Object> function) { this.function = function; } public boolean hasVarargs() { return hasVarargs; } public void setHasVarargs(boolean hasVarargs) { this.hasVarargs = hasVarargs; } }
repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\function\CustomFunction.java
1
请在Spring Boot框架中完成以下Java代码
public class WebMvcConfig implements WebMvcConfigurer { @Autowired private WebFlowConfig webFlowConfig; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public FlowHandlerMapping flowHandlerMapping() {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping(); handlerMapping.setOrder(-1); handlerMapping.setFlowRegistry(this.webFlowConfig.flowRegistry()); return handlerMapping; } @Bean public FlowHandlerAdapter flowHandlerAdapter() { FlowHandlerAdapter handlerAdapter = new FlowHandlerAdapter(); handlerAdapter.setFlowExecutor(this.webFlowConfig.flowExecutor()); handlerAdapter.setSaveOutputToFlashScopeOnRedirect(true); return handlerAdapter; } }
repos\tutorials-master\spring-web-modules\spring-mvc-webflow\src\main\java\com\baeldung\spring\WebMvcConfig.java
2
请完成以下Java代码
public class C_PurchaseCandiate_Create_PurchaseOrders extends JavaProcess implements IProcessPrecondition { @Override public ProcessPreconditionsResolution checkPreconditionsApplicable( @NonNull final IProcessPreconditionsContext context) { if (!I_C_PurchaseCandidate.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.reject(); } final boolean containsEligibleRecords = context .streamSelectedModels(I_C_PurchaseCandidate.class) .anyMatch(I_C_PurchaseCandidate::isPrepared); return ProcessPreconditionsResolution.acceptIf(containsEligibleRecords); } @Override protected String doIt() throws Exception { final IQueryBL queryBL = Services.get(IQueryBL.class); final ImmutableSet<PurchaseCandidateId> purchaseCandidateIds = queryBL
.createQueryBuilder(I_C_PurchaseCandidate.class) .filter(getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false))) .addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_IsPrepared, true) .create() .iterateAndStreamIds(PurchaseCandidateId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); createPurchaseOrders(purchaseCandidateIds); return MSG_OK; } protected void createPurchaseOrders(final ImmutableSet<PurchaseCandidateId> purchaseCandidateIds) { C_PurchaseCandidates_GeneratePurchaseOrders.enqueue(purchaseCandidateIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\process\C_PurchaseCandiate_Create_PurchaseOrders.java
1
请完成以下Java代码
private boolean shouldIgnore(MediaType httpRequestMediaType) { for (MediaType ignoredMediaType : this.ignoredMediaTypes) { if (httpRequestMediaType.includes(ignoredMediaType)) { return true; } } return false; } /** * If set to true, matches on exact {@link MediaType}, else uses * {@link MediaType#isCompatibleWith(MediaType)}. * @param useEquals specify if equals comparison should be used. */ public void setUseEquals(boolean useEquals) { this.useEquals = useEquals; } /** * Set the {@link MediaType} to ignore from the {@link ContentNegotiationStrategy}. * This is useful if for example, you want to match on * {@link MediaType#APPLICATION_JSON} but want to ignore {@link MediaType#ALL}. * @param ignoredMediaTypes the {@link MediaType}'s to ignore from the * {@link ContentNegotiationStrategy} */ public void setIgnoredMediaTypes(Set<MediaType> ignoredMediaTypes) { this.ignoredMediaTypes = ignoredMediaTypes; }
private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException { try { List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept(); MimeTypeUtils.sortBySpecificity(mediaTypes); return mediaTypes; } catch (InvalidMediaTypeException ex) { String value = exchange.getRequest().getHeaders().getFirst("Accept"); throw new NotAcceptableStatusException( "Could not parse 'Accept' header [" + value + "]: " + ex.getMessage()); } } @Override public String toString() { return "MediaTypeRequestMatcher [matchingMediaTypes=" + this.matchingMediaTypes + ", useEquals=" + this.useEquals + ", ignoredMediaTypes=" + this.ignoredMediaTypes + "]"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\util\matcher\MediaTypeServerWebExchangeMatcher.java
1
请完成以下Java代码
public Boolean isAttndntMsgCpbl() { return attndntMsgCpbl; } /** * Sets the value of the attndntMsgCpbl property. * * @param value * allowed object is * {@link Boolean } * */ public void setAttndntMsgCpbl(Boolean value) { this.attndntMsgCpbl = value; } /** * Gets the value of the attndntLang property. * * @return * possible object is * {@link String } * */ public String getAttndntLang() { return attndntLang; } /** * Sets the value of the attndntLang property. * * @param value * allowed object is * {@link String } * */ public void setAttndntLang(String value) { this.attndntLang = value; } /** * Gets the value of the cardDataNtryMd property. * * @return * possible object is * {@link CardDataReading1Code } * */ public CardDataReading1Code getCardDataNtryMd() { return cardDataNtryMd; } /** * Sets the value of the cardDataNtryMd property. * * @param value * allowed object is * {@link CardDataReading1Code } * */ public void setCardDataNtryMd(CardDataReading1Code value) { this.cardDataNtryMd = value; } /** * Gets the value of the fllbckInd property. * * @return * possible object is * {@link Boolean } *
*/ public Boolean isFllbckInd() { return fllbckInd; } /** * Sets the value of the fllbckInd property. * * @param value * allowed object is * {@link Boolean } * */ public void setFllbckInd(Boolean value) { this.fllbckInd = value; } /** * Gets the value of the authntcnMtd property. * * @return * possible object is * {@link CardholderAuthentication2 } * */ public CardholderAuthentication2 getAuthntcnMtd() { return authntcnMtd; } /** * Sets the value of the authntcnMtd property. * * @param value * allowed object is * {@link CardholderAuthentication2 } * */ public void setAuthntcnMtd(CardholderAuthentication2 value) { this.authntcnMtd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\PaymentContext3.java
1
请完成以下Java代码
public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port); if (ii == null) return 0; return ii.intValue(); }
/** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor.java
1
请完成以下Spring Boot application配置
# datasource config spring.datasource.url=jdbc:mysql://localhost:3306/springboot3_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false spring.datasource.driver-class-name=c
om.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-jdbc\src\main\resources\application.properties
2
请完成以下Java代码
public class MergingCosts { private static final List<Integer> arrayListOfNumbers = new ArrayList<>(); static { IntStream.rangeClosed(1, 1_000_000).forEach(i -> { arrayListOfNumbers.add(i); }); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public static void mergingCostsSumSequential() { arrayListOfNumbers.stream().reduce(0, Integer::sum); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public static void mergingCostsSumParallel() { arrayListOfNumbers.stream().parallel().reduce(0, Integer::sum); }
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public static void mergingCostsGroupingSequential() { arrayListOfNumbers.stream().collect(Collectors.toSet()); } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public static void mergingCostsGroupingParallel() { arrayListOfNumbers.stream().parallel().collect(Collectors.toSet()); } }
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\parallel\MergingCosts.java
1
请完成以下Java代码
private static String extractContextTableName(final IValidationContext evalCtx) { final String contextTableName = evalCtx.get_ValueAsString(IValidationContext.PARAMETER_ContextTableName); if (Check.isEmpty(contextTableName)) { throw new AdempiereException("Failed getting " + IValidationContext.PARAMETER_ContextTableName + " from " + evalCtx); } return contextTableName; } private static String extractDocStatus(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_DocStatus); } private static DocTypeId extractDocTypeId(final IValidationContext evalCtx) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocType_ID, -1)); if (docTypeId != null) { return docTypeId; } return DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocTypeTarget_ID, -1)); } private static SOTrx extractSOTrx(final IValidationContext evalCtx) { return SOTrx.ofBoolean(evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_IsSOTrx, false)); } private static boolean extractProcessing(final IValidationContext evalCtx) { final Boolean valueAsBoolean = evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_Processing, false);
return valueAsBoolean != null && valueAsBoolean; } private static String extractOrderType(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_OrderType); } @Override public Set<String> getParameters(@Nullable final String contextTableName) { final HashSet<String> parameters = new HashSet<>(PARAMETERS); final IDocActionOptionsBL docActionOptionsBL = Services.get(IDocActionOptionsBL.class); parameters.addAll(docActionOptionsBL.getRequiredParameters(contextTableName)); return parameters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\DocActionValidationRule.java
1
请完成以下Java代码
public AsyncBeforeUpdate getDelegateAsyncBeforeUpdate() { return delegateAsyncBeforeUpdate; } public void setDelegateAsyncBeforeUpdate(AsyncBeforeUpdate delegateAsyncBeforeUpdate) { this.delegateAsyncBeforeUpdate = delegateAsyncBeforeUpdate; } public AsyncAfterUpdate getDelegateAsyncAfterUpdate() { return delegateAsyncAfterUpdate; } public void setDelegateAsyncAfterUpdate(AsyncAfterUpdate delegateAsyncAfterUpdate) { this.delegateAsyncAfterUpdate = delegateAsyncAfterUpdate; } /** * Delegate interface for the asyncBefore property update. */ public interface AsyncBeforeUpdate { /** * Method which is called if the asyncBefore property should be updated. *
* @param asyncBefore the new value for the asyncBefore flag * @param exclusive the exclusive flag */ public void updateAsyncBefore(boolean asyncBefore, boolean exclusive); } /** * Delegate interface for the asyncAfter property update */ public interface AsyncAfterUpdate { /** * Method which is called if the asyncAfter property should be updated. * * @param asyncAfter the new value for the asyncBefore flag * @param exclusive the exclusive flag */ public void updateAsyncAfter(boolean asyncAfter, boolean exclusive); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ActivityImpl.java
1
请完成以下Java代码
public class X_MobileUI_HUManager extends org.compiere.model.PO implements I_MobileUI_HUManager, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1751514139L; /** Standard Constructor */ public X_MobileUI_HUManager (final Properties ctx, final int MobileUI_HUManager_ID, @Nullable final String trxName) { super (ctx, MobileUI_HUManager_ID, trxName); } /** Load Constructor */ public X_MobileUI_HUManager (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID)
{ if (MobileUI_HUManager_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID); } @Override public int getMobileUI_HUManager_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_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_MobileUI_HUManager.java
1
请在Spring Boot框架中完成以下Java代码
SimpleJmsListenerContainerFactoryConfigurer simpleJmsListenerContainerFactoryConfigurer() { SimpleJmsListenerContainerFactoryConfigurer configurer = new SimpleJmsListenerContainerFactoryConfigurer(); configurer.setDestinationResolver(this.destinationResolver.getIfUnique()); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setExceptionListener(this.exceptionListener.getIfUnique()); configurer.setObservationRegistry(this.observationRegistry.getIfUnique()); configurer.setJmsProperties(this.properties); return configurer; } @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnMissingBean(name = "jmsListenerContainerFactory") DefaultJmsListenerContainerFactory jmsListenerContainerFactory( DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, ConnectionFactoryUnwrapper.unwrapCaching(connectionFactory)); return factory; } @Configuration(proxyBeanMethods = false) @EnableJms
@ConditionalOnMissingBean(name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) static class EnableJmsConfiguration { } @Configuration(proxyBeanMethods = false) @ConditionalOnJndi static class JndiConfiguration { @Bean @ConditionalOnMissingBean(DestinationResolver.class) JndiDestinationResolver destinationResolver() { JndiDestinationResolver resolver = new JndiDestinationResolver(); resolver.setFallbackToDynamicDestination(true); return resolver; } } }
repos\spring-boot-main\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsAnnotationDrivenConfiguration.java
2
请完成以下Java代码
public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_ValueNoCheck (COLUMNNAME_Summary, Summary);
} /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** TaskStatus AD_Reference_ID=366 */ public static final int TASKSTATUS_AD_Reference_ID=366; /** 0% Not Started = 0 */ public static final String TASKSTATUS_0NotStarted = "0"; /** 100% Complete = D */ public static final String TASKSTATUS_100Complete = "D"; /** 20% Started = 2 */ public static final String TASKSTATUS_20Started = "2"; /** 80% Nearly Done = 8 */ public static final String TASKSTATUS_80NearlyDone = "8"; /** 40% Busy = 4 */ public static final String TASKSTATUS_40Busy = "4"; /** 60% Good Progress = 6 */ public static final String TASKSTATUS_60GoodProgress = "6"; /** 90% Finishing = 9 */ public static final String TASKSTATUS_90Finishing = "9"; /** 95% Almost Done = A */ public static final String TASKSTATUS_95AlmostDone = "A"; /** 99% Cleaning up = C */ public static final String TASKSTATUS_99CleaningUp = "C"; /** Set Task Status. @param TaskStatus Status of the Task */ public void setTaskStatus (String TaskStatus) { set_Value (COLUMNNAME_TaskStatus, TaskStatus); } /** Get Task Status. @return Status of the Task */ public String getTaskStatus () { return (String)get_Value(COLUMNNAME_TaskStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestAction.java
1