instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static int toRepoIdOr( @Nullable final UserId userId, final int defaultValue) { return userId != null ? userId.getRepoId() : defaultValue; } public static boolean equals(@Nullable final UserId userId1, @Nullable final UserId userId2) { return Objects.equals(userId1, userId2); } int repoId; private UserId(final int userRepoId) { this.repoId = Check.assumeGreaterOrEqualToZero(userRepoId, "userRepoId");
} @Override @JsonValue public int getRepoId() { return repoId; } public boolean isSystemUser() {return isSystemUser(repoId);} private static boolean isSystemUser(final int repoId) {return repoId == SYSTEM.repoId;} public boolean isRegularUser() {return !isSystemUser();} private static boolean isRegularUser(int repoId) {return !isSystemUser(repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserId.java
1
请完成以下Java代码
public Future<Integer> releaseAfterTrxCommit(final String trxName) { final FutureValue<Integer> countUnlockedFuture = new FutureValue<>(); final ITrxManager trxManager = Services.get(ITrxManager.class); trxManager.getTrxListenerManagerOrAutoCommit(trxName) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> { try { final int countUnlocked = release(); countUnlockedFuture.set(countUnlocked); } catch (Exception e) { countUnlockedFuture.setError(e); } }); return countUnlockedFuture; } @Override public IUnlockCommand setOwner(final LockOwner owner) { this.owner = owner; return this; } @Override public final LockOwner getOwner() { Check.assumeNotNull(owner, UnlockFailedException.class, "owner not null"); return this.owner; } @Override public IUnlockCommand setRecordByModel(final Object model) { _recordsToUnlock.setRecordByModel(model); return this; } @Override public IUnlockCommand setRecordsByModels(final Collection<?> models) {
_recordsToUnlock.setRecordsByModels(models); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final int tableId, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableId, recordId); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final String tableName, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableName, recordId); return this; } @Override public IUnlockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId adPIstanceId) { _recordsToUnlock.setRecordsBySelection(modelClass, adPIstanceId); return this; } @Override public final AdTableId getSelectionToUnlock_AD_Table_ID() { return _recordsToUnlock.getSelection_AD_Table_ID(); } @Override public final PInstanceId getSelectionToUnlock_AD_PInstance_ID() { return _recordsToUnlock.getSelection_PInstanceId(); } @Override public final Iterator<TableRecordReference> getRecordsToUnlockIterator() { return _recordsToUnlock.getRecordsIterator(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\UnlockCommand.java
1
请完成以下Java代码
public void unregisterProducerByTableId(@NonNull final AdTableId tableId) { outboundProducersLock.lock(); try { unregisterProducerByTableId0(tableId); } finally { outboundProducersLock.unlock(); } } private void unregisterProducerByTableId0(@NonNull final AdTableId tableId) { final IDocOutboundProducer producer = outboundProducers.get(tableId); if (producer == null) { // no producer was not registered for given config, nothing to unregister return; } producer.destroy(this);
outboundProducers.remove(tableId); } private List<IDocOutboundProducer> getProducersList() { return new ArrayList<>(outboundProducers.values()); } @Override public void createDocOutbound(@NonNull final Object model) { for (final IDocOutboundProducer producer : getProducersList()) { if (!producer.accept(model)) { continue; } producer.createDocOutbound(model); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundProducerService.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonService { private final PersonRepository personRepository; public PersonService(PersonRepository personRepository) { this.personRepository = personRepository; } public PersonRepository getPersonRepository() { return personRepository; } public Promise<VerifiedPerson> findAndVerifyPerson(String name) { return personRepository.findPerson(name) .combine(findPersonNotes(name), (person, notes) -> new VerifiedPerson(person.name(), person.description(), notes, null)) .map(person -> verify(person));
} private VerifiedPerson verify(VerifiedPerson person) { if(person.description().startsWith("Good")) { return new VerifiedPerson(person.name(), person.description(), person.notes(), "SUCCESS"); } return new VerifiedPerson(person.name(), person.description(), person.notes(), "FAIL"); } private Promise<String> findPersonNotes(String name) { return Promise.of(name + " notes"); } }
repos\tutorials-master\libraries\src\main\java\com\baeldung\activej\service\PersonService.java
2
请完成以下Java代码
public abstract class AbstractDDOrderEvent implements MaterialEvent { @NonNull private final EventDescriptor eventDescriptor; @NonNull private final DDOrder ddOrder; /** * Set to not-null mainly if this event is about and "advise" that was created due to a {@link SupplyRequiredEvent}, but also<br> * if this event is about a "wild" DDOrder that was somehow created and has a sales order line ID */ @Nullable private final SupplyRequiredDescriptor supplyRequiredDescriptor; public AbstractDDOrderEvent( @NonNull final EventDescriptor eventDescriptor, @NonNull final DDOrder ddOrder, @Nullable final SupplyRequiredDescriptor supplyRequiredDescriptor) { this.eventDescriptor = eventDescriptor;
this.ddOrder = ddOrder; this.supplyRequiredDescriptor = supplyRequiredDescriptor; } @JsonIgnore public WarehouseId getFromWarehouseId() {return ddOrder.getSourceWarehouseId();} @JsonIgnore public WarehouseId getToWarehouseId() {return ddOrder.getTargetWarehouseId();} public TableRecordReference getSourceTableReference() { return TableRecordReference.of(I_DD_Order.Table_Name, ddOrder.getDdOrderId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddorder\AbstractDDOrderEvent.java
1
请在Spring Boot框架中完成以下Java代码
public C requestMatchers(String... patterns) { return requestMatchers(null, patterns); } /** * <p> * Match when the {@link HttpMethod} is {@code method} * </p> * <p> * If a specific {@link RequestMatcher} must be specified, use * {@link #requestMatchers(RequestMatcher...)} instead * </p> * @param method the {@link HttpMethod} to use or {@code null} for any * {@link HttpMethod}. * @return the object that is chained after creating the {@link RequestMatcher}. * @since 5.8
*/ public C requestMatchers(HttpMethod method) { return requestMatchers(method, "/**"); } /** * Subclasses should implement this method for returning the object that is chained to * the creation of the {@link RequestMatcher} instances. * @param requestMatchers the {@link RequestMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link RequestMatcher} */ protected abstract C chainRequestMatchers(List<RequestMatcher> requestMatchers); }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\AbstractRequestMatcherRegistry.java
2
请完成以下Java代码
public Instant getLastAccessedTime() { return this.cached.getLastAccessedTime(); } @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); flushIfRequired(); } @Override public Duration getMaxInactiveInterval() { return this.cached.getMaxInactiveInterval(); } @Override public boolean isExpired() { return this.cached.isExpired(); } private void flushIfRequired() { if (RedisSessionRepository.this.flushMode == FlushMode.IMMEDIATE) { save(); } } private boolean hasChangedSessionId() { return !getId().equals(this.originalSessionId); } private void save() { saveChangeSessionId(); saveDelta(); if (this.isNew) {
this.isNew = false; } } private void saveChangeSessionId() { if (hasChangedSessionId()) { if (!this.isNew) { String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey); } this.originalSessionId = getId(); } } private void saveDelta() { if (this.delta.isEmpty()) { return; } String key = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta)); RedisSessionRepository.this.sessionRedisOperations.expireAt(key, Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli()) .plusSeconds(getMaxInactiveInterval().getSeconds())); this.delta.clear(); } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentTermId implements RepoIdAware { @JsonCreator public static PaymentTermId ofRepoId(final int repoId) { return new PaymentTermId(repoId); } @Nullable public static PaymentTermId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<PaymentTermId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } int repoId;
private PaymentTermId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_PaymentTerm_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final PaymentTermId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(@Nullable final PaymentTermId id1, @Nullable final PaymentTermId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\paymentterm\PaymentTermId.java
2
请完成以下Java代码
public void huParentChanged(final I_M_HU hu, final I_M_HU_Item parentHUItemOld) { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); // If it's not an TU or VHU, we shall do nothing if (!handlingUnitsBL.isTransportUnitOrVirtual(hu)) { return; } final I_M_HU tuHU = hu; final IHUReceiptScheduleDAO huReceiptScheduleDAO = Services.get(IHUReceiptScheduleDAO.class); huReceiptScheduleDAO.updateAllocationLUForTU(tuHU); } /** * On split, update transaction's referenced model if missing. * * After that, we relly on {@link #trxLineProcessed(IHUContext, I_M_HU_Trx_Line)} business logic, to create the proper {@link I_M_ReceiptSchedule_Alloc}s. */ @Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { final I_M_ReceiptSchedule referencedModel = findReceiptScheduleFromSplitTransactions(huContext, unloadTrx, loadTrx); if (referencedModel == null) { return; } unloadTrx.setReferencedModel(referencedModel); loadTrx.setReferencedModel(referencedModel); } @Nullable private I_M_ReceiptSchedule findReceiptScheduleFromSplitTransactions(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) {
// // If referenced model of the load transaction is a Receipt Schedule, use that final Object loadReferencedModel = loadTrx.getReferencedModel(); if (InterfaceWrapperHelper.isInstanceOf(loadReferencedModel, I_M_ReceiptSchedule.class)) { return InterfaceWrapperHelper.create(loadReferencedModel, I_M_ReceiptSchedule.class); } // // If referenced model of the unload transaction is a Receipt Schedule, use that final Object unloadReferencedModel = unloadTrx.getReferencedModel(); if (InterfaceWrapperHelper.isInstanceOf(unloadReferencedModel, I_M_ReceiptSchedule.class)) { return InterfaceWrapperHelper.create(unloadReferencedModel, I_M_ReceiptSchedule.class); } // // Find the receipt schedule of the VHU from where we split final I_M_HU fromVHU = unloadTrx.getVHU(); if(X_M_HU.HUSTATUS_Planning.equals(fromVHU.getHUStatus())) { final IHUReceiptScheduleDAO huReceiptScheduleDAO = Services.get(IHUReceiptScheduleDAO.class); return huReceiptScheduleDAO.retrieveReceiptScheduleForVHU(fromVHU); } // Fallback return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUTrxListener.java
1
请完成以下Java代码
public ProcessInstanceStartEventSubscriptionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } public String getProcessDefinitionKey() { return processDefinitionKey; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } public boolean isDoNotUpdateToLatestVersionAutomatically() { return doNotUpdateToLatestVersionAutomatically; } public String getTenantId() { return tenantId;
} @Override public EventSubscription subscribe() { checkValidInformation(); return runtimeService.registerProcessInstanceStartEventSubscription(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionKey)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the key for the subscription to be registered."); } if (correlationParameterValues.isEmpty()) { throw new FlowableIllegalArgumentException( "At least one correlation parameter value must be provided for a dynamic process start event subscription, " + "otherwise the process would get started on all events, regardless their correlation parameter values."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionBuilderImpl.java
1
请完成以下Java代码
private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg) { ByteArrayOutputStream output = new ByteArrayOutputStream(text.length); try { final Cipher cipher = Cipher.getInstance(alg.getJceName()); int limit = Math.min(text.length, alg.getMaxLength()); int pos = 0; while (pos < text.length) { cipher.init(Cipher.ENCRYPT_MODE, key); cipher.update(text, pos, limit); pos += limit; limit = Math.min(text.length - pos, alg.getMaxLength()); byte[] buffer = cipher.doFinal(); output.write(buffer, 0, buffer.length); } return output.toByteArray(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Cannot encrypt", ex); } } private static byte[] decrypt(byte[] text, @Nullable RSAPrivateKey key, RsaAlgorithm alg) { ByteArrayOutputStream output = new ByteArrayOutputStream(text.length); try { final Cipher cipher = Cipher.getInstance(alg.getJceName()); int maxLength = getByteLength(key); int pos = 0; while (pos < text.length) { int limit = Math.min(text.length - pos, maxLength); cipher.init(Cipher.DECRYPT_MODE, key); cipher.update(text, pos, limit);
pos += limit; byte[] buffer = cipher.doFinal(); output.write(buffer, 0, buffer.length); } return output.toByteArray(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Cannot decrypt", ex); } } // copied from sun.security.rsa.RSACore.getByteLength(java.math.BigInteger) public static int getByteLength(@Nullable RSAKey key) { if (key == null) { throw new IllegalArgumentException("key cannot be null"); } int n = key.getModulus().bitLength(); return (n + 7) >> 3; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaRawEncryptor.java
1
请完成以下Java代码
public long getInstances() { return instances; } public void setInstances(long instances) { this.instances = instances; } public long getFinished() { return finished; } public void setFinished(long finished) { this.finished = finished; } public long getCanceled() { return canceled; } public void setCanceled(long canceled) { this.canceled = canceled; } public long getCompleteScope() { return completeScope; } public void setCompleteScope(long completeScope) { this.completeScope = completeScope; } public long getOpenIncidents() { return openIncidents; }
public void setOpenIncidents(long openIncidents) { this.openIncidents = openIncidents; } public long getResolvedIncidents() { return resolvedIncidents; } public void setResolvedIncidents(long resolvedIncidents) { this.resolvedIncidents = resolvedIncidents; } public long getDeletedIncidents() { return deletedIncidents; } public void setDeletedIncidents(long closedIncidents) { this.deletedIncidents = closedIncidents; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityStatisticsImpl.java
1
请完成以下Java代码
public class City implements Serializable { private static final long serialVersionUID = -1L; /** * 城市编号 */ private Long id; /** * 城市名称 */ private String name; /** * 描述 */ private String description; /** * 城市评分 */ private Integer score; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } }
repos\springboot-learning-example-master\spring-data-elasticsearch-crud\src\main\java\org\spring\springboot\domain\City.java
1
请完成以下Java代码
public Object getModel(@NonNull final IContextAware context) { checkModelStaled(context); // // Load the model now final Object cachedModel = modelRef.get(); if (cachedModel != null) { return cachedModel; } final Properties ctx = context.getCtx(); final String trxName = context.getTrxName(); final Object loadedModel = InterfaceWrapperHelper.create(ctx, tableName, getRecord_ID(), Object.class, trxName); modelRef = new SoftReference<>(loadedModel); return loadedModel; } @Override public <T> T getModel(@NonNull final IContextAware context, @NonNull final Class<T> modelClass) { return InterfaceWrapperHelper.create(getModel(context), modelClass); } @NonNull public <T> T getModelNonNull(@NonNull final IContextAware context, @NonNull final Class<T> modelClass) { final T model = InterfaceWrapperHelper.create(getModel(context), modelClass); return Check.assumeNotNull(model, "Model for this TableRecordReference={} may not be null", this); } @Override public void notifyModelStaled() { modelRef = new SoftReference<>(null); } /** * Checks if underlying (and cached) model is still valid in given context. In case is no longer valid, it will be set to <code>null</code>. */ private void checkModelStaled(final IContextAware context) { final Object model = modelRef.get(); if (model == null) { return; } final String modelTrxName = InterfaceWrapperHelper.getTrxName(model); if (!Services.get(ITrxManager.class).isSameTrxName(modelTrxName, context.getTrxName())) { modelRef = new SoftReference<>(null); } // TODO: why the ctx is not validated, like org.adempiere.ad.dao.cache.impl.TableRecordCacheLocal.getValue(Class<RT>) does? } @Deprecated @Override public Object getModel() { return getModel(PlainContextAware.newWithThreadInheritedTrx()); } /**
* Deprecated: pls use appropriate DAO/Repository for loading models * e.g. ModelDAO.getById({@link TableRecordReference#getIdAssumingTableName(String, IntFunction)}) */ @Deprecated @Override public <T> T getModel(final Class<T> modelClass) { return getModel(PlainContextAware.newWithThreadInheritedTrx(), modelClass); } @NonNull public <T> T getModelNonNull(@NonNull final Class<T> modelClass) { return getModelNonNull(PlainContextAware.newWithThreadInheritedTrx(), modelClass); } public static <T> List<T> getModels( @NonNull final Collection<? extends ITableRecordReference> references, @NonNull final Class<T> modelClass) { return references .stream() .map(ref -> ref.getModel(modelClass)) .collect(ImmutableList.toImmutableList()); } public boolean isOfType(@NonNull final Class<?> modelClass) { final String modelTableName = InterfaceWrapperHelper.getTableNameOrNull(modelClass); return modelTableName != null && modelTableName.equals(getTableName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReference.java
1
请在Spring Boot框架中完成以下Java代码
public ObjectFactory jaxbObjectFactoryV1() { return new ObjectFactory(); } // e.g. http://localhost:8080/ws/Msv3VerbindungTestenService.wsdl @Bean(name = TestConnectionWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition testConnectionWebServiceV1() { return createWsdl(TestConnectionWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3VerfuegbarkeitAnfragenService.wsdl @Bean(name = StockAvailabilityWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition stockAvailabilityWebServiceV1() { return createWsdl(StockAvailabilityWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3BestellenService.wsdl @Bean(name = OrderWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition orderWebServiceV1() { return createWsdl(OrderWebServiceV1.WSDL_BEAN_NAME); } // e.g. http://localhost:8080/ws/Msv3BestellstatusAbfragenService.wsdl @Bean(name = OrderStatusWebServiceV1.WSDL_BEAN_NAME) public Wsdl11Definition orderStatusWebServiceV1() { return createWsdl(OrderStatusWebServiceV1.WSDL_BEAN_NAME); } @Bean("Msv3Service_schema1") public XsdSchema msv3serviceSchemaXsdV1()
{ return createXsdSchema("Msv3Service_schema1.xsd"); } @Bean("Msv3FachlicheFunktionen") public XsdSchema msv3FachlicheFunktionenV1() { return createXsdSchema("Msv3FachlicheFunktionen.xsd"); } private static Wsdl11Definition createWsdl(@NonNull final String beanName) { return new SimpleWsdl11Definition(createSchemaResource(beanName + ".wsdl")); } private static XsdSchema createXsdSchema(@NonNull final String resourceName) { return new SimpleXsdSchema(createSchemaResource(resourceName)); } private static ClassPathResource createSchemaResource(@NonNull final String resourceName) { return new ClassPathResource(SCHEMA_RESOURCE_PREFIX + "/" + resourceName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\WebServiceConfigV1.java
2
请在Spring Boot框架中完成以下Java代码
ConcurrentKafkaListenerContainerFactoryConfigurer kafkaListenerContainerFactoryConfigurerVirtualThreads() { ConcurrentKafkaListenerContainerFactoryConfigurer configurer = configurer(); SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor("kafka-"); executor.setVirtualThreads(true); configurer.setListenerTaskExecutor(executor); return configurer; } private ConcurrentKafkaListenerContainerFactoryConfigurer configurer() { ConcurrentKafkaListenerContainerFactoryConfigurer configurer = new ConcurrentKafkaListenerContainerFactoryConfigurer(); configurer.setKafkaProperties(this.properties); configurer.setBatchMessageConverter(this.batchMessageConverter); configurer.setRecordMessageConverter(this.recordMessageConverter); configurer.setRecordFilterStrategy(this.recordFilterStrategy); configurer.setReplyTemplate(this.kafkaTemplate); configurer.setTransactionManager(this.transactionManager); configurer.setRebalanceListener(this.rebalanceListener); configurer.setCommonErrorHandler(this.commonErrorHandler); configurer.setAfterRollbackProcessor(this.afterRollbackProcessor); configurer.setRecordInterceptor(this.recordInterceptor); configurer.setBatchInterceptor(this.batchInterceptor); configurer.setThreadNameSupplier(this.threadNameSupplier); return configurer; }
@Bean @ConditionalOnMissingBean(name = "kafkaListenerContainerFactory") ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory( ConcurrentKafkaListenerContainerFactoryConfigurer configurer, ObjectProvider<ConsumerFactory<Object, Object>> kafkaConsumerFactory, ObjectProvider<ContainerCustomizer<Object, Object, ConcurrentMessageListenerContainer<Object, Object>>> kafkaContainerCustomizer) { ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>(); configurer.configure(factory, kafkaConsumerFactory .getIfAvailable(() -> new DefaultKafkaConsumerFactory<>(this.properties.buildConsumerProperties()))); kafkaContainerCustomizer.ifAvailable(factory::setContainerCustomizer); return factory; } @Configuration(proxyBeanMethods = false) @EnableKafka @ConditionalOnMissingBean(name = KafkaListenerConfigUtils.KAFKA_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) static class EnableKafkaConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAnnotationDrivenConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
JvmGcMetrics jvmGcMetrics() { return new JvmGcMetrics(); } @Bean @ConditionalOnMissingBean JvmHeapPressureMetrics jvmHeapPressureMetrics() { return new JvmHeapPressureMetrics(); } @Bean @ConditionalOnMissingBean JvmMemoryMetrics jvmMemoryMetrics(ObjectProvider<JvmMemoryMeterConventions> jvmMemoryMeterConventions) { JvmMemoryMeterConventions conventions = jvmMemoryMeterConventions.getIfAvailable(); return (conventions != null) ? new JvmMemoryMetrics(Collections.emptyList(), conventions) : new JvmMemoryMetrics(); } @Bean @ConditionalOnMissingBean JvmThreadMetrics jvmThreadMetrics(ObjectProvider<JvmThreadMeterConventions> jvmThreadMeterConventions) { JvmThreadMeterConventions conventions = jvmThreadMeterConventions.getIfAvailable(); return (conventions != null) ? new JvmThreadMetrics(Collections.emptyList(), conventions) : new JvmThreadMetrics(); } @Bean @ConditionalOnMissingBean ClassLoaderMetrics classLoaderMetrics( ObjectProvider<JvmClassLoadingMeterConventions> jvmClassLoadingMeterConventions) { JvmClassLoadingMeterConventions conventions = jvmClassLoadingMeterConventions.getIfAvailable(); return (conventions != null) ? new ClassLoaderMetrics(conventions) : new ClassLoaderMetrics(); } @Bean @ConditionalOnMissingBean JvmInfoMetrics jvmInfoMetrics() { return new JvmInfoMetrics(); } @Bean @ConditionalOnMissingBean JvmCompilationMetrics jvmCompilationMetrics() { return new JvmCompilationMetrics(); } @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = VIRTUAL_THREAD_METRICS_CLASS) static class VirtualThreadMetricsConfiguration { @Bean @ConditionalOnMissingBean(type = VIRTUAL_THREAD_METRICS_CLASS) @ImportRuntimeHints(VirtualThreadMetricsRuntimeHintsRegistrar.class) MeterBinder virtualThreadMetrics() throws ClassNotFoundException { Class<?> virtualThreadMetricsClass = ClassUtils.forName(VIRTUAL_THREAD_METRICS_CLASS, getClass().getClassLoader()); return (MeterBinder) BeanUtils.instantiateClass(virtualThreadMetricsClass); } } static final class VirtualThreadMetricsRuntimeHintsRegistrar implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerTypeIfPresent(classLoader, VIRTUAL_THREAD_METRICS_CLASS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
repos\spring-boot-main\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\jvm\JvmMetricsAutoConfiguration.java
2
请完成以下Java代码
public List<I_GL_DistributionLine> retrieveLines(final I_GL_Distribution glDistribution) { Check.assumeNotNull(glDistribution, "glDistribution not null"); final Properties ctx = InterfaceWrapperHelper.getCtx(glDistribution); final String trxName = InterfaceWrapperHelper.getTrxName(glDistribution); final int glDistributionId = glDistribution.getGL_Distribution_ID(); final List<I_GL_DistributionLine> lines = retrieveLines(ctx, glDistributionId, trxName); // optimization for (final I_GL_DistributionLine line : lines) { line.setGL_Distribution(glDistribution); } return lines; } @Cached(cacheName = I_GL_DistributionLine.Table_Name + "#by#" + I_GL_DistributionLine.COLUMNNAME_GL_Distribution_ID) List<I_GL_DistributionLine> retrieveLines(@CacheCtx final Properties ctx, final int glDistributionId, @CacheTrx final String trxName) { return Services.get(IQueryBL.class) .createQueryBuilder(I_GL_DistributionLine.class, ctx, trxName) .addEqualsFilter(I_GL_DistributionLine.COLUMN_GL_Distribution_ID, glDistributionId) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(I_GL_DistributionLine.COLUMN_Line)
.endOrderBy() // .create() .list(I_GL_DistributionLine.class); } @Override public final int retrieveLastLineNo(final I_GL_Distribution glDistribution) { Check.assumeNotNull(glDistribution, "glDistribution not null"); final Integer lastLineNo = Services.get(IQueryBL.class) .createQueryBuilder(I_GL_DistributionLine.class, glDistribution) .addEqualsFilter(I_GL_DistributionLine.COLUMN_GL_Distribution_ID, glDistribution.getGL_Distribution_ID()) // .create() .aggregate(I_GL_DistributionLine.COLUMNNAME_Line, Aggregate.MAX, Integer.class); return lastLineNo == null ? 0 : lastLineNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gldistribution\impl\GLDistributionDAO.java
1
请完成以下Java代码
public long getSecondsToWaitOnShutdown() { return getConfiguration().getAwaitTerminationPeriod().getSeconds(); } public void setSecondsToWaitOnShutdown(long secondsToWaitOnShutdown) { getConfiguration().setAwaitTerminationPeriod(Duration.ofSeconds(secondsToWaitOnShutdown)); } public BlockingQueue<Runnable> getThreadPoolQueue() { return threadPoolQueue; } public void setThreadPoolQueue(BlockingQueue<Runnable> threadPoolQueue) { this.threadPoolQueue = threadPoolQueue; } public String getThreadPoolNamingPattern() { return getConfiguration().getThreadPoolNamingPattern(); } public void setThreadPoolNamingPattern(String threadPoolNamingPattern) { getConfiguration().setThreadPoolNamingPattern(threadPoolNamingPattern); }
public ThreadFactory getThreadFactory() { return threadFactory; } public void setThreadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; } public RejectedExecutionHandler getRejectedExecutionHandler() { return rejectedExecutionHandler; } public void setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) { this.rejectedExecutionHandler = rejectedExecutionHandler; } @Override public int getRemainingCapacity() { return threadPoolQueue.remainingCapacity(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\DefaultAsyncTaskExecutor.java
1
请完成以下Java代码
public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public String getCallbackId() { return callbackId; } public Set<String> getCallBackIds() { return callbackIds; } public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public List<ExecutionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; }
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return null; } public String getParentScopeId() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
static HandlerFilterFunction<ServerResponse, ServerResponse> rewritePath(String regexp, String replacement) { return ofRequestProcessor(BeforeFilterFunctions.rewritePath(regexp, replacement)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> rewriteResponseHeader(String name, String regexp, String replacement) { return ofResponseProcessor(AfterFilterFunctions.rewriteResponseHeader(name, regexp, replacement)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> routeId(String routeId) { return ofRequestProcessor(BeforeFilterFunctions.routeId(routeId)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setPath(String path) { return ofRequestProcessor(BeforeFilterFunctions.setPath(path)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestHeader(String name, String value) { return ofRequestProcessor(BeforeFilterFunctions.setRequestHeader(name, value)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestHostHeader(String host) { return ofRequestProcessor(BeforeFilterFunctions.setRequestHostHeader(host)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setResponseHeader(String name, String value) { return ofResponseProcessor(AfterFilterFunctions.setResponseHeader(name, value)); } static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix() { return stripPrefix(1); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> stripPrefix(int parts) { return ofRequestProcessor(BeforeFilterFunctions.stripPrefix(parts)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(int statusCode) { return setStatus(new HttpStatusHolder(null, statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusCode statusCode) { return setStatus(new HttpStatusHolder(statusCode, null)); }
@Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> setStatus(HttpStatusHolder statusCode) { return ofResponseProcessor(AfterFilterFunctions.setStatus(statusCode)); } static HandlerFilterFunction<ServerResponse, ServerResponse> uri(String uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } @Shortcut static HandlerFilterFunction<ServerResponse, ServerResponse> uri(URI uri) { return ofRequestProcessor(BeforeFilterFunctions.uri(uri)); } class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(FilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FilterFunctions.java
1
请完成以下Java代码
public ProcessDefinitionCacheEntry getProcessDefinitionCacheEntry(String processDefinitionId) { return processDefinitionCache.get(processDefinitionId); } // getters and setters //////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew;
} @Override public String getEngineVersion() { return engineVersion; } @Override public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } @Override public String getDerivedFrom() { return derivedFrom; } @Override public void setDerivedFrom(String derivedFrom) { this.derivedFrom = derivedFrom; } @Override public String getDerivedFromRoot() { return derivedFromRoot; } @Override public void setDerivedFromRoot(String derivedFromRoot) { this.derivedFromRoot = derivedFromRoot; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "DeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java
1
请完成以下Java代码
public ReturnsInOutHeaderFiller setReturnsDocTypeIdProvider(final IReturnsDocTypeIdProvider returnsDocTypeIdProvider) { this.returnsDocTypeIdProvider = returnsDocTypeIdProvider; return this; } private int getReturnsDocTypeId(final String docBaseType, final boolean isSOTrx, final int adClientId, final int adOrgId) { return returnsDocTypeIdProvider.getReturnsDocTypeId(docBaseType, isSOTrx, adClientId, adOrgId); } public ReturnsInOutHeaderFiller setBPartnerId(final int bpartnerId) { this.bpartnerId = bpartnerId; return this; } private int getBPartnerId() { return bpartnerId; } public ReturnsInOutHeaderFiller setBPartnerLocationId(final int bpartnerLocationId) { this.bpartnerLocationId = bpartnerLocationId; return this; } private int getBPartnerLocationId() { return bpartnerLocationId; } public ReturnsInOutHeaderFiller setMovementDate(final Timestamp movementDate) { this.movementDate = movementDate; return this; } private Timestamp getMovementDate() { return movementDate; } public ReturnsInOutHeaderFiller setWarehouseId(final int warehouseId) { this.warehouseId = warehouseId; return this; } private int getWarehouseId() { return warehouseId; } public ReturnsInOutHeaderFiller setOrder(@Nullable final I_C_Order order) { this.order = order; return this; } private I_C_Order getOrder() { return order; }
public ReturnsInOutHeaderFiller setExternalId(@Nullable final String externalId) { this.externalId = externalId; return this; } private String getExternalId() { return this.externalId; } private String getExternalResourceURL() { return this.externalResourceURL; } public ReturnsInOutHeaderFiller setExternalResourceURL(@Nullable final String externalResourceURL) { this.externalResourceURL = externalResourceURL; return this; } public ReturnsInOutHeaderFiller setDateReceived(@Nullable final Timestamp dateReceived) { this.dateReceived = dateReceived; return this; } private Timestamp getDateReceived() { return dateReceived; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsInOutHeaderFiller.java
1
请在Spring Boot框架中完成以下Java代码
public class MultipleMongoConfig { @Autowired private MultipleMongoProperties mongoProperties; @Primary @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE) public MongoTemplate primaryMongoTemplate() throws Exception { return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary())); } @Bean @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE) public MongoTemplate secondaryMongoTemplate() throws Exception { return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
} @Bean @Primary public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception { MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getPrimary().getUri())); return new SimpleMongoDbFactory(client, mongoProperties.getPrimary().getDatabase()); } @Bean public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception { MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getSecondary().getUri())); return new SimpleMongoDbFactory(client, mongoProperties.getSecondary().getDatabase()); } }
repos\spring-boot-leaning-master\1.x\第12课:MongoDB 实战\spring-boot-multi-mongodb\src\main\java\com\neo\config\MultipleMongoConfig.java
2
请完成以下Java代码
public void setAD_UserGroup(org.compiere.model.I_AD_UserGroup AD_UserGroup) { set_ValueFromPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class, AD_UserGroup); } /** Set Users Group. @param AD_UserGroup_ID Users Group */ @Override public void setAD_UserGroup_ID (int AD_UserGroup_ID) { if (AD_UserGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID)); } /** Get Users Group. @return Users Group */ @Override public int getAD_UserGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Users Group User Assignment. @param AD_UserGroup_User_Assign_ID Users Group User Assignment */ @Override public void setAD_UserGroup_User_Assign_ID (int AD_UserGroup_User_Assign_ID) { if (AD_UserGroup_User_Assign_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UserGroup_User_Assign_ID, Integer.valueOf(AD_UserGroup_User_Assign_ID)); } /** Get Users Group User Assignment. @return Users Group User Assignment */ @Override public int getAD_UserGroup_User_Assign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_User_Assign_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab.
@param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserGroup_User_Assign.java
1
请完成以下Java代码
public HandlerMethodArgumentResolverComposite getResolvers() { return this.resolvers; } /** * Get the method argument values for the current request, checking the provided * argument values and falling back to the configured argument resolvers. * @param environment the data fetching environment to resolve arguments from * @param providedArgs the arguments provided directly */ protected @Nullable Object[] getMethodArgumentValues( DataFetchingEnvironment environment, Object... providedArgs) throws Exception { MethodParameter[] parameters = getMethodParameters(); if (ObjectUtils.isEmpty(parameters)) { return EMPTY_ARGS; } @Nullable Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); args[i] = findProvidedArgument(parameter, providedArgs); if (args[i] != null) { continue; }
if (!this.resolvers.supportsParameter(parameter)) { throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver")); } try { args[i] = this.resolvers.resolveArgument(parameter, environment); } catch (Exception ex) { // Leave stack trace for later, exception may actually be resolved and handled... if (logger.isDebugEnabled()) { String exMsg = ex.getMessage(); if (exMsg != null && !exMsg.contains(parameter.getExecutable().toGenericString())) { logger.debug(formatArgumentError(parameter, exMsg)); } } throw ex; } } return args; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\DataFetcherHandlerMethodSupport.java
1
请完成以下Java代码
public class OssFileController { @Autowired private IOssFileService ossFileService; @ResponseBody @GetMapping("/list") public Result<IPage<OssFile>> queryPageList(OssFile file, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { Result<IPage<OssFile>> result = new Result<>(); QueryWrapper<OssFile> queryWrapper = QueryGenerator.initQueryWrapper(file, req.getParameterMap()); Page<OssFile> page = new Page<>(pageNo, pageSize); IPage<OssFile> pageList = ossFileService.page(page, queryWrapper); result.setSuccess(true); result.setResult(pageList); return result; } @ResponseBody @PostMapping("/upload") //@RequiresRoles("admin") @RequiresPermissions("system:ossFile:upload") public Result upload(@RequestParam("file") MultipartFile multipartFile) { Result result = new Result(); try { ossFileService.upload(multipartFile); result.success("上传成功!"); } catch (Exception ex) { log.info(ex.getMessage(), ex); result.error500("上传失败"); } return result; }
@ResponseBody @DeleteMapping("/delete") public Result delete(@RequestParam(name = "id") String id) { Result result = new Result(); OssFile file = ossFileService.getById(id); if (file == null) { result.error500("未找到对应实体"); }else { boolean ok = ossFileService.delete(file); result.success("删除成功!"); } return result; } /** * 通过id查询. */ @ResponseBody @GetMapping("/queryById") public Result<OssFile> queryById(@RequestParam(name = "id") String id) { Result<OssFile> result = new Result<>(); OssFile file = ossFileService.getById(id); if (file == null) { result.error500("未找到对应实体"); } else { result.setResult(file); result.setSuccess(true); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\oss\controller\OssFileController.java
1
请完成以下Java代码
public void stop() throws Exception { } /* * (non-Javadoc) * * @see org.eclipse.jetty.server.Handler#destroy() */ @Override public void destroy() { } /* * (non-Javadoc) * * @see org.eclipse.jetty.server.Handler#getServer() */ @Override public Server getServer() { return null; } /* * (non-Javadoc)
* * @see org.eclipse.jetty.server.Handler#handle(java.lang.String, * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException { LOG.info("Received a new request"); } /* * (non-Javadoc) * * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server. * Server) */ @Override public void setServer(Server server) { } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\jetty\programmatic\LoggingRequestHandler.java
1
请完成以下Java代码
public class SoehenleResponseStringParser implements IParser<ISoehenleCmd> { private static final Logger logger = LogManager.getLogger(SoehenleResponseStringParser.class); public static final int STATUS_IN_ALIBISPEICHER_EXPECTED_LENGTH = 15; public static final int STATUS_EXPECTED_LENGTH = 7; @SuppressWarnings("unchecked") @Override public <T> T parse(final ISoehenleCmd cmd, final String stringToParse, final String elementName, final Class<T> clazz) { try { if (Check.isBlank(stringToParse)) { Loggables.withLogger(logger, Level.INFO).addLog("The scale returned no value for cmd={};", cmd); return (T)ZERO.toString(); } final SoehenleResultStringElement elementInfo = cmd.getResultElements().get(elementName); final String[] tokens = stringToParse.split(" +"); // split string around spaces final String status = getStatus(cmd, tokens); //underweight if (status.startsWith("1")) { Loggables.withLogger(logger, Level.INFO).addLog("The scale returned an underweight measurement {} for cmd={};Returning 0;", stringToParse, cmd); return (T)ZERO.toString(); } //overweight if (status.startsWith("01")) { Loggables.withLogger(logger, Level.INFO).addLog("The scale returned an overweight measurement {} for cmd={};Returning 0;", stringToParse, cmd); return (T)ZERO.toString(); } final String resultToken = tokens[elementInfo.getPosition() - 1]; return (T)resultToken; }
catch (final Exception e) { throw new ParserException(cmd, stringToParse, elementName, clazz, e); } } private static String getStatus(final ISoehenleCmd cmd, final String[] tokens) { final SoehenleResultStringElement statusInfo = cmd.getResultElements().get(RESULT_ELEMENT_STATUS); final String status = tokens[statusInfo.getPosition() - 1]; if (status.length() == STATUS_IN_ALIBISPEICHER_EXPECTED_LENGTH) //Message is in Alibispeicher format, drop the first 8 characters { return status.substring(8); } if (status.length() != STATUS_EXPECTED_LENGTH) { Loggables.withLogger(logger, Level.WARN).addLog("Found an incorrectly formatted status: {} ", status); } return status; } @Override public String toString() { return "SicsResponseStringParser []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\soehenle\SoehenleResponseStringParser.java
1
请在Spring Boot框架中完成以下Java代码
public static class LogoutOnRequestConfiguration { @Bean public SecurityFilterChain filterChainLogoutOnRequest(HttpSecurity http) throws Exception { http.securityMatcher("/request/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/request/logout") .addLogoutHandler((request, response, auth) -> { try { request.logout(); } catch (ServletException e) { logger.error(e.getMessage()); } })); return http.build(); } } @Order(3) @Configuration public static class DefaultLogoutConfiguration { @Bean public SecurityFilterChain filterChainDefaultLogout(HttpSecurity http) throws Exception { http.securityMatcher("/basic/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/basic/basiclogout")); return http.build(); } } @Order(2) @Configuration public static class AllCookieClearingLogoutConfiguration { @Bean public SecurityFilterChain filterChainAllCookieClearing(HttpSecurity http) throws Exception { http.securityMatcher("/cookies/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/cookies/cookielogout") .addLogoutHandler(new SecurityContextLogoutHandler()) .addLogoutHandler((request, response, auth) -> { for (Cookie cookie : request.getCookies()) { String cookieName = cookie.getName();
Cookie cookieToDelete = new Cookie(cookieName, null); cookieToDelete.setMaxAge(0); response.addCookie(cookieToDelete); } })); return http.build(); } } @Order(1) @Configuration public static class ClearSiteDataHeaderLogoutConfiguration { private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; @Bean public SecurityFilterChain filterChainClearSiteDataHeader(HttpSecurity http) throws Exception { http.securityMatcher("/csd/**") .authorizeHttpRequests(authz -> authz.anyRequest() .permitAll()) .logout(logout -> logout.logoutUrl("/csd/csdlogout") .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))); return http.build(); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\manuallogout\SimpleSecurityConfiguration.java
2
请完成以下Java代码
private OrderLinePackingMaterialDocumentLineSource toImpl(final IPackingMaterialDocumentLineSource source) { return (OrderLinePackingMaterialDocumentLineSource)source; } @Override protected void removeDocumentLine(final IPackingMaterialDocumentLine pmLine) { final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine); final I_C_OrderLine pmOrderLine = orderLinePMLine.getC_OrderLine(); if (!InterfaceWrapperHelper.isNew(pmOrderLine)) { InterfaceWrapperHelper.delete(pmOrderLine); } } @Override protected void createDocumentLine(final IPackingMaterialDocumentLine pmLine) { final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine); final I_C_OrderLine pmOrderLine = orderLinePMLine.getC_OrderLine(); // qtyOrdered is in the product's UOM whereas QtyEntered is in the order line's UOM. They don't have to be the same. // pmOrderLine.setQtyEntered(pmOrderLine.getQtyOrdered()); final boolean ordereWasInactive = !pmOrderLine.isActive(); pmOrderLine.setIsActive(true); if (ordereWasInactive) { // while the order line was inactive e.g. the order's datePromised might have been changed orderLineBL.setOrder(pmOrderLine, order); } orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder() .orderLine(pmOrderLine) .resultUOM(ResultUOM.CONTEXT_UOM) .updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true) .updateLineNetAmt(true) .build());
InterfaceWrapperHelper.save(pmOrderLine); } @Override protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source, final IPackingMaterialDocumentLine pmLine) { final OrderLinePackingMaterialDocumentLineSource orderLineSource = toImpl(source); final OrderLinePackingMaterialDocumentLine orderLinePMLine = toImpl(pmLine); final I_C_OrderLine regularOrderLine = orderLineSource.getC_OrderLine(); Check.assume(regularOrderLine.getC_OrderLine_ID() > 0, "Regular order line shall be already saved: {}", regularOrderLine); final I_C_OrderLine pmOrderLine; if (orderLinePMLine == null) { pmOrderLine = null; } else { pmOrderLine = orderLinePMLine.getC_OrderLine(); } regularOrderLine.setC_PackingMaterial_OrderLine(pmOrderLine); InterfaceWrapperHelper.save(regularOrderLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderPackingMaterialDocumentLinesBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class ShiroRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; /** * 获取用户角色和权限 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) { return null; } /** * 登录认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String userName = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo"); User user = userMapper.findByUserName(userName);
if (user == null) { throw new UnknownAccountException("用户名或密码错误!"); } if (!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("用户名或密码错误!"); } if (user.getStatus().equals("0")) { throw new LockedAccountException("账号已被锁定,请联系管理员!"); } SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; } }
repos\SpringAll-master\11.Spring-Boot-Shiro-Authentication\src\main\java\com\springboot\shiro\ShiroRealm.java
2
请完成以下Java代码
public OidcIdToken getIdToken() { return this.idToken; } /** * Returns the {@link OidcUserInfo UserInfo} containing claims about the user, may be * {@code null}. * @return the {@link OidcUserInfo} containing claims about the user, or {@code null} */ public OidcUserInfo getUserInfo() { return this.userInfo; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } if (!super.equals(obj)) { return false; } OidcUserAuthority that = (OidcUserAuthority) obj; if (!this.getIdToken().equals(that.getIdToken())) { return false;
} return (this.getUserInfo() != null) ? this.getUserInfo().equals(that.getUserInfo()) : that.getUserInfo() == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + this.getIdToken().hashCode(); result = 31 * result + ((this.getUserInfo() != null) ? this.getUserInfo().hashCode() : 0); return result; } static Map<String, Object> collectClaims(OidcIdToken idToken, OidcUserInfo userInfo) { Assert.notNull(idToken, "idToken cannot be null"); Map<String, Object> claims = new HashMap<>(); if (userInfo != null) { claims.putAll(userInfo.getClaims()); } claims.putAll(idToken.getClaims()); return claims; } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\user\OidcUserAuthority.java
1
请完成以下Java代码
public boolean isReadable() { return this.delegate.isReadable(); } @Override public Instant lastModified() { return this.delegate.lastModified(); } @Override public long length() { return this.delegate.length(); } @Override public URI getURI() { return this.delegate.getURI(); } @Override public String getName() { return this.delegate.getName(); } @Override public String getFileName() { return this.delegate.getFileName(); } @Override public InputStream newInputStream() throws IOException { return this.delegate.newInputStream(); } @Override @SuppressWarnings({ "deprecation", "removal" }) public ReadableByteChannel newReadableByteChannel() throws IOException { return this.delegate.newReadableByteChannel(); } @Override public List<Resource> list() { return asLoaderHidingResources(this.delegate.list()); } private boolean nonLoaderResource(Resource resource) { return !resource.getPath().startsWith(this.loaderBasePath); } private List<Resource> asLoaderHidingResources(Collection<Resource> resources) { return resources.stream().filter(this::nonLoaderResource).map(this::asLoaderHidingResource).toList(); }
private Resource asLoaderHidingResource(Resource resource) { return (resource instanceof LoaderHidingResource) ? resource : new LoaderHidingResource(this.base, resource); } @Override public @Nullable Resource resolve(String subUriPath) { if (subUriPath.startsWith(LOADER_RESOURCE_PATH_PREFIX)) { return null; } Resource resolved = this.delegate.resolve(subUriPath); return (resolved != null) ? new LoaderHidingResource(this.base, resolved) : null; } @Override public boolean isAlias() { return this.delegate.isAlias(); } @Override public URI getRealURI() { return this.delegate.getRealURI(); } @Override public void copyTo(Path destination) throws IOException { this.delegate.copyTo(destination); } @Override public Collection<Resource> getAllResources() { return asLoaderHidingResources(this.delegate.getAllResources()); } @Override public String toString() { return this.delegate.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\LoaderHidingResource.java
1
请完成以下Java代码
public class Person { @Id private UUID id; private String firstName; public Person(final UUID id, final String firstName) { this.id = id; this.firstName = firstName; } private Person() { } public UUID getId() { return id; }
public String getFirstName() { return firstName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return Objects.equals(id, person.id) && Objects.equals(firstName, person.firstName); } @Override public int hashCode() { return Objects.hash(id, firstName); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-data-couchbase\src\main\java\com\baeldung\couchbase\domain\Person.java
1
请完成以下Java代码
public static X_AD_ReplicationTable getReplicationTable(Properties ctx ,int AD_ReplicationStrategy_ID, int AD_Table_ID) { final String whereClause = I_AD_ReplicationTable.COLUMNNAME_AD_ReplicationStrategy_ID + "=? AND " + I_AD_ReplicationTable.COLUMNNAME_AD_Table_ID + "=?"; return new Query(ctx, I_AD_ReplicationTable.Table_Name, whereClause, null) // .setClient_ID() // TODO: metas: tsa: debugging .setOnlyActiveRecords(true) .setRequiredAccess(Access.READ) .setParameters(AD_ReplicationStrategy_ID, AD_Table_ID) .firstOnly(X_AD_ReplicationTable.class) ; } /** * * @param AD_Table_ID * @return X_AD_ReplicationDocument Document to replication */ public static X_AD_ReplicationDocument getReplicationDocument(Properties ctx ,int AD_ReplicationStrategy_ID , int AD_Table_ID) { final String whereClause = I_AD_ReplicationDocument.COLUMNNAME_AD_ReplicationStrategy_ID + "=? AND " + I_AD_ReplicationDocument.COLUMNNAME_AD_Table_ID + "=?"; return new Query(ctx, I_AD_ReplicationDocument.Table_Name, whereClause, null) .setClient_ID() .setOnlyActiveRecords(true) .setRequiredAccess(Access.READ) .setParameters(AD_ReplicationStrategy_ID, AD_Table_ID) .first() ; } /** * * @param AD_Table_ID
* @return X_AD_ReplicationDocument Document to replication */ public static X_AD_ReplicationDocument getReplicationDocument(Properties ctx ,int AD_ReplicationStrategy_ID , int AD_Table_ID, int C_DocType_ID) { final String whereClause = I_AD_ReplicationDocument.COLUMNNAME_AD_ReplicationStrategy_ID + "=? AND " + I_AD_ReplicationDocument.COLUMNNAME_AD_Table_ID + "=? AND " + I_AD_ReplicationDocument.COLUMNNAME_C_DocType_ID + "=?"; return new Query(ctx, X_AD_ReplicationDocument.Table_Name, whereClause, null) .setClient_ID() .setOnlyActiveRecords(true) .setRequiredAccess(Access.READ) .setParameters(AD_ReplicationStrategy_ID, AD_Table_ID, C_DocType_ID) .first(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MReplicationStrategy.java
1
请完成以下Java代码
public void setPreAuthenticatedUserDetailsService( AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> uds) { this.preAuthenticatedUserDetailsService = uds; } /** * If true, causes the provider to throw a BadCredentialsException if the presented * authentication request is invalid (contains a null principal or credentials). * Otherwise it will just return null. Defaults to false. */ public void setThrowExceptionWhenTokenRejected(boolean throwExceptionWhenTokenRejected) { this.throwExceptionWhenTokenRejected = throwExceptionWhenTokenRejected; } /** * Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt> * object for the user. Defaults to an {@link AccountStatusUserDetailsChecker}. * @param userDetailsChecker */ public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) { Assert.notNull(userDetailsChecker, "userDetailsChecker cannot be null"); this.userDetailsChecker = userDetailsChecker;
} /** * Sets authorities that this provider should grant once authentication completes * @param grantedAuthoritySupplier the supplier that grants authorities */ public void setGrantedAuthoritySupplier(Supplier<Collection<GrantedAuthority>> grantedAuthoritySupplier) { Assert.notNull(grantedAuthoritySupplier, "grantedAuthoritySupplier cannot be null"); this.grantedAuthoritySupplier = grantedAuthoritySupplier; } @Override public int getOrder() { return this.order; } public void setOrder(int i) { this.order = i; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\PreAuthenticatedAuthenticationProvider.java
1
请完成以下Java代码
public static boolean doesProductMatchFilter( @NonNull final I_M_Product product, @NonNull final ProductFilterVO filterVO) { final boolean ignoreCase = true; // ProductName final String productName = filterVO.getProductName(); if (!Check.isEmpty(productName, true)) { final StringLikeFilter<I_M_Product> likeFilter = new StringLikeFilter<>(I_M_Product.COLUMNNAME_Name, productName, ignoreCase); if (!likeFilter.accept(product)) { return false; } } // ProductValue final String productValue = filterVO.getProductValue(); if (!Check.isEmpty(productValue, true)) { final StringLikeFilter<I_M_Product> likeFilter = new StringLikeFilter<>(I_M_Product.COLUMNNAME_Value, productValue, ignoreCase); if (!likeFilter.accept(product)) { return false; } } // Product Category if (filterVO.getProductCategoryId() > 0 && product.getM_Product_Category_ID() != filterVO.getProductCategoryId()) { return false; }
// IsPurchase if (filterVO.getIsPurchased() != null && filterVO.getIsPurchased() != product.isPurchased()) { return false; } // IsSold if (filterVO.getIsSold() != null && filterVO.getIsSold() != product.isSold()) { return false; } // IsActive if (filterVO.getIsActive() != null && filterVO.getIsActive() != product.isActive()) { return false; } // Discontinued if (filterVO.getIsDiscontinued() != null && filterVO.getIsDiscontinued() != product.isDiscontinued()) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\ProductFilterUtil.java
1
请完成以下Java代码
private final UserNotificationRequest createFlatrateTermGeneratedEvent( @NonNull final I_C_Flatrate_Term contract, final UserId recipientUserId, @NonNull final AdMessageKey message) { if (recipientUserId == null) { // nothing to do return null; } final TableRecordReference flatrateTermRef = TableRecordReference.of(contract); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(message) .targetAction(TargetRecordAction.ofRecordAndWindow(flatrateTermRef, Contracts_Constants.CONTRACTS_WINDOW_ID))
.build(); } private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private void postNotification(final UserNotificationRequest notification) { Services.get(INotificationBL.class).sendAfterCommit(notification); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\event\FlatrateUserNotificationsProducer.java
1
请完成以下Java代码
public class Person { private String name = "John"; private byte age = 30; private short uidNumber = 5555; private int pinCode = 452002; private long contactNumber = 123456789L; private float height = 6.1242f; private double weight = 75.2564; private char gender = 'M'; private boolean active = true; public String getName() { return name; } public void setName(String name) { this.name = name; } public byte getAge() { return age; } public void setAge(byte age) { this.age = age; } public short getUidNumber() { return uidNumber; } public void setUidNumber(short uidNumber) { this.uidNumber = uidNumber; } public int getPinCode() { return pinCode; } public void setPinCode(int pinCode) { this.pinCode = pinCode; } public long getContactNumber() { return contactNumber;
} public void setContactNumber(long contactNumber) { this.contactNumber = contactNumber; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
repos\tutorials-master\core-java-modules\core-java-reflection\src\main\java\com\baeldung\reflection\access\privatefields\Person.java
1
请完成以下Java代码
public void setScriptScannerFactory(final IScriptScannerFactory scriptScannerFactory) { getDelegate().setScriptScannerFactory(scriptScannerFactory); } @Override public IScriptScannerFactory getScriptScannerFactory() { return getDelegate().getScriptScannerFactory(); } @Override public IScriptScannerFactory getScriptScannerFactoryToUse() { return getDelegate().getScriptScannerFactoryToUse(); } @Override public IScriptFactory getScriptFactory() { return getDelegate().getScriptFactory(); } @Override public void setScriptFactory(final IScriptFactory scriptFactory) { getDelegate().setScriptFactory(scriptFactory); } @Override
public IScriptFactory getScriptFactoryToUse() { return getDelegate().getScriptFactoryToUse(); } @Override public boolean hasNext() { return getDelegate().hasNext(); } @Override public IScript next() { return getDelegate().next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ForwardingScriptScanner.java
1
请完成以下Java代码
public String[] toWordArray() { List<Word> wordList = toSimpleWordList(); String[] wordArray = new String[wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < wordArray.length; i++) { wordArray[i] = iterator.next().value; } return wordArray; } /** * word pos * * @return */ public String[][] toWordTagArray() { List<Word> wordList = toSimpleWordList(); String[][] pair = new String[2][wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < pair[0].length; i++) { Word word = iterator.next(); pair[0][i] = word.value; pair[1][i] = word.label; } return pair; } /** * word pos ner * * @param tagSet * @return */ public String[][] toWordTagNerArray(NERTagSet tagSet) { List<String[]> tupleList = Utility.convertSentenceToNER(this, tagSet); String[][] result = new String[3][tupleList.size()]; Iterator<String[]> iterator = tupleList.iterator(); for (int i = 0; i < result[0].length; i++) { String[] tuple = iterator.next(); for (int j = 0; j < 3; ++j) { result[j][i] = tuple[j]; } }
return result; } public Sentence mergeCompoundWords() { ListIterator<IWord> listIterator = wordList.listIterator(); while (listIterator.hasNext()) { IWord word = listIterator.next(); if (word instanceof CompoundWord) { listIterator.set(new Word(word.getValue(), word.getLabel())); } } return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sentence sentence = (Sentence) o; return toString().equals(sentence.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\Sentence.java
1
请在Spring Boot框架中完成以下Java代码
public String metricKeyPrefix() { return obtain(v2(V2::getMetricKeyPrefix), DynatraceConfig.super::metricKeyPrefix); } @Override public Map<String, String> defaultDimensions() { return obtain(v2(V2::getDefaultDimensions), DynatraceConfig.super::defaultDimensions); } @Override public boolean enrichWithDynatraceMetadata() { return obtain(v2(V2::isEnrichWithDynatraceMetadata), DynatraceConfig.super::enrichWithDynatraceMetadata); } @Override public boolean useDynatraceSummaryInstruments() {
return obtain(v2(V2::isUseDynatraceSummaryInstruments), DynatraceConfig.super::useDynatraceSummaryInstruments); } @Override public boolean exportMeterMetadata() { return obtain(v2(V2::isExportMeterMetadata), DynatraceConfig.super::exportMeterMetadata); } private <V> Getter<DynatraceProperties, V> v1(Getter<V1, V> getter) { return (properties) -> getter.get(properties.getV1()); } private <V> Getter<DynatraceProperties, V> v2(Getter<V2, V> getter) { return (properties) -> getter.get(properties.getV2()); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatracePropertiesConfigAdapter.java
2
请完成以下Java代码
public static <IT, OT> Iterator<OT> map(@NonNull final Iterator<IT> iterator, @NonNull final Function<IT, OT> mapper) { return new MappingIteratorWrapper<>(iterator, mapper); } public static <T> Iterator<T> unmodifiableIterator(final Iterator<T> iterator) { return new UnmodifiableIterator<>(iterator); } public static <T> Iterator<T> emptyIterator() { return EmptyIterator.getInstance(); } /** * @param iterator * @return the iterator wrapped to stream */ public static <T> Stream<T> stream(final Iterator<T> iterator) {
Spliterator<T> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED); final boolean parallel = false; return StreamSupport.stream(spliterator, parallel); } public static <T> Stream<T> stream(final BlindIterator<T> blindIterator) { return stream(asIterator(blindIterator)); } public static <T> PagedIteratorBuilder<T> newPagedIterator() { return PagedIterator.builder(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IteratorUtils.java
1
请完成以下Java代码
public final void removeAncestorKeyBindingsOf(final JComponent comp, final Predicate<KeyStroke> isRemoveKeyStrokePredicate) { // Skip null components (but tolerate that) if (comp == null) { return; } // Get component's ancestors input map (the map which defines which key bindings will work when pressed in a component which is included inside this component). final InputMap compInputMap = comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); // NOTE: don't check and exit if "compInputMap.size() <= 0" because it might be that this map is empty but the key bindings are defined in it's parent map. // Iterate all key bindings for our panel and remove those which are also present in component's ancestor map. final InputMap thisInputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); for (final KeyStroke key : thisInputMap.allKeys()) { // Check if the component has a key binding defined for our panel key binding. final Object compAction = compInputMap.get(key); if (compAction == null) { continue; } if (isRemoveKeyStrokePredicate != null && !isRemoveKeyStrokePredicate.apply(key)) {
continue; } // NOTE: Instead of removing it, it is much more safe to bind it to "none", // to explicitly say to not consume that key event even if is defined in some parent map of this input map. compInputMap.put(key, "none"); if (log.isDebugEnabled()) { log.debug("Removed " + key + "->" + compAction + " which in this component is binded to " + thisInputMap.get(key) + "\n\tThis panel: " + this + "\n\tComponent: " + comp); } } } } // APanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\APanel.java
1
请完成以下Java代码
public static PickedHUEditorRow ofUnprocessedRow( @NonNull final HUEditorRow huEditorRow, @NonNull final ImmutableMap<HuId, ImmutableSet<OrderId>> huIds2OpenPickingOrderIds) { return new PickedHUEditorRow(huEditorRow, false, huIds2OpenPickingOrderIds); } @NonNull HUEditorRow huEditorRow; boolean processed; @NonNull ImmutableMap<HuId, ImmutableSet<OrderId>> huIds2OpenPickingOrderIds; @NonNull public HuId getHUId() { return huEditorRow.getHuId(); }
@NonNull public ImmutableMap<HuId, ImmutableSet<OrderId>> getPickingOrderIdsFor(@NonNull final ImmutableSet<HuId> huIds) { return huIds.stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), huId -> Optional.ofNullable(huIds2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()))); } public boolean containsHUId(@NonNull final HuId packToHUId) { return huEditorRow.getAllHuIds().contains(packToHUId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickedHUEditorRow.java
1
请在Spring Boot框架中完成以下Java代码
protected Pair<Boolean, Boolean> saveOrUpdateCalculatedField(TenantId tenantId, CalculatedFieldId calculatedFieldId, CalculatedFieldUpdateMsg calculatedFieldUpdateMsg) { boolean isCreated = false; boolean isNameUpdated = false; try { CalculatedField calculatedField = JacksonUtil.fromString(calculatedFieldUpdateMsg.getEntity(), CalculatedField.class, true); if (calculatedField == null) { throw new RuntimeException("[{" + tenantId + "}] calculatedFieldUpdateMsg {" + calculatedFieldUpdateMsg + " } cannot be converted to calculatedField"); } CalculatedField calculatedFieldById = edgeCtx.getCalculatedFieldService().findById(tenantId, calculatedFieldId); if (calculatedFieldById == null) { calculatedField.setCreatedTime(Uuids.unixTimestamp(calculatedFieldId.getId())); isCreated = true; calculatedField.setId(null); } else { calculatedField.setId(calculatedFieldId); } String calculatedFieldName = calculatedField.getName(); CalculatedField calculatedFieldByName = edgeCtx.getCalculatedFieldService().findByEntityIdAndTypeAndName(calculatedField.getEntityId(), calculatedField.getType(), calculatedFieldName); if (calculatedFieldByName != null && !calculatedFieldByName.getId().equals(calculatedFieldId)) { calculatedFieldName = calculatedFieldName + "_" + StringUtils.randomAlphabetic(15); log.warn("[{}] calculatedField with name {} already exists. Renaming calculatedField name to {}", tenantId, calculatedField.getName(), calculatedFieldByName.getName()); isNameUpdated = true; } calculatedField.setName(calculatedFieldName);
calculatedFieldValidator.validate(calculatedField, CalculatedField::getTenantId); if (isCreated) { calculatedField.setId(calculatedFieldId); } edgeCtx.getCalculatedFieldService().save(calculatedField, false); } catch (Exception e) { log.error("[{}] Failed to process calculatedField update msg [{}]", tenantId, calculatedFieldUpdateMsg, e); throw e; } return Pair.of(isCreated, isNameUpdated); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\cf\BaseCalculatedFieldProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice() { ExpressionBasedPreInvocationAdvice preInvocationAdvice = new ExpressionBasedPreInvocationAdvice(); preInvocationAdvice.setExpressionHandler(getExpressionHandler()); return preInvocationAdvice; } /** * Obtains the attributes from {@link EnableGlobalMethodSecurity} if this class was * imported using the {@link EnableGlobalMethodSecurity} annotation. */ @Override public final void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> annotationAttributes = importMetadata .getAnnotationAttributes(EnableGlobalMethodSecurity.class.getName()); this.enableMethodSecurity = AnnotationAttributes.fromMap(annotationAttributes); } @Autowired(required = false) public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) { this.objectPostProcessor = objectPostProcessor; } @Autowired(required = false) public void setMethodSecurityExpressionHandler(List<MethodSecurityExpressionHandler> handlers) { if (handlers.size() != 1) { logger.debug("Not autowiring MethodSecurityExpressionHandler since size != 1. Got " + handlers); return; } this.expressionHandler = handlers.get(0); } @Autowired(required = false) void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; }
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.context = beanFactory; } private AuthenticationConfiguration getAuthenticationConfiguration() { return this.context.getBean(AuthenticationConfiguration.class); } private boolean prePostEnabled() { return enableMethodSecurity().getBoolean("prePostEnabled"); } private boolean securedEnabled() { return enableMethodSecurity().getBoolean("securedEnabled"); } private boolean jsr250Enabled() { return enableMethodSecurity().getBoolean("jsr250Enabled"); } private boolean isAspectJ() { return enableMethodSecurity().getEnum("mode") == AdviceMode.ASPECTJ; } private AnnotationAttributes enableMethodSecurity() { if (this.enableMethodSecurity == null) { // if it is null look at this instance (i.e. a subclass was used) EnableGlobalMethodSecurity methodSecurityAnnotation = AnnotationUtils.findAnnotation(getClass(), EnableGlobalMethodSecurity.class); Assert.notNull(methodSecurityAnnotation, () -> EnableGlobalMethodSecurity.class.getName() + " is required"); Map<String, Object> methodSecurityAttrs = AnnotationUtils.getAnnotationAttributes(methodSecurityAnnotation); this.enableMethodSecurity = AnnotationAttributes.fromMap(methodSecurityAttrs); } return this.enableMethodSecurity; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\GlobalMethodSecurityConfiguration.java
2
请完成以下Java代码
public static List<Integer> findByTreeMap(Integer[] arr, int n) { // Create a TreeMap and use a reverse order comparator to sort the entries by frequency in descending order Map<Integer, Integer> countMap = new TreeMap<>(Collections.reverseOrder()); for (int i : arr) { countMap.put(i, countMap.getOrDefault(i, 0) + 1); } // Create a list of the map entries and sort them by value (i.e. by frequency) in descending order List<Map.Entry<Integer, Integer>> sortedEntries = new ArrayList<>(countMap.entrySet()); sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue())); // Extract the n most frequent elements from the sorted list of entries List<Integer> result = new ArrayList<>(); for (int i = 0; i < n && i < sortedEntries.size(); i++) { result.add(sortedEntries.get(i).getKey()); } return result; } public static List<Integer> findByBucketSort(Integer[] arr, int n) { List<Integer> result = new ArrayList<>(); Map<Integer, Integer> freqMap = new HashMap<>(); List<Integer>[] bucket = new List[arr.length + 1]; // Loop through the input array and update the frequency count of each element in the HashMap for (int num : arr) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } // Loop through the HashMap and add each element to its corresponding bucket based on its frequency count for (int num : freqMap.keySet()) { int freq = freqMap.get(num); if (bucket[freq] == null) { bucket[freq] = new ArrayList<>(); } bucket[freq].add(num); } // Loop through the bucket array in reverse order and add the elements to the result list // until we have found the n most frequent elements for (int i = bucket.length - 1; i >= 0 && result.size() < n; i--) { if (bucket[i] != null) { result.addAll(bucket[i]); } } // Return a sublist of the result list containing only the first n elements return result.subList(0, n); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\frequentelements\MostFrequentElementsFinder.java
1
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder(word.length * 50); for (CoNLLWord word : this.word) { sb.append(word); sb.append('\n'); } return sb.toString(); } /** * 获取边的列表,edge[i][j]表示id为i的词语与j存在一条依存关系为该值的边,否则为null * @return */ public String[][] getEdgeArray() { String[][] edge = new String[word.length + 1][word.length + 1]; for (CoNLLWord coNLLWord : word) { edge[coNLLWord.ID][coNLLWord.HEAD.ID] = coNLLWord.DEPREL; } return edge; } /** * 获取包含根节点在内的单词数组 * @return */ public CoNLLWord[] getWordArrayWithRoot() { CoNLLWord[] wordArray = new CoNLLWord[word.length + 1]; wordArray[0] = CoNLLWord.ROOT; System.arraycopy(word, 0, wordArray, 1, word.length); return wordArray; } public CoNLLWord[] getWordArray() { return word; } @Override public Iterator<CoNLLWord> iterator() { return new Iterator<CoNLLWord>() { int index; @Override public boolean hasNext() { return index < word.length; } @Override public CoNLLWord next() { return word[index++]; } @Override public void remove() { throw new UnsupportedOperationException("CoNLLSentence是只读对象,不允许删除"); } }; } /** * 找出所有子节点
* @param word * @return */ public List<CoNLLWord> findChildren(CoNLLWord word) { List<CoNLLWord> result = new LinkedList<CoNLLWord>(); for (CoNLLWord other : this) { if (other.HEAD == word) result.add(other); } return result; } /** * 找出特定依存关系的子节点 * @param word * @param relation * @return */ public List<CoNLLWord> findChildren(CoNLLWord word, String relation) { List<CoNLLWord> result = new LinkedList<CoNLLWord>(); for (CoNLLWord other : this) { if (other.HEAD == word && other.DEPREL.equals(relation)) result.add(other); } return result; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\CoNLLSentence.java
1
请完成以下Java代码
public class Person { private String name; private String nickname; private int age; public Person() { } public Person(String name, String nickname, int age) { super(); this.name = name; this.nickname = nickname; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Person.java
1
请在Spring Boot框架中完成以下Java代码
GeodeGatewaySendersHealthIndicator gatewaySendersHealthIndicator(GemFireCache gemfireCache) { return new GeodeGatewaySendersHealthIndicator(gemfireCache); } @Bean BeanPostProcessor cacheServerLoadProbeWrappingBeanPostProcessor() { return new BeanPostProcessor() { @Nullable @Override @SuppressWarnings("all") public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServerFactoryBean) { CacheServerFactoryBean cacheServerFactoryBean = (CacheServerFactoryBean) bean; ServerLoadProbe serverLoadProbe = ObjectUtils.<ServerLoadProbe>get(bean, "serverLoadProbe"); if (serverLoadProbe != null) { cacheServerFactoryBean.setServerLoadProbe(wrap(serverLoadProbe)); } } return bean; } @Nullable @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServer) { CacheServer cacheServer = (CacheServer) bean; Optional.ofNullable(cacheServer.getLoadProbe()) .filter(it -> !(it instanceof ActuatorServerLoadProbeWrapper)) .filter(it -> cacheServer.getLoadPollInterval() > 0) .filter(it -> !cacheServer.isRunning()) .ifPresent(serverLoadProbe -> cacheServer.setLoadProbe(new ActuatorServerLoadProbeWrapper(serverLoadProbe)));
} return bean; } private ServerLoadProbe wrap(ServerLoadProbe serverLoadProbe) { return new ActuatorServerLoadProbeWrapper(serverLoadProbe); } }; } public static final class PeerCacheCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Cache peerCache = CacheUtils.getCache(); ClientCache clientCache = CacheUtils.getClientCache(); return peerCache != null || clientCache == null; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator-autoconfigure\src\main\java\org\springframework\geode\boot\actuate\autoconfigure\config\PeerCacheHealthIndicatorConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public Mono<Integer> add(@RequestBody Publisher<UserAddDTO> addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return Mono.just(returnId); } /** * 添加用户 * * @param addDTO 添加用户信息 DTO * @return 添加成功的用户编号 */ @PostMapping("add2") public Mono<Integer> add2(Mono<UserAddDTO> addDTO) { // 插入用户记录,返回编号 Integer returnId = 1; // 返回用户编号 return Mono.just(returnId); } /** * 更新指定用户编号的用户 * * @param updateDTO 更新用户信息 DTO * @return 是否修改成功 */ @PostMapping("/update") public Mono<Boolean> update(@RequestBody Publisher<UserUpdateDTO> updateDTO) { // 更新用户记录 Boolean success = true; // 返回更新是否成功 return Mono.just(success); }
/** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE public Mono<Boolean> delete(@RequestParam("id") Integer id) { // 删除用户记录 Boolean success = true; // 返回是否更新成功 return Mono.just(success); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public class Comment extends BaseAuditingEntity implements Serializable { @Serial private static final long serialVersionUID = -420530763778423311L; private String content; @Enumerated(EnumType.STRING) private CommentStatus status = CommentStatus.AWAITING_APPROVAL; @JoinColumn(nullable = false) private Long articleId; @JoinColumn(nullable = true) private Long parentCommentId; public Comment() { } public Comment(String content, Long articleId) { this.content = content; this.articleId = articleId; } public Comment(String content, Long parentCommentId, Long articleId) { this.content = content; this.articleId = articleId;
this.parentCommentId = parentCommentId; } public void addChildComment(Comment childComment) { childComment.setParentCommentId(getId()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Comment comment = (Comment) o; return Objects.equals(id, comment.id) && Objects.equals(articleId, comment.articleId); } @Override public int hashCode() { return Objects.hash(id, articleId); } }
repos\spring-boot-web-application-sample-master\main-app\main-orm\src\main\java\gt\app\domain\Comment.java
2
请完成以下Java代码
public class UniqueDigitCounter { static int bruteForce(int n) { int count = 0; int limit = (int)Math.pow(10, n); for (int num = 0; num < limit; num++) { if (hasUniqueDigits(num)) { count++; } } return count; } static boolean hasUniqueDigits(int num) { String str = Integer.toString(num); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) { return false; } } } return true; } static int combinatorial(int n) { if (n == 0) return 1; int result = 10;
int current = 9; int available = 9; for (int i = 2; i <= n; i++) { current *= available; result += current; available--; } return result; } static int dp(int n) { if (n == 0) return 1; int result = 10; int current = 9; int available = 9; for (int i = 2; i <= n; i++) { current *= available; result += current; available--; } return result; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\uniquedigitcounter\UniqueDigitCounter.java
1
请完成以下Java代码
public OrgId getOrgId() {return getEventDescriptor().getOrgId();} @NonNull @JsonIgnore public SupplyRequiredDescriptor withNewEventId() { return toBuilder().eventDescriptor(newEventDescriptor()).build(); } @NonNull @JsonIgnore public EventDescriptor newEventDescriptor() {return getEventDescriptor().withNewEventId();} @NonNull @JsonIgnore public Instant getDemandDate() {return getMaterialDescriptor().getDate();} @JsonIgnore public int getProductId() {return getMaterialDescriptor().getProductId();} @JsonIgnore public BigDecimal getQtyToSupplyBD() {return getMaterialDescriptor().getQuantity();} @Nullable @JsonIgnore
public BPartnerId getCustomerId() {return getMaterialDescriptor().getCustomerId();} @JsonIgnore public WarehouseId getWarehouseId() {return getMaterialDescriptor().getWarehouseId();} @JsonIgnore public int getAttributeSetInstanceId() {return getMaterialDescriptor().getAttributeSetInstanceId();} @JsonIgnore public AttributesKey getStorageAttributesKey() {return getMaterialDescriptor().getStorageAttributesKey();} @Nullable public PPOrderCandidateId getPpOrderCandidateId() { final PPOrderRef ppOrderRef = getPpOrderRef(); return ppOrderRef == null ? null : ppOrderRef.getPpOrderCandidateId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\SupplyRequiredDescriptor.java
1
请完成以下Spring Boot application配置
spring: ssl: bundle: pem: default: keystore: certificate: "classpath:default/test-hello-server.crt" private-key: "classpath:default/test-hello-server.key" truststore: certificate: "classpath:ca/test-ca.crt" alt: keystore: certificate: "classpath:alt/test-hello-alt-server.crt" private-key: "classpath:alt/test-hello-alt-server.key" truststore: certificate: "classpath:ca/test-ca.crt" server: port: 8443 ssl: bundle: "default" server-name-bundles: - server-name: "hello.example.com" bundle: "default" - server-name: "hello-alt.example.com" bundle: "a
lt" management: server: port: 8444 ssl: bundle: "default" server-name-bundles: - server-name: "hello.example.com" bundle: "default" - server-name: "hello-alt.example.com" bundle: "alt" endpoints: web: exposure: include: - "*"
repos\spring-boot-4.0.1\integration-test\spring-boot-sni-integration-tests\spring-boot-sni-reactive-app\src\main\resources\application.yml
2
请完成以下Java代码
private PlainHUPackingAware createQuickInputPackingAware(@NonNull final OrderLineCandidate candidate) { final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setBpartnerId(candidate.getBpartnerId()); huPackingAware.setInDispute(false); huPackingAware.setProductId(candidate.getProductId()); huPackingAware.setUomId(candidate.getQty().getUomId()); huPackingAware.setAsiId(createASI(candidate.getProductId(), candidate.getAttributes())); huPackingAware.setPiItemProductId(candidate.getPiItemProductId()); huPackingAware.setLuId(candidate.getLuId()); huPackingAware.setQtyLU(Quantitys.toBigDecimalOrNull(candidate.getLuQty())); // huPackingAwareBL.computeAndSetQtysForNewHuPackingAware(huPackingAware, candidate.getQty().toBigDecimal()); // // Validate: if (huPackingAware.getQty() == null || huPackingAware.getQty().signum() <= 0) { logger.warn("Invalid Qty={} for {}", huPackingAware.getQty(), huPackingAware); throw new AdempiereException("Qty shall be greather than zero"); // TODO trl } if (huPackingAware.getQtyTU() == null || huPackingAware.getQtyTU().signum() <= 0) { logger.warn("Invalid QtyTU={} for {}", huPackingAware.getQtyTU(), huPackingAware); throw new AdempiereException("QtyTU shall be greather than zero"); // TODO trl } return huPackingAware;
} @Nullable private AttributeSetInstanceId createASI( @NonNull final ProductId productId, @NonNull final ImmutableAttributeSet attributes) { if (attributes.isEmpty()) { return null; } final I_M_AttributeSetInstance asi = asiBL.createASIWithASFromProductAndInsertAttributeSet( productId, attributes); return AttributeSetInstanceId.ofRepoId(asi.getM_AttributeSetInstance_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\orderline\OrderLineQuickInputProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } /** * The actual attachment data as base64-encoded String. * * @return * possible object is * byte[]
*/ public byte[] getAttachmentData() { return attachmentData; } /** * Sets the value of the attachmentData property. * * @param value * allowed object is * byte[] */ public void setAttachmentData(byte[] value) { this.attachmentData = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\AttachmentType.java
2
请完成以下Java代码
private void enqueuePrintQueues(@NonNull final PrintingQueueQueryRequest queryRequest) { final List<I_C_Printing_Queue> printingQueues = queryRequest.getQuery().list(); if (printingQueues.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("*** There is nothing to enqueue. Skipping it: {}", queryRequest); return; } final Properties ctx = Env.getCtx(); final I_C_Async_Batch parentAsyncBatchRecord = asyncBatchBL.getAsyncBatchById(printingQueueItemsGeneratedAsyncBatchId); final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch() .setContext(ctx) .setC_Async_Batch_Type(C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting) .setName(C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting) .setDescription(queryRequest.getQueryName()) .setParentAsyncBatchId(printingQueueItemsGeneratedAsyncBatchId) .setOrgId(OrgId.ofRepoId(parentAsyncBatchRecord.getAD_Org_ID())) .buildAndEnqueue(); workPackageQueueFactory .getQueueForEnqueuing(ctx, PrintingQueuePDFConcatenateWorkpackageProcessor.class) .newWorkPackage() .setAsyncBatchId(asyncBatchId) .addElements(printingQueues) .buildAndEnqueue(); } private List<PrintingQueueQueryRequest> getPrintingQueueQueryBuilders() { final Map<String, String> filtersMap = sysConfigBL.getValuesForPrefix(QUERY_PREFIX, clientAndOrgId); final Collection<String> keys = filtersMap.keySet(); final ArrayList<PrintingQueueQueryRequest> queries = new ArrayList<>(); for (final String key : keys) { final String whereClause = filtersMap.get(key);
final IQuery<I_C_Printing_Queue> query = createPrintingQueueQuery(whereClause); final PrintingQueueQueryRequest request = PrintingQueueQueryRequest.builder() .queryName(key) .query(query) .build(); queries.add(request); } return queries; } private IQuery<I_C_Printing_Queue> createPrintingQueueQuery(@NonNull final String whereClause) { return queryBL .createQueryBuilder(I_C_Printing_Queue.class) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId()) .addEqualsFilter(I_C_Printing_Queue.COLUMN_C_Async_Batch_ID, printingQueueItemsGeneratedAsyncBatchId) .addEqualsFilter(I_C_Printing_Queue.COLUMNNAME_Processed, false) .filter(TypedSqlQueryFilter.of(whereClause)) .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\ConcatenatePDFsCommand.java
1
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder("MMShipperTransportation["); sb.append(get_ID()).append("-").append(getSummary()) .append("]"); return sb.toString(); } // toString /** * Package Lines */ private List<I_M_ShippingPackage> m_lines = null; /** * Get Lines * * @param requery requery * @return array of lines */ private List<I_M_ShippingPackage> getLines(boolean requery) { final String trxName = get_TrxName(); if (m_lines != null && !requery) { m_lines.forEach(line -> InterfaceWrapperHelper.setTrxName(line, trxName));
return m_lines; } final String whereClause = I_M_ShippingPackage.COLUMNNAME_M_ShipperTransportation_ID + "=?"; m_lines = new Query(getCtx(), I_M_ShippingPackage.Table_Name, whereClause, trxName) .setParameters(new Object[] { getM_ShipperTransportation_ID() }) .listImmutable(I_M_ShippingPackage.class); return m_lines; } /** * Before Delete * * @return true of it can be deleted */ @Override protected boolean beforeDelete() { if (isProcessed()) return false; getLines(false).forEach(InterfaceWrapperHelper::delete); return true; } // beforeDelete } // MMShipperTransportation
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\MMShipperTransportation.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { resultField.setText(processStatements (sqlField.getText(), false)); } // actionedPerformed /** * Process SQL Statements * @param sqlStatements one or more statements separated by ; * @param allowDML allow DML statements * @return result */ public static String processStatements (String sqlStatements, boolean allowDML) { if (sqlStatements == null || sqlStatements.length() == 0) return ""; StringBuffer result = new StringBuffer(); // StringTokenizer st = new StringTokenizer(sqlStatements, ";", false); while (st.hasMoreTokens()) { result.append(processStatement(st.nextToken(), allowDML)); result.append(Env.NL); } // return result.toString(); } // processStatements /** * Process SQL Statements * @param sqlStatement one statement * @param allowDML allow DML statements * @return result */ public static String processStatement (String sqlStatement, boolean allowDML) { if (sqlStatement == null) return ""; StringBuffer sb = new StringBuffer(); char[] chars = sqlStatement.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isWhitespace(c)) sb.append(' '); else sb.append(c); } String sql = sb.toString().trim(); if (sql.length() == 0) return ""; // StringBuffer result = new StringBuffer("SQL> ") .append(sql) .append(Env.NL); if (!allowDML) { boolean error = false; String SQL = sql.toUpperCase(); for (int i = 0; i < DML_KEYWORDS.length; i++) { if (SQL.startsWith(DML_KEYWORDS[i] + " ") || SQL.indexOf(" " + DML_KEYWORDS[i] + " ") != -1 || SQL.indexOf("(" + DML_KEYWORDS[i] + " ") != -1) { result.append("===> ERROR: Not Allowed Keyword ") .append(DML_KEYWORDS[i]) .append(Env.NL); error = true; } } if (error) return result.toString(); } // !allowDML // Process Connection conn = DB.createConnection(true, Connection.TRANSACTION_READ_COMMITTED); Statement stmt = null; try { stmt = conn.createStatement(); boolean OK = stmt.execute(sql); int count = stmt.getUpdateCount();
if (count == -1) { result.append("---> ResultSet"); } else result.append("---> Result=").append(count); } catch (SQLException e) { log.error("process statement: " + sql + " - " + e.toString()); result.append("===> ").append(e.toString()); } // Clean up try { stmt.close(); } catch (SQLException e1) { log.error("processStatement - close statement", e1); } stmt = null; try { conn.close(); } catch (SQLException e2) { log.error("processStatement - close connection", e2); } conn = null; // result.append(Env.NL); return result.toString(); } // processStatement } // VSQLProcess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VSQLProcess.java
1
请完成以下Java代码
public List<DefaultMetadataElement> getConfigurationFileFormats() { return this.configurationFileFormats; } public List<DefaultMetadataElement> getBootVersions() { return this.bootVersions; } public SimpleElement getGroupId() { return this.groupId; } public SimpleElement getArtifactId() { return this.artifactId; } public SimpleElement getVersion() { return this.version; } public SimpleElement getName() { return this.name; } public SimpleElement getDescription() { return this.description; } public SimpleElement getPackageName() { return this.packageName; } /** * A simple element from the properties. */ public static final class SimpleElement { /** * Element title. */ private String title; /** * Element description. */ private String description; /** * Element default value. */ private String value; /** * Create a new instance with the given value. * @param value the value */ public SimpleElement(String value) { this.value = value; } public String getTitle() { return this.title; } public void setTitle(String title) {
this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public void apply(TextCapability capability) { if (StringUtils.hasText(this.title)) { capability.setTitle(this.title); } if (StringUtils.hasText(this.description)) { capability.setDescription(this.description); } if (StringUtils.hasText(this.value)) { capability.setContent(this.value); } } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\InitializrProperties.java
1
请完成以下Java代码
public void addAndSaveLocation(final I_C_BPartner_Location bpartnerLocation) { bpartnersRepo.save(bpartnerLocation); final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerLocation.getC_BPartner_ID(), bpartnerLocation.getC_BPartner_Location_ID()); if (!getBPLocationById(bpartnerLocationId).isPresent()) { getOrLoadBPLocations().add(bpartnerLocation); } } public Optional<I_AD_User> getContactById(final BPartnerContactId contactId) { return getOrLoadContacts() .stream() .filter(contact -> contact.getAD_User_ID() == contactId.getRepoId()) .findFirst(); } private ArrayList<I_AD_User> getOrLoadContacts() { if (contacts == null) { if (record.getC_BPartner_ID() > 0) { contacts = new ArrayList<>(bpartnersRepo.retrieveContacts(record)); } else {
contacts = new ArrayList<>(); } } return contacts; } public BPartnerContactId addAndSaveContact(final I_AD_User contact) { bpartnersRepo.save(contact); final BPartnerContactId contactId = BPartnerContactId.ofRepoId(contact.getC_BPartner_ID(), contact.getAD_User_ID()); if (!getContactById(contactId).isPresent()) { getOrLoadContacts().add(contact); } return contactId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnersCache.java
1
请完成以下Java代码
protected String doIt() throws Exception { if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } final I_M_HU fromHU = getSingleSelectedPickingSlotTopLevelHU(); final IAllocationSource source = HUListAllocationSourceDestination .of(fromHU) .setDestroyEmptyHUs(true); final IHUProducerAllocationDestination destination = createHUProducer(fromHU); HULoader.of(source, destination) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .load(prepareUnloadRequest(fromHU, qtyCUsPerTU).setForceQtyAllocation(true).create()); // If the source HU was destroyed, then "remove" it from picking slots if (handlingUnitsBL.isDestroyedRefreshFirst(fromHU)) { pickingCandidateService.inactivateForHUId(HuId.ofRepoId(fromHU.getM_HU_ID())); } return MSG_OK; }
@Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } private IHUProducerAllocationDestination createHUProducer(@NonNull final I_M_HU fromHU) { final PickingSlotRow pickingRow = getRootRowForSelectedPickingSlotRows(); final IHUStorageFactory storageFactory = Services.get(IHandlingUnitsBL.class).getStorageFactory(); final IHUStorage storage = storageFactory.getStorage(fromHU); final ProductId singleProductId = storage.getSingleProductIdOrNull(); final I_C_UOM uom = Services.get(IProductBL.class).getStockUOM(singleProductId); final LUTUProducerDestination lutuProducerDestination = createNewHUProducer(pickingRow, targetHUPI); lutuProducerDestination.addCUPerTU(singleProductId, qtyCUsPerTU, uom); return lutuProducerDestination; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutHUAndAddToNewHU.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getIncludeCaseVariables() { return includeCaseVariables; } public void setIncludeCaseVariables(Boolean includeCaseVariables) { this.includeCaseVariables = includeCaseVariables; } public Collection<String> getIncludeCaseVariablesNames() { return includeCaseVariablesNames; } public void setIncludeCaseVariablesNames(Collection<String> includeCaseVariablesNames) { this.includeCaseVariablesNames = includeCaseVariablesNames; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public String getActivePlanItemDefinitionId() { return activePlanItemDefinitionId; } public void setActivePlanItemDefinitionId(String activePlanItemDefinitionId) { this.activePlanItemDefinitionId = activePlanItemDefinitionId; } public Set<String> getActivePlanItemDefinitionIds() { return activePlanItemDefinitionIds; } public void setActivePlanItemDefinitionIds(Set<String> activePlanItemDefinitionIds) { this.activePlanItemDefinitionIds = activePlanItemDefinitionIds; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; }
public Boolean getWithoutTenantId() { return withoutTenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public String getTenantIdLikeIgnoreCase() { return tenantIdLikeIgnoreCase; } public void setTenantIdLikeIgnoreCase(String tenantIdLikeIgnoreCase) { this.tenantIdLikeIgnoreCase = tenantIdLikeIgnoreCase; } public Set<String> getCaseInstanceCallbackIds() { return caseInstanceCallbackIds; } public void setCaseInstanceCallbackIds(Set<String> caseInstanceCallbackIds) { this.caseInstanceCallbackIds = caseInstanceCallbackIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceQueryRequest.java
2
请完成以下Java代码
public static String decodeBase64String(String str) throws IOException { BASE64Decoder encoder = new BASE64Decoder(); return new String(encoder.decodeBuffer(str)); } private static String encode(String str, String method) { MessageDigest mdInst = null; // 把密文转换成十六进制的字符串形式 // 单线程用StringBuilder,速度快 多线程用stringbuffer,安全 StringBuilder dstr = new StringBuilder(); try { // 获得MD5摘要算法的 MessageDigest对象 mdInst = MessageDigest.getInstance(method); // 使用指定的字节更新摘要 mdInst.update(str.getBytes()); // 获得密文 byte[] md = mdInst.digest(); for (int i = 0; i < md.length; i++) { int tmp = md[i];
if (tmp < 0) { tmp += 256; } if (tmp < 16) { dstr.append("0"); } dstr.append(Integer.toHexString(tmp)); } } catch (NoSuchAlgorithmException e) { LOG.error(e); } return dstr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\EncryptUtil.java
1
请完成以下Java代码
public boolean hasNamespace(WebServerNamespace webServerNamespace) { return this.namespace.equals(webServerNamespace); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AdditionalHealthEndpointPath other = (AdditionalHealthEndpointPath) obj; boolean result = true; result = result && this.namespace.equals(other.namespace); result = result && this.canonicalValue.equals(other.canonicalValue); return result; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.namespace.hashCode(); result = prime * result + this.canonicalValue.hashCode(); return result; } @Override public String toString() { return this.namespace.getValue() + ":" + this.value; } /** * Creates an {@link AdditionalHealthEndpointPath} from the given input. The input * must contain a prefix and value separated by a `:`. The value must be limited to * one path segment. For example, `server:/healthz`. * @param value the value to parse * @return the new instance */ public static AdditionalHealthEndpointPath from(String value) { Assert.hasText(value, "'value' must not be null"); String[] values = value.split(":"); Assert.isTrue(values.length == 2, "'value' must contain a valid namespace and value separated by ':'."); Assert.isTrue(StringUtils.hasText(values[0]), "'value' must contain a valid namespace."); WebServerNamespace namespace = WebServerNamespace.from(values[0]); validateValue(values[1]); return new AdditionalHealthEndpointPath(namespace, values[1]); }
/** * Creates an {@link AdditionalHealthEndpointPath} from the given * {@link WebServerNamespace} and value. * @param webServerNamespace the server namespace * @param value the value * @return the new instance */ public static AdditionalHealthEndpointPath of(WebServerNamespace webServerNamespace, String value) { Assert.notNull(webServerNamespace, "'webServerNamespace' must not be null."); Assert.notNull(value, "'value' must not be null."); validateValue(value); return new AdditionalHealthEndpointPath(webServerNamespace, value); } private static void validateValue(String value) { Assert.isTrue(StringUtils.countOccurrencesOf(value, "/") <= 1 && value.indexOf("/") <= 0, "'value' must contain only one segment."); } }
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\AdditionalHealthEndpointPath.java
1
请完成以下Java代码
public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID()
{ return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); } /** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeType() { return this.scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return this.scopeDefinitionId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public Date getCreateTime() { return createTime; } @Override public void setCreateTime(Date createTime) { this.createTime = createTime; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id); sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) { sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (scopeId != null) { sb.append(", scopeId=").append(scopeId); } if (scopeType != null) { sb.append(", scopeType=").append(scopeType); } if (scopeDefinitionId != null) { sb.append(", scopeDefinitionId=").append(scopeDefinitionId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\HistoricIdentityLinkEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setMHUPackagingCodeText(String value) { this.mhuPackagingCodeText = value; } /** * Gets the value of the ediExpDesadvPackItem property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ediExpDesadvPackItem property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEDIExpDesadvPackItem().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link EDIExpDesadvPackItemType } * * */ public List<EDIExpDesadvPackItemType> getEDIExpDesadvPackItem() { if (ediExpDesadvPackItem == null) { ediExpDesadvPackItem = new ArrayList<EDIExpDesadvPackItemType>(); } return this.ediExpDesadvPackItem; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackType.java
2
请完成以下Java代码
public boolean hasChanges() { if (isNew()) { return true; } final Set<String> changedPropertyNames = valuesOld.keySet(); for (final String propertyName : changedPropertyNames) { if (isValueChanged(propertyName)) { return true; } } return false; } public int getLoadCount() { return loadCount; } public final String getTrxName() { return _trxName; } public final String setTrxName(final String trxName) { final String trxNameOld = _trxName; _trxName = trxName; return trxNameOld; } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { return getWrapper(model).isOldValues(); } public Evaluatee2 asEvaluatee() { return new Evaluatee2() { @Override public String get_ValueAsString(final String variableName) { if (!has_Variable(variableName)) { return ""; } final Object value = POJOWrapper.this.getValuesMap().get(variableName); return value == null ? "" : value.toString();
} @Override public boolean has_Variable(final String variableName) { return POJOWrapper.this.hasColumnName(variableName); } @Override public String get_ValueOldAsString(final String variableName) { throw new UnsupportedOperationException("not implemented"); } }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; } POJOModelInternalAccessor _modelInternalAccessor = null; public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请在Spring Boot框架中完成以下Java代码
public class FlowableConfig { @Bean public void processEngine(DataSourceTransactionManager transactionManager, DataSource dataSource) throws IOException { SpringProcessEngineConfiguration configuration = new SpringProcessEngineConfiguration(); //自动部署已有的流程文件 Resource[] resources = new PathMatchingResourcePatternResolver().getResources( ResourceLoader.CLASSPATH_URL_PREFIX + "processes/*.bpmn"); configuration.setTransactionManager(transactionManager); // 执行工作流对应的数据源 configuration.setDataSource(dataSource); // 是否自动创建流程引擎表 configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); configuration.setDeploymentResources(resources); //configuration.setDbIdentityUsed(false); //configuration.setAsyncExecutorActivate(false); // 流程历史等级 //configuration.setHistoryLevel(HistoryLevel.FULL); // 流程图字体 configuration.setActivityFontName("宋体"); configuration.setAnnotationFontName("宋体"); configuration.setLabelFontName("宋体"); //return configuration; } @Bean public RepositoryService repositoryService(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } @Bean public RuntimeService runtimeService(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } @Bean
public TaskService taskService(ProcessEngine processEngine) { return processEngine.getTaskService(); } @Bean public HistoryService historyService(ProcessEngine processEngine) { return processEngine.getHistoryService(); } @Bean public ManagementService managementService(ProcessEngine processEngine) { return processEngine.getManagementService(); } @Bean public IdentityService identityService(ProcessEngine processEngine) { return processEngine.getIdentityService(); } @Bean public FormService formService(ProcessEngine processEngine) { return processEngine.getFormService(); } }
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\config\FlowableConfig.java
2
请完成以下Java代码
private ViewEvaluationCtx getViewEvaluationCtx() { return viewEvaluationCtxSupplier.get(); } public void updateChangedRows( @NonNull final Set<DocumentId> changedRowIds, @NonNull final AddRemoveChangedRowIdsCollector changesCollector) { if (changedRowIds.isEmpty()) { return; } computeCurrentSelectionsIfPresent(selections -> addRemoveChangedRows(selections, changedRowIds, changesCollector)); } private ViewRowIdsOrderedSelections addRemoveChangedRows( @NonNull final ViewRowIdsOrderedSelections selections, @NonNull final Set<DocumentId> rowIds, @NonNull final AddRemoveChangedRowIdsCollector changesCollector) { final ViewRowIdsOrderedSelection defaultSelectionBeforeFacetsFiltering = viewDataRepository.addRemoveChangedRows( selections.getDefaultSelectionBeforeFacetsFiltering(), filtersExcludingFacets, rowIds, changesCollector); final ViewRowIdsOrderedSelection defaultSelection; if (!facetFilters.isEmpty()) { defaultSelection = viewDataRepository.addRemoveChangedRows( selections.getDefaultSelection(), facetFilters, rowIds, changesCollector); } else { defaultSelection = defaultSelectionBeforeFacetsFiltering; } return selections.withDefaultSelection(defaultSelectionBeforeFacetsFiltering, defaultSelection); } public ViewRowIdsOrderedSelection getOrderedSelection(@Nullable final DocumentQueryOrderByList orderBys) { if(orderBys == null || orderBys.isEmpty()) { return getDefaultSelection(); } return computeCurrentSelections(selections -> computeOrderBySelectionIfAbsent(selections, orderBys)) .getSelection(orderBys); } private ViewRowIdsOrderedSelections computeOrderBySelectionIfAbsent( @NonNull final ViewRowIdsOrderedSelections selections, @Nullable final DocumentQueryOrderByList orderBys) { return selections.withOrderBysSelectionIfAbsent( orderBys, this::createSelectionFromSelection); }
private ViewRowIdsOrderedSelection createSelectionFromSelection( @NonNull final ViewRowIdsOrderedSelection fromSelection, @Nullable final DocumentQueryOrderByList orderBys) { final ViewEvaluationCtx viewEvaluationCtx = getViewEvaluationCtx(); final SqlDocumentFilterConverterContext filterConverterContext = SqlDocumentFilterConverterContext.builder() .userRolePermissionsKey(viewEvaluationCtx.getPermissionsKey()) .build(); return viewDataRepository.createOrderedSelectionFromSelection( viewEvaluationCtx, fromSelection, DocumentFilterList.EMPTY, orderBys, filterConverterContext); } public Set<DocumentId> retainExistingRowIds(@NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } return viewDataRepository.retrieveRowIdsMatchingFilters( viewId, DocumentFilterList.EMPTY, rowIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelectionsHolder.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<ClusterUniversalStatePairVO>> apiGetClusterStateOfApp(@PathVariable String app) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app cannot be null or empty"); } try { return clusterConfigService.getClusterUniversalState(app) .thenApply(Result::ofSuccess) .get(); } catch (ExecutionException ex) { logger.error("Error when fetching cluster state of app: " + app, ex.getCause()); return errorResponse(ex); } catch (Throwable throwable) { logger.error("Error when fetching cluster state of app: " + app, throwable); return Result.ofFail(-1, throwable.getMessage()); } } private boolean isNotSupported(Throwable ex) { return ex instanceof CommandNotFoundException; } private boolean checkIfSupported(String app, String ip, int port) { try { return Optional.ofNullable(appManagement.getDetailApp(app)) .flatMap(e -> e.getMachine(ip, port)) .flatMap(m -> VersionUtils.parseVersion(m.getVersion()) .map(v -> v.greaterOrEqual(version140))) .orElse(true); // If error occurred or cannot retrieve machine info, return true. } catch (Exception ex) { return true; } } private Result<Boolean> checkValidRequest(ClusterModifyRequest request) { if (StringUtil.isEmpty(request.getApp())) { return Result.ofFail(-1, "app cannot be empty"); } if (StringUtil.isEmpty(request.getIp())) { return Result.ofFail(-1, "ip cannot be empty"); }
if (request.getPort() == null || request.getPort() < 0) { return Result.ofFail(-1, "invalid port"); } if (request.getMode() == null || request.getMode() < 0) { return Result.ofFail(-1, "invalid mode"); } if (!checkIfSupported(request.getApp(), request.getIp(), request.getPort())) { return unsupportedVersion(); } return null; } private <R> Result<R> unsupportedVersion() { return Result.ofFail(4041, "Sentinel client not supported for cluster flow control (unsupported version or dependency absent)"); } private static final String KEY_MODE = "mode"; }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\cluster\ClusterConfigController.java
2
请完成以下Java代码
private void updateInOutLine(final org.compiere.model.I_M_InOutLine inOutLine, final I_M_Material_Tracking materialTracking) { createUpdateASIAndLink(inOutLine, materialTracking); addLog(msgBL.parseTranslation(getCtx(), "@Processed@: @M_InOut_ID@ " + inOutLine.getM_InOut().getDocumentNo() + " @Line@ " + inOutLine.getLine())); final List<I_C_Invoice_Candidate> ics = InterfaceWrapperHelper.createList( invoiceCandDAO.retrieveInvoiceCandidatesForInOutLine(inOutLine), I_C_Invoice_Candidate.class); deleteOrUpdate(ics, materialTracking); } private void createUpdateASIAndLink(final Object documentLine, final I_M_Material_Tracking materialTracking) { materialTrackingAttributeBL.createOrUpdateMaterialTrackingASI(documentLine, materialTracking); InterfaceWrapperHelper.save(documentLine); materialTrackingBL.linkModelToMaterialTracking( MTLinkRequest.builder() .model(documentLine) .materialTrackingRecord(materialTracking) // pass the process parameters on. They contain HU specific infos which this class and module doesn't know or care about, but which are required to // happen when this process runs. Search for references to this process class name in the HU module to find out specifics. .params(getParameterAsIParams()) // unlink from another material tracking if necessary .ifModelAlreadyLinked(IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS) .build()); } /** * @return <code>true</code> for orders and order lines with <code>SOTrx=N</code> (i.e. purchase order lines), <code>false</code> otherwise. */
@Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (I_C_Order.Table_Name.equals(context.getTableName())) { final I_C_Order order = context.getSelectedModel(I_C_Order.class); if (order == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no order"); } if (Services.get(IOrderBL.class).isRequisition(order)) { return ProcessPreconditionsResolution.rejectWithInternalReason("Is purchase requisition"); } return ProcessPreconditionsResolution.acceptIf(!order.isSOTrx()); } else if (I_C_OrderLine.Table_Name.equals(context.getTableName())) { final I_C_OrderLine orderLine = context.getSelectedModel(I_C_OrderLine.class); if (orderLine == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("context contains no orderLine"); } return ProcessPreconditionsResolution.acceptIf(!orderLine.getC_Order().isSOTrx()); } return ProcessPreconditionsResolution.reject(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\M_Material_Tracking_CreateOrUpdate_ID.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isAwaitTermination() { return this.awaitTermination; } public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } /** * Determine when the task executor is to be created. *
* @since 3.5.0 */ public enum Mode { /** * Create the task executor if no user-defined executor is present. */ AUTO, /** * Create the task executor even if a user-defined executor is present. */ FORCE } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskExecutionProperties.java
2
请完成以下Java代码
public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the ssn property. * * @return * possible object is * {@link String } * */ public String getSsn() { return ssn; } /** * Sets the value of the ssn property. * * @param value * allowed object is * {@link String } * */ public void setSsn(String value) { this.ssn = value; } /** * Gets the value of the nif property. * * @return
* possible object is * {@link String } * */ public String getNif() { return nif; } /** * Sets the value of the nif property. * * @param value * allowed object is * {@link String } * */ public void setNif(String value) { this.nif = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\IvgLawType.java
1
请完成以下Java代码
public String getToUserName() { return ToUserName; } public void setToUserName(String toUserName) { ToUserName = toUserName; } public String getFromUserName() { return FromUserName; } public void setFromUserName(String fromUserName) { FromUserName = fromUserName; } public long getCreateTime() { return CreateTime; } public void setCreateTime(long createTime) { CreateTime = createTime; } public String getMsgType() { return MsgType;
} public void setMsgType(String msgType) { MsgType = msgType; } public int getFuncFlag() { return FuncFlag; } public void setFuncFlag(int funcFlag) { FuncFlag = funcFlag; } @Override public String toString() { return "BaseMessage{" + "ToUserName='" + ToUserName + '\'' + ", FromUserName='" + FromUserName + '\'' + ", CreateTime=" + CreateTime + ", MsgType='" + MsgType + '\'' + ", FuncFlag=" + FuncFlag + '}'; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\model\BaseMessage.java
1
请在Spring Boot框架中完成以下Java代码
public ReturnT<String> update(HttpServletRequest request, XxlJobUser xxlJobUser) { // avoid opt login seft XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); if (loginUser.getUsername().equals(xxlJobUser.getUsername())) { return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("user_update_loginuser_limit")); } // valid password if (StringUtils.hasText(xxlJobUser.getPassword())) { xxlJobUser.setPassword(xxlJobUser.getPassword().trim()); if (!(xxlJobUser.getPassword().length()>=4 && xxlJobUser.getPassword().length()<=20)) { return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); } // md5 password xxlJobUser.setPassword(DigestUtils.md5DigestAsHex(xxlJobUser.getPassword().getBytes())); } else { xxlJobUser.setPassword(null); } // write xxlJobUserDao.update(xxlJobUser); return ReturnT.SUCCESS; } @RequestMapping("/remove") @ResponseBody @PermissionLimit(adminuser = true) public ReturnT<String> remove(HttpServletRequest request, int id) { // avoid opt login seft XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); if (loginUser.getId() == id) { return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("user_update_loginuser_limit")); } xxlJobUserDao.delete(id);
return ReturnT.SUCCESS; } @RequestMapping("/updatePwd") @ResponseBody public ReturnT<String> updatePwd(HttpServletRequest request, String password){ // valid password if (password==null || password.trim().length()==0){ return new ReturnT<String>(ReturnT.FAIL.getCode(), "密码不可为空"); } password = password.trim(); if (!(password.length()>=4 && password.length()<=20)) { return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("system_lengh_limit")+"[4-20]" ); } // md5 password String md5Password = DigestUtils.md5DigestAsHex(password.getBytes()); // update pwd XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY); // do write XxlJobUser existUser = xxlJobUserDao.loadByUserName(loginUser.getUsername()); existUser.setPassword(md5Password); xxlJobUserDao.update(existUser); return ReturnT.SUCCESS; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\UserController.java
2
请完成以下Java代码
public ProcessExtensionModel read(InputStream inputStream) throws IOException { objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS); ProcessExtensionModel mappedModel = objectMapper.readValue(inputStream, ProcessExtensionModel.class); return convertJsonVariables(mappedModel); } /** * Json variables need to be represented as JsonNode for engine to handle as Json * Do this for any var marked as json or whose type is not recognised from the extension file */ private ProcessExtensionModel convertJsonVariables(ProcessExtensionModel processExtensionModel) { if ( processExtensionModel != null && processExtensionModel.getAllExtensions() != null && processExtensionModel.getAllExtensions().size() > 0 ) { for (Extension extension : processExtensionModel.getAllExtensions().values()) { if (extension.getProperties() != null) { saveVariableAsJsonObject(extension); }
} } return processExtensionModel; } private void saveVariableAsJsonObject(Extension extension) { for (VariableDefinition variableDefinition : extension.getProperties().values()) { if ( !variableTypeMap.containsKey(variableDefinition.getType()) || variableDefinition.getType().equals("json") ) { variableDefinition.setValue(objectMapper.convertValue(variableDefinition.getValue(), JsonNode.class)); } } } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\ProcessExtensionResourceReader.java
1
请完成以下Java代码
public OnMoreThanOneFound getOnMoreThanOneFound() { return onMoreThanOneFound; } @Override public IMaterialTrackingQuery setCompleteFlatrateTerm(final Boolean completeFlatrateTerm) { this.completeFlatrateTerm = completeFlatrateTerm; return this; } @Override public Boolean getCompleteFlatrateTerm() { return completeFlatrateTerm; } @Override public IMaterialTrackingQuery setLot(final String lot) { this.lot = lot; return this; }
@Override public String getLot() { return lot; } @Override public IMaterialTrackingQuery setReturnReadOnlyRecords(boolean returnReadOnlyRecords) { this.returnReadOnlyRecords = returnReadOnlyRecords; return this; } @Override public boolean isReturnReadOnlyRecords() { return returnReadOnlyRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingQuery.java
1
请完成以下Spring Boot application配置
server.port=8080 #spring.activemq.broker-url=tcp://60.205.191.82:8081 #spring.activemq.user=admin #spring.activemq.password=admin #spring.activemq.in-memory=true #spring.activemq.pool.enabled=false activemq.switch=true activemq.url=failover:(tcp://localhost:61616) jsa.activemq.queue.name_1=test_queue_1 jsa.activemq.queue.name_2=test_queue_2 jsa.activemq.queue.name_3=test_queue_3 jsa.activemq.queue.name_4=test_queue_4 jsa.activemq.queue.name_5=test_queue_5 jsa.activemq.queue.names.concurrency=1,2,3,4,5 jsa.activemq.simple.queue.name_1=simpe_queue_1 jsa.a
ctivemq.simple.queue.name_2=simpe_queue_2 jsa.activemq.simple.queue.name_3=simpe_queue_3 jsa.activemq.simple.queue.name_4=simpe_queue_4 jsa.activemq.simple.queue.name_5=simpe_queue_5 jsa.activemq.simple.names.concurrency=1,2,3,4,5 test=today
repos\spring-boot-quick-master\quick-activemq2\src\main\resources\application.properties
2
请完成以下Java代码
public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine); } @Override public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) { if (PP_Product_BOMLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID);
} @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java
1
请完成以下Java代码
public PickingJobStepPickedTo removing(final List<PickingJobStepPickedToHU> toRemove) { if (toRemove.isEmpty()) { return this; } final ImmutableList<PickingJobStepPickedToHU> actualPickedHUsNew = this.actualPickedHUs.stream() .filter(pickedHU -> !toRemove.contains(pickedHU)) .collect(ImmutableList.toImmutableList()); if (actualPickedHUsNew.size() == actualPickedHUs.size()) { return this; } if (actualPickedHUsNew.isEmpty() && this.qtyRejected == null) { return null; } return toBuilder().actualPickedHUs(actualPickedHUsNew).build(); }
@NonNull public List<HuId> getPickedHuIds() { return actualPickedHUs.stream() .map(PickingJobStepPickedToHU::getActualPickedHU) .map(HUInfo::getId) .collect(ImmutableList.toImmutableList()); } @NonNull public Optional<PickingJobStepPickedToHU> getLastPickedHu() { return actualPickedHUs.stream() .max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickedTo.java
1
请在Spring Boot框架中完成以下Java代码
public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public Integer getNumberOfStages() { return numberOfStages; } public void setNumberOfStages(Integer numberOfStages) { this.numberOfStages = numberOfStages; } @Override public String toString() {
return "ScanPayRequestBo{" + "payKey='" + payKey + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", orderPeriod=" + orderPeriod + ", returnUrl='" + returnUrl + '\'' + ", notifyUrl='" + notifyUrl + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + ", numberOfStages=" + numberOfStages + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ScanPayRequestBo.java
2
请完成以下Java代码
protected void onCurrentItemChanged(MTreeNode node) { onTreeNodeSelected(node); } }; treeSearchLabel.setText(msgBL.getMsg(Env.getCtx(), "TreeSearch") + " "); treeSearchLabel.setLabelFor(treeSearch); treeSearchLabel.setToolTipText(msgBL.getMsg(Env.getCtx(), "TreeSearchText")); treeSearch.setBackground(AdempierePLAF.getInfoBackground()); } /** * Executed when a node is selected by the user. * * @param node */ protected void onTreeNodeSelected(final MTreeNode node) { // nothing } /** * Loads the auto-complete suggestions. * * @param root */ public final void setTreeNodesFromRoot(final MTreeNode root)
{ treeSearchAutoCompleter.setTreeNodes(root); } /** @return the search label of {@link #getSearchField()} */ public final CLabel getSearchFieldLabel() { return treeSearchLabel; } /** @return the search field (with auto-complete support) */ public final CTextField getSearchField() { return treeSearch; } public final void requestFocus() { treeSearch.requestFocus(); } public final boolean requestFocusInWindow() { return treeSearch.requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreePanelSearchSupport.java
1
请完成以下Java代码
private final String getQtyCapacityUOMSymbol() { final I_C_UOM uom = IHUPIItemProductBL.extractUOMOrNull(getM_HU_PI_Item_Product()); if (uom == null) { return null; } return uom.getUOMSymbol(); } /** * * @return QtyMoved / QtyPlanned string */ private String getQtysDisplayName() { if (_qtyTUPlanned == null && _qtyTUMoved == null) { return null; } final StringBuilder sb = new StringBuilder(); // // Qty Moved if (_qtyTUMoved != null) { sb.append(toQtyTUString(_qtyTUMoved)); } // // Qty Planned { if (sb.length() > 0) { sb.append(" / "); } sb.append(toQtyTUString(_qtyTUPlanned)); } return sb.toString(); } private final String toQtyTUString(final BigDecimal qtyTU) { if (qtyTU == null) { return "?"; } return qtyTU .setScale(0, RoundingMode.UP) // it's general integer, just making sure we don't end up with 3.0000000 .toString(); } @Override public IHUPIItemProductDisplayNameBuilder setM_HU_PI_Item_Product(final I_M_HU_PI_Item_Product huPIItemProduct) { _huPIItemProduct = huPIItemProduct; return this; } @Override public IHUPIItemProductDisplayNameBuilder setM_HU_PI_Item_Product(@NonNull final HUPIItemProductId id) { final I_M_HU_PI_Item_Product huPIItemProduct = Services.get(IHUPIItemProductDAO.class).getRecordById(id); return setM_HU_PI_Item_Product(huPIItemProduct); } private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product() { Check.assumeNotNull(_huPIItemProduct, "_huPIItemProduct not null"); return _huPIItemProduct; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final BigDecimal qtyTUPlanned) { _qtyTUPlanned = qtyTUPlanned; return this; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final int qtyTUPlanned) { setQtyTUPlanned(BigDecimal.valueOf(qtyTUPlanned));
return this; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final BigDecimal qtyTUMoved) { _qtyTUMoved = qtyTUMoved; return this; } @Override public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final int qtyTUMoved) { setQtyTUMoved(BigDecimal.valueOf(qtyTUMoved)); return this; } @Override public HUPIItemProductDisplayNameBuilder setQtyCapacity(final BigDecimal qtyCapacity) { _qtyCapacity = qtyCapacity; return this; } @Override public IHUPIItemProductDisplayNameBuilder setShowAnyProductIndicator(boolean showAnyProductIndicator) { this._showAnyProductIndicator = showAnyProductIndicator; return this; } private boolean isShowAnyProductIndicator() { return _showAnyProductIndicator; } private boolean isAnyProductAllowed() { return getM_HU_PI_Item_Product().isAllowAnyProduct(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDisplayNameBuilder.java
1
请完成以下Java代码
public static class GitIgnoreSection implements Section { private final String name; private final LinkedList<String> items; public GitIgnoreSection(String name) { this.name = name; this.items = new LinkedList<>(); } public void add(String... items) { this.items.addAll(Arrays.asList(items)); } public LinkedList<String> getItems() { return this.items; }
@Override public void write(PrintWriter writer) { if (!this.items.isEmpty()) { if (this.name != null) { writer.println(); writer.println(String.format("### %s ###", this.name)); } this.items.forEach(writer::println); } } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java
1
请完成以下Java代码
public class C_Workplace_PrintQRCode_ViewSelection extends ViewBasedProcessTemplate implements IProcessPrecondition { private final WorkplaceService workplaceService = SpringContextHolder.instance.getBean(WorkplaceService.class); private final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final Collection<Workplace> workplaces = getWorkplaces(); final ImmutableList<PrintableQRCode> qrCodes = toPrintableQRCodes(workplaces); final QRCodePDFResource pdf = globalQRCodeService.createPDF(qrCodes); getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType());
return MSG_OK; } private Collection<Workplace> getWorkplaces() { final ImmutableSet<WorkplaceId> workplaceIds = streamSelectedRows() .map(row -> row.getId().toId(WorkplaceId::ofRepoId)) .collect(ImmutableSet.toImmutableSet()); return workplaceService.getByIds(workplaceIds); } private static ImmutableList<PrintableQRCode> toPrintableQRCodes(final Collection<Workplace> workplaces) { return workplaces.stream() .map(WorkplaceQRCode::ofWorkplace) .map(WorkplaceQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\workplace\qrcode\process\C_Workplace_PrintQRCode_ViewSelection.java
1
请完成以下Java代码
public class MHRPayroll extends X_HR_Payroll { /** * */ private static final long serialVersionUID = -1407037967021019961L; /** Cache */ private static CCache<Integer, MHRPayroll> s_cache = new CCache<Integer, MHRPayroll>(Table_Name, 10); /** Cache */ private static CCache<String, MHRPayroll> s_cacheValue = new CCache<String, MHRPayroll>(Table_Name+"_Value", 10); /** * Get Payroll by Value * @param ctx * @param value * @return payroll */ public static MHRPayroll forValue(Properties ctx, String value) { if (Check.isEmpty(value, true)) { return null; } int AD_Client_ID = Env.getAD_Client_ID(ctx); final String key = AD_Client_ID+"#"+value; MHRPayroll payroll = s_cacheValue.get(key); if (payroll != null) { return payroll; } final String whereClause = COLUMNNAME_Value+"=? AND AD_Client_ID IN (?,?)"; payroll = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{value, 0, AD_Client_ID}) .setOnlyActiveRecords(true) .setOrderBy("AD_Client_ID DESC") .first(); if (payroll != null) { s_cacheValue.put(key, payroll); s_cache.put(payroll.get_ID(), payroll); } return payroll; } /** * Get Payroll by ID * @param ctx * @param HR_Payroll_ID * @return payroll */ public static MHRPayroll get(Properties ctx, int HR_Payroll_ID) { if (HR_Payroll_ID <= 0) return null; // MHRPayroll payroll = s_cache.get(HR_Payroll_ID); if (payroll != null) return payroll; // payroll = new MHRPayroll(ctx, HR_Payroll_ID, null); if (payroll.get_ID() == HR_Payroll_ID) { s_cache.put(HR_Payroll_ID, payroll); } else
{ payroll = null; } return payroll; } /** * Standard Constructor * @param ctx context * @param HR_Payroll_ID id */ public MHRPayroll (Properties ctx, int HR_Payroll_ID, String trxName) { super (ctx, HR_Payroll_ID, trxName); if (HR_Payroll_ID == 0) { setProcessing (false); // N } } // HRPayroll /** * Load Constructor * @param ctx context * @param rs result set */ public MHRPayroll (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } /** * Parent Constructor * @param parent parent */ public MHRPayroll (MCalendar calendar) { this (calendar.getCtx(), 0, calendar.get_TrxName()); setClientOrg(calendar); //setC_Calendar_ID(calendar.getC_Calendar_ID()); } // HRPayroll } // MPayroll
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRPayroll.java
1
请完成以下Java代码
public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; }
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ManyToOne @JoinColumn(name = "customer_id") private User customer; }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Product.java
1
请完成以下Java代码
public static boolean isPalindromeHalfReversal(int number) { if (number < 0 || (number % 10 == 0 && number != 0)) { return false; } int reversedNumber = 0; while (number > reversedNumber) { reversedNumber = reversedNumber * 10 + number % 10; number /= 10; } return number == reversedNumber || number == reversedNumber / 10; } public static boolean isPalindromeDigitByDigit(int number) { if (number < 0) { return false; }
int divisor = 1; while (number / divisor >= 10) { divisor *= 10; } while (number != 0) { int leading = number / divisor; int trailing = number % 10; if (leading != trailing) { return false; } number = (number % divisor) / 10; divisor /= 100; } return true; } }
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\palindrome\PalindromeNumber.java
1
请在Spring Boot框架中完成以下Java代码
public class OpenTelemetryTracingProperties { /** * Span export configuration. */ private final Export export = new Export(); public Export getExport() { return this.export; } public static class Export { /** * Whether unsampled spans should be exported. */ private boolean includeUnsampled; /** * Maximum time an export will be allowed to run before being cancelled. */ private Duration timeout = Duration.ofSeconds(30); /** * Maximum batch size for each export. This must be less than or equal to * 'maxQueueSize'. */ private int maxBatchSize = 512; /** * Maximum number of spans that are kept in the queue before they will be dropped. */ private int maxQueueSize = 2048; /** * The delay interval between two consecutive exports. */ private Duration scheduleDelay = Duration.ofSeconds(5); public boolean isIncludeUnsampled() { return this.includeUnsampled; } public void setIncludeUnsampled(boolean includeUnsampled) { this.includeUnsampled = includeUnsampled; } public Duration getTimeout() { return this.timeout; } public void setTimeout(Duration timeout) {
this.timeout = timeout; } public int getMaxBatchSize() { return this.maxBatchSize; } public void setMaxBatchSize(int maxBatchSize) { this.maxBatchSize = maxBatchSize; } public int getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(int maxQueueSize) { this.maxQueueSize = maxQueueSize; } public Duration getScheduleDelay() { return this.scheduleDelay; } public void setScheduleDelay(Duration scheduleDelay) { this.scheduleDelay = scheduleDelay; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingProperties.java
2
请在Spring Boot框架中完成以下Java代码
private ClassInfo parseTableStructure(ParamInfo paramInfo) throws Exception { String dataType = MapUtil.getString(paramInfo.getOptions(), "dataType"); ParserTypeEnum parserType = ParserTypeEnum.fromValue(dataType); // 添加调试信息 log.debug("解析数据类型: {}, 解析结果: {}", dataType, parserType); switch (parserType) { case SQL: // 默认模式:parse DDL table structure from sql return sqlParserService.processTableIntoClassInfo(paramInfo); case JSON: // JSON模式:parse field from json string return jsonParserService.processJsonToClassInfo(paramInfo); case INSERT_SQL: // INSERT SQL模式:parse field from insert sql
return sqlParserService.processInsertSqlToClassInfo(paramInfo); case SQL_REGEX: // 正则表达式模式(非完善版本):parse sql by regex return sqlParserService.processTableToClassInfoByRegex(paramInfo); case SELECT_SQL: // SelectSqlBySQLPraser模式:parse select sql by JSqlParser return sqlParserService.generateSelectSqlBySQLPraser(paramInfo); case CREATE_SQL: // CreateSqlBySQLPraser模式:parse create sql by JSqlParser return sqlParserService.generateCreateSqlBySQLPraser(paramInfo); default: // 默认模式:parse DDL table structure from sql return sqlParserService.processTableIntoClassInfo(paramInfo); } } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\service\impl\CodeGenServiceImpl.java
2
请完成以下Java代码
public static MaterialCockpitDetailsRowAggregation getValueOrDefault(@Nullable final String value) { for (final MaterialCockpitDetailsRowAggregation aggregation : MaterialCockpitDetailsRowAggregation.values()) { if (aggregation.name().equalsIgnoreCase(value)) { return aggregation; } } return getDefault(); // default value } public static @NonNull MaterialCockpitDetailsRowAggregation getDefault() { return PLANT; }
public boolean isNone() { return this == NONE; } public boolean isPlant() { return this == PLANT; } public boolean isWarehouse() { return this == WAREHOUSE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitDetailsRowAggregation.java
1
请完成以下Java代码
private DocumentFilterDescriptorsProvider createFiltersProvider( @NonNull final String tableName) { if (!I_C_BPartner.Table_Name.equals(tableName)) { logger.debug("Skip creating Postgres FTS filters because table {} isn't supported", tableName); return NullDocumentFilterDescriptorsProvider.instance; } if (!sysConfigBL.getBooleanValue(SYSCONFIG_ENABLED, false)) { logger.debug("Skip creating Postgres FTS filters because it is disabled by {}", SYSCONFIG_ENABLED); return NullDocumentFilterDescriptorsProvider.instance; }
final ITranslatableString caption = TranslatableStrings.adMessage(MSG_FULL_TEXT_SEARCH_CAPTION); return ImmutableDocumentFilterDescriptorsProvider.of( DocumentFilterDescriptor.builder() .setFilterId(FILTER_ID) .setSortNo(DocumentFilterDescriptorsConstants.SORT_NO_POSTGRES_FULL_TEXT_SEARCH) .setDisplayName(caption) .setFrequentUsed(true) .setInlineRenderMode(DocumentFilterInlineRenderMode.INLINE_PARAMETERS) .addParameter(DocumentFilterParamDescriptor.builder() .fieldName(PARAM_SearchText) .displayName(caption) .widgetType(DocumentFieldWidgetType.Text)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\fullTextSearch\PostgresFTSDocumentFilterDescriptorsProviderFactory.java
1
请完成以下Java代码
public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCondition() { return condition; }
public void setCondition(String condition) { this.condition = condition; } public static QueryRuleEnum getByValue(String value){ if(oConvertUtils.isEmpty(value)) { return null; } for(QueryRuleEnum val :values()){ if (val.getValue().equals(value) || val.getCondition().equalsIgnoreCase(value)){ return val; } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\query\QueryRuleEnum.java
1
请完成以下Java代码
public ValueConversionException setFieldName(@Nullable final String fieldName) { setParameter("fieldName", fieldName); return this; } public ValueConversionException setWidgetType(@Nullable final DocumentFieldWidgetType widgetType) { setParameter("widgetType", widgetType); return this; } public ValueConversionException setFromValue(@Nullable final Object fromValue) { setParameter("value", fromValue); setParameter("valueClass", fromValue != null ? fromValue.getClass() : null); return this;
} public ValueConversionException setTargetType(@Nullable final Class<?> targetType) { setParameter("targetType", targetType); return this; } public ValueConversionException setLookupDataSource(@Nullable final LookupValueByIdSupplier lookupDataSource) { setParameter("lookupDataSource", lookupDataSource); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DataTypes.java
1