instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
Properties gemfireProperties() { Properties gemfireProperties = new Properties(); gemfireProperties.setProperty("name", "SpringDataGemFireApplication"); gemfireProperties.setProperty("mcast-port", "0"); gemfireProperties.setProperty("log-level", "config"); return gemfireProperties; } @Bean @Autowired CacheFactoryBean gemfireCache() { CacheFactoryBean gemfireCache = new CacheFactoryBean(); gemfireCache.setClose(true); gemfireCache.setProperties(gemfireProperties()); return gemfireCache; }
@Bean(name="employee") @Autowired LocalRegionFactoryBean<String, Employee> getEmployee(final GemFireCache cache) { LocalRegionFactoryBean<String, Employee> employeeRegion = new LocalRegionFactoryBean<String, Employee>(); employeeRegion.setCache(cache); employeeRegion.setClose(false); employeeRegion.setName("employee"); employeeRegion.setPersistent(false); employeeRegion.setDataPolicy(DataPolicy.PRELOADED); return employeeRegion; } }
repos\tutorials-master\persistence-modules\spring-data-gemfire\src\main\java\com\baeldung\spring\data\gemfire\function\GemfireConfiguration.java
2
请完成以下Java代码
public static HistoricVariableUpdateDto fromHistoricVariableUpdate(HistoricVariableUpdate historicVariableUpdate) { HistoricVariableUpdateDto dto = new HistoricVariableUpdateDto(); fromHistoricVariableUpdate(dto, historicVariableUpdate); return dto; } protected static void fromHistoricVariableUpdate(HistoricVariableUpdateDto dto, HistoricVariableUpdate historicVariableUpdate) { dto.revision = historicVariableUpdate.getRevision(); dto.variableName = historicVariableUpdate.getVariableName(); dto.variableInstanceId = historicVariableUpdate.getVariableInstanceId(); dto.initial = historicVariableUpdate.isInitial(); if (historicVariableUpdate.getErrorMessage() == null) { try {
VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(historicVariableUpdate.getTypedValue()); dto.value = variableValueDto.getValue(); dto.variableType = variableValueDto.getType(); dto.valueInfo = variableValueDto.getValueInfo(); } catch (RuntimeException e) { dto.errorMessage = e.getMessage(); dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); } } else { dto.errorMessage = historicVariableUpdate.getErrorMessage(); dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableUpdateDto.java
1
请完成以下Java代码
public int getM_Product_ID() { return infoWindow.getRecordId(rowIndexModel); } @Override public void setM_Product_ID(final int productId) { throw new UnsupportedOperationException(); } @Override public int getM_AttributeSetInstance_ID() { final Object asiObj = infoWindow.getValue(rowIndexModel, COLUMNNAME_M_AttributeSetInstance_ID); if (asiObj == null) { return -1; } else if (asiObj instanceof KeyNamePair) { return ((KeyNamePair)asiObj).getKey(); } else if (asiObj instanceof Number) { return ((Number)asiObj).intValue(); } else { throw new AdempiereException("Unsupported value for " + COLUMNNAME_M_AttributeSetInstance_ID + ": " + asiObj); } } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { throw new UnsupportedOperationException(); } @Override public void setQty(final BigDecimal qty) { infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_Qty_CU, rowIndexModel, qty); } @Override public BigDecimal getQty() { final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_Qty_CU); return qty; } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { throw new UnsupportedOperationException(); } @Override public int getM_HU_PI_Item_Product_ID() { final KeyNamePair huPiItemProductKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_M_HU_PI_Item_Product_ID); if (huPiItemProductKNP == null) { return -1; } final int piItemProductId = huPiItemProductKNP.getKey(); if (piItemProductId <= 0) { return -1; } return piItemProductId; } @Override public BigDecimal getQtyTU() { final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_QtyPacks); return qty; } @Override public void setQtyTU(final BigDecimal qtyPacks) { infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_QtyPacks, rowIndexModel, qtyPacks);
} @Override public int getC_UOM_ID() { return Services.get(IProductBL.class).getStockUOMId(getM_Product_ID()).getRepoId(); } @Override public void setC_UOM_ID(final int uomId) { throw new UnsupportedOperationException(); } @Override public void setC_BPartner_ID(final int partnerId) { throw new UnsupportedOperationException(); } @Override public int getC_BPartner_ID() { final KeyNamePair bpartnerKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_C_BPartner_ID); return bpartnerKNP != null ? bpartnerKNP.getKey() : -1; } @Override public boolean isInDispute() { // there is no InDispute flag to be considered return false; } @Override public void setInDispute(final boolean inDispute) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareInfoWindowAdapter.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Knowledge Category. @param K_Category_ID Knowledge Category */ public void setK_Category_ID (int K_Category_ID) { if (K_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Category_ID, Integer.valueOf(K_Category_ID)); } /** Get Knowledge Category. @return Knowledge Category */ public int getK_Category_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_K_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Category.java
1
请完成以下Java代码
public void clear() { performClearOperation(referenceSourceElement); } }; } protected void performClearOperation(ModelElementInstance referenceSourceElement) { setReferenceIdentifier(referenceSourceElement, ""); } @Override protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) { if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) { super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier); } else { referenceSourceAttribute.removeAttribute(referenceSourceElement); } } /** * @param referenceSourceElement * @param o */ protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) { removeReference(referenceSourceElement, (ModelElementInstance) o);
} protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) { String identifier = getReferenceIdentifier(referenceSourceElement); List<String> references = StringUtil.splitListBySeparator(identifier, separator); String targetIdentifier = getTargetElementIdentifier(referenceTargetElement); references.add(targetIdentifier); identifier = StringUtil.joinList(references, separator); setReferenceIdentifier(referenceSourceElement, identifier); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java
1
请完成以下Java代码
protected final String getTableName() { return getProcessInfo().getTableNameOrNull(); } /** * Retrieves the records which where selected and attached to this process execution, i.e. * <ul> * <li>if there is any {@link ProcessInfo#getQueryFilterOrElse(IQueryFilter)} that will be used to fetch the records * <li>else if the single record is set ({@link ProcessInfo}'s AD_Table_ID/Record_ID) that will will be used * <li>else an exception is thrown * </ul> * * @return query builder which will provide selected record(s) */ protected final <ModelType> IQueryBuilder<ModelType> retrieveSelectedRecordsQueryBuilder(final Class<ModelType> modelClass) { final ProcessInfo pi = getProcessInfo(); final String tableName = pi.getTableNameOrNull(); final int singleRecordId = pi.getRecord_ID(); final IContextAware contextProvider = PlainContextAware.newWithThreadInheritedTrx(getCtx()); final IQueryBuilder<ModelType> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(modelClass, tableName, contextProvider); // // Try fetching the selected records from AD_PInstance's WhereClause. final IQueryFilter<ModelType> selectionQueryFilter = pi.getQueryFilterOrElse(null); if (selectionQueryFilter != null) { queryBuilder.filter(selectionQueryFilter) .addOnlyActiveRecordsFilter() .addOnlyContextClient(); } // // Try fetching the single selected record from AD_PInstance's AD_Table_ID/Record_ID. else if (tableName != null && singleRecordId >= 0) { final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName); queryBuilder.addEqualsFilter(keyColumnName, singleRecordId); // .addOnlyActiveRecordsFilter() // NOP, return it as is // .addOnlyContextClient(); // NOP, return it as is } else { throw new AdempiereException("@NoSelection@"); } return queryBuilder; } /** * Exceptions to be thrown if we want to cancel the process run. * <p>
* If this exception is thrown: * <ul> * <li>the process will be terminated right away * <li>transaction (if any) will be rolled back * <li>process summary message will be set from this exception message * <li>process will NOT be flagged as error * </ul> */ public static final class ProcessCanceledException extends AdempiereException { @VisibleForTesting public static final AdMessageKey MSG_Canceled = AdMessageKey.of("Canceled"); public ProcessCanceledException() { super(MSG_Canceled); } } protected final <T> int createSelection(@NonNull final IQueryBuilder<T> queryBuilder, @NonNull final PInstanceId pinstanceId) { return queryBuilder .create() .setRequiredAccess(Access.READ) .createSelection(pinstanceId); } protected final UserId getLoggedUserId() { return Env.getLoggedUserId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\JavaProcess.java
1
请完成以下Java代码
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { // 执行本地事务 System.out.println("TX message listener execute local transaction"); RocketMQLocalTransactionState result; try { // 业务代码( 例如下订单 ) result = RocketMQLocalTransactionState.COMMIT; } catch (Exception e) { System.out.println("execute local transaction error"); result = RocketMQLocalTransactionState.UNKNOWN; } return result; } @Override public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
// 检查本地事务( 例如检查下订单是否成功 ) System.out.println("TX message listener check local transaction"); RocketMQLocalTransactionState result; try { //业务代码( 根据检查结果,决定是COMMIT或ROLLBACK ) result = RocketMQLocalTransactionState.COMMIT; } catch (Exception e) { // 异常就回滚 System.out.println("check local transaction error"); result = RocketMQLocalTransactionState.ROLLBACK; } return result; } }
repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\TxProducerListener.java
1
请在Spring Boot框架中完成以下Java代码
public void logSuccess() { totalMsgCounter.incrementAndGet(); successMsgCounter.incrementAndGet(); } public void logFailed() { totalMsgCounter.incrementAndGet(); failedMsgCounter.incrementAndGet(); } public void logTimeout() { totalMsgCounter.incrementAndGet(); timeoutMsgCounter.incrementAndGet(); } public void logTmpFailed() { totalMsgCounter.incrementAndGet(); tmpFailedMsgCounter.incrementAndGet(); }
public void logTmpTimeout() { totalMsgCounter.incrementAndGet(); tmpTimeoutMsgCounter.incrementAndGet(); } public void printStats() { int total = totalMsgCounter.get(); if (total > 0) { StringBuilder stats = new StringBuilder(); counters.forEach((label, value) -> { stats.append(label).append(" = [").append(value.get()).append("]"); }); log.info("[{}] Stats: {}", tenantId, stats); } } public void reset() { counters.values().forEach(counter -> counter.set(0)); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbTenantRuleEngineStats.java
2
请完成以下Java代码
public Event loadEventForReposting(@NonNull final EventLogId eventLogId) { return loadEventForReposting(eventLogId, ImmutableList.of()); } public Event loadEventForReposting( @NonNull final EventLogId eventLogId, @NonNull final List<String> handlersToIgnore) { final I_AD_EventLog eventLogRecord = loadOutOfTrx(eventLogId, I_AD_EventLog.class); final String eventString = eventLogRecord.getEventData(); final Event eventFromStoredString = JacksonJsonEventSerializer.instance.fromString(eventString); final List<String> processedHandlers = Services.get(IQueryBL.class) .createQueryBuilder(I_AD_EventLog_Entry.class, PlainContextAware.newOutOfTrx()) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_AD_EventLog_ID, eventLogRecord.getAD_EventLog_ID()) .addEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_Processed, true) .addNotEqualsFilter(I_AD_EventLog_Entry.COLUMNNAME_Classname, null) .addNotInArrayFilter(I_AD_EventLog_Entry.COLUMN_Classname, handlersToIgnore) .create() .listDistinct(I_AD_EventLog_Entry.COLUMNNAME_Classname, String.class); return eventFromStoredString.toBuilder() .putPropertyFromObject( EventLogUserService.PROPERTY_PROCESSED_BY_HANDLER_CLASS_NAMES, processedHandlers) .wasLogged() // the event was logged; otherwise we would not be able to load it .build(); } public EventLogId saveEvent( @NonNull final Event event, @NonNull final Topic eventBusTopic) { final String eventString = JacksonJsonEventSerializer.instance.toString(event); final I_AD_EventLog eventLogRecord = newInstanceOutOfTrx(I_AD_EventLog.class); eventLogRecord.setEvent_UUID(event.getUuid().toString()); eventLogRecord.setEventTime(Timestamp.from(event.getWhen()));
eventLogRecord.setEventData(eventString); eventLogRecord.setEventTopicName(eventBusTopic.getName()); eventLogRecord.setEventTypeName(eventBusTopic.getType().toString()); eventLogRecord.setEventName(event.getEventName()); final TableRecordReference sourceRecordReference = event.getSourceRecordReference(); if (sourceRecordReference != null) { eventLogRecord.setAD_Table_ID(sourceRecordReference.getAD_Table_ID()); eventLogRecord.setRecord_ID(sourceRecordReference.getRecord_ID()); } save(eventLogRecord); return EventLogId.ofRepoId(eventLogRecord.getAD_EventLog_ID()); } public void saveEventLogEntries(@NonNull final Collection<EventLogEntry> eventLogEntries) { if (eventLogEntries.isEmpty()) { return; } // Save each entry eventLogsRepository.saveLogs(eventLogEntries); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogService.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Override public String getUserId() { return userId; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public byte[] getData() { return data;
} @Override public void setData(byte[] data) { this.data = data; } @Override public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @Override public String getLockTime() { return lockTime; } @Override public void setLockTime(String lockTime) { this.lockTime = lockTime; } @Override public int getProcessed() { return isProcessed; } @Override public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请完成以下Java代码
static String unicodeValueOfNormalizedString(String input) { return toUnicode(normalize(input)); } private static String normalize(String input) { return input == null ? null : Normalizer.normalize(input, Normalizer.Form.NFKD); } private static String toUnicode(String input) { if (input.length() == 1) { return toUnicode(input.charAt(0)); } else { StringJoiner stringJoiner = new StringJoiner(" "); for (char c : input.toCharArray()) { stringJoiner.add(toUnicode(c)); }
return stringJoiner.toString(); } } private static String toUnicode(char input) { String hex = Integer.toHexString(input); StringBuilder sb = new StringBuilder(hex); while (sb.length() < 4) { sb.insert(0, "0"); } sb.insert(0, "\\u"); return sb.toString(); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-3\src\main\java\com\baeldung\accentsanddiacriticsremoval\StringNormalizer.java
1
请完成以下Java代码
public class WidgetType extends BaseWidgetType { @Schema(description = "Complex JSON object that describes the widget type", accessMode = Schema.AccessMode.READ_ONLY) private JsonNode descriptor; public WidgetType() { super(); } public WidgetType(WidgetTypeId id) { super(id); } public WidgetType(BaseWidgetType baseWidgetType) { super(baseWidgetType); } public WidgetType(WidgetType widgetType) { super(widgetType); this.descriptor = widgetType.getDescriptor(); }
@JsonIgnore public JsonNode getDefaultConfig() { return Optional.ofNullable(descriptor) .map(descriptor -> descriptor.get("defaultConfig")) .filter(JsonNode::isTextual).map(JsonNode::asText) .map(json -> { try { return mapper.readTree(json); } catch (JsonProcessingException e) { return null; } }).orElse(null); } public void setDefaultConfig(JsonNode defaultConfig) { ((ObjectNode) descriptor).put("defaultConfig", defaultConfig.toString()); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\widget\WidgetType.java
1
请完成以下Java代码
public class Query extends TypedSqlQuery<Object> { @SuppressWarnings("deprecation") public Query(Properties ctx, MTable table, String whereClause, String trxName) { super(ctx, Object.class, // modelClass table == null ? null : table.getTableName(), // NOTE: an exception will be thrown if tableName is null whereClause, trxName); } @SuppressWarnings("deprecation") public Query(Properties ctx, String tableName, String whereClause, @Nullable String trxName) { super(ctx, Object.class, tableName, whereClause, trxName); } @Override public Query setParameters(List<Object> parameters) { return (Query)super.setParameters(parameters); } @Override public Query setParameters(Object... parameters) { return (Query)super.setParameters(parameters); } @Override public Query setClient_ID() { return (Query)super.setClient_ID(); } @Override
public Query setOnlyActiveRecords(final boolean onlyActiveRecords) { return (Query)super.setOnlyActiveRecords(onlyActiveRecords); } @Override public Query setOrderBy(String orderBy) { return (Query)super.setOrderBy(orderBy); } @Override protected Query newInstance() { return new Query(getCtx(), getTableName(), getWhereClause(), getTrxName()); } @Override public Query addWhereClause(final boolean joinByAnd, final String whereClause) { return (Query)super.addWhereClause(joinByAnd, whereClause); } @Override public List<Object> list() throws DBException { return super.list(); } @Override public Query setOption(String name, Object value) { return (Query)super.setOption(name, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Query.java
1
请在Spring Boot框架中完成以下Java代码
public class MaterialEventsQueueConfiguration implements IEventBusQueueConfiguration { public static final Topic EVENTBUS_TOPIC = Topic.distributed("de.metas.material"); static final String QUEUE_NAME_SPEL = "#{metasfreshMaterialEventsQueue.name}"; private static final String QUEUE_BEAN_NAME = "metasfreshMaterialEventsQueue"; private static final String EXCHANGE_NAME_PREFIX = "metasfresh-material-events"; @Value(RabbitMQEventBusConfiguration.APPLICATION_NAME_SPEL) private String appName; @Bean(QUEUE_BEAN_NAME) public AnonymousQueue materialEventsQueue() { final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy(EVENTBUS_TOPIC.getName() + "." + appName + "-"); return new AnonymousQueue(eventQueueNamingStrategy); } @Bean public DirectExchange materialEventsExchange() { return new DirectExchange(EXCHANGE_NAME_PREFIX); } @Bean public Binding materialEventsBinding() { return BindingBuilder.bind(materialEventsQueue()) .to(materialEventsExchange()).with(EXCHANGE_NAME_PREFIX);
} @Override public String getQueueName() { return materialEventsQueue().getName(); } @Override public Optional<String> getTopicName() { return Optional.of(EVENTBUS_TOPIC.getName()); } @Override public String getExchangeName() { return materialEventsExchange().getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\material_dispo\MaterialEventsQueueConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class EmbeddableBook { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @Embedded @EmbeddableInstantiator(AuthorInstallator.class) private Author author; private String isbn; public EmbeddableBook() { } public EmbeddableBook(Long id, String title, Author author, String isbn) { this.id = id; this.title = title; this.author = author; this.isbn = isbn; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\recordswithjpa\embeddable\EmbeddableBook.java
2
请在Spring Boot框架中完成以下Java代码
static MongoManagedTypes mongoManagedTypes(ApplicationContext applicationContext) throws ClassNotFoundException { return MongoManagedTypes.fromIterable(new EntityScanner(applicationContext).scan(Document.class)); } @Bean @ConditionalOnMissingBean MongoMappingContext mongoMappingContext(MongoCustomConversions conversions, MongoManagedTypes managedTypes) { PropertyMapper map = PropertyMapper.get(); MongoMappingContext context = new MongoMappingContext(); map.from(this.properties.isAutoIndexCreation()).to(context::setAutoIndexCreation); context.setManagedTypes(managedTypes); Class<?> strategyClass = this.properties.getFieldNamingStrategy(); if (strategyClass != null) { context.setFieldNamingStrategy((FieldNamingStrategy) BeanUtils.instantiateClass(strategyClass)); } context.setSimpleTypeHolder(conversions.getSimpleTypeHolder()); return context; } @Bean @ConditionalOnMissingBean MongoCustomConversions mongoCustomConversions() { return MongoCustomConversions.create(this::configureConversions); } private void configureConversions(MongoConverterConfigurationAdapter configurer) { PropertyMapper.get().from(this.properties.getRepresentation()::getBigDecimal).to(configurer::bigDecimal);
} @Bean @ConditionalOnMissingBean(MongoConverter.class) MappingMongoConverter mappingMongoConverter(ObjectProvider<MongoDatabaseFactory> factory, MongoMappingContext context, MongoCustomConversions conversions) { MongoDatabaseFactory mongoDatabaseFactory = factory.getIfAvailable(); DbRefResolver dbRefResolver = (mongoDatabaseFactory != null) ? new DefaultDbRefResolver(mongoDatabaseFactory) : NoOpDbRefResolver.INSTANCE; MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); mappingConverter.setCustomConversions(conversions); return mappingConverter; } }
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoConfiguration.java
2
请完成以下Java代码
public void setC_Invoice_ID (final int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, C_Invoice_ID); } @Override public int getC_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_ID); } @Override public void setC_InvoiceTax_ID (final int C_InvoiceTax_ID) { if (C_InvoiceTax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_InvoiceTax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_InvoiceTax_ID, C_InvoiceTax_ID); } @Override public int getC_InvoiceTax_ID() { return get_ValueAsInt(COLUMNNAME_C_InvoiceTax_ID); } @Override public void setC_Tax_ID (final int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, C_Tax_ID); } @Override public int getC_Tax_ID() { return get_ValueAsInt(COLUMNNAME_C_Tax_ID); } @Override public void setIsDocumentLevel (final boolean IsDocumentLevel) { set_Value (COLUMNNAME_IsDocumentLevel, IsDocumentLevel); } @Override public boolean isDocumentLevel() { return get_ValueAsBoolean(COLUMNNAME_IsDocumentLevel); } @Override public void setIsPackagingTax (final boolean IsPackagingTax) { set_Value (COLUMNNAME_IsPackagingTax, IsPackagingTax); } @Override public boolean isPackagingTax() { return get_ValueAsBoolean(COLUMNNAME_IsPackagingTax); } @Override public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override
public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setIsWholeTax (final boolean IsWholeTax) { set_Value (COLUMNNAME_IsWholeTax, IsWholeTax); } @Override public boolean isWholeTax() { return get_ValueAsBoolean(COLUMNNAME_IsWholeTax); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceTax.java
1
请完成以下Java代码
public java.lang.CharSequence getDepartmentName() { return departmentName; } /** * Sets the value of the 'departmentName' field. * @param value The value of 'departmentName'. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder setDepartmentName(java.lang.CharSequence value) { validate(fields()[1], value); this.departmentName = value; fieldSetFlags()[1] = true; return this; } /** * Checks whether the 'departmentName' field has been set. * @return True if the 'departmentName' field has been set, false otherwise. */ public boolean hasDepartmentName() { return fieldSetFlags()[1]; } /** * Clears the value of the 'departmentName' field. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder clearDepartmentName() { departmentName = null; fieldSetFlags()[1] = false; return this; } @Override @SuppressWarnings("unchecked") public EmployeeKey build() { try { EmployeeKey record = new EmployeeKey(); record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]); record.departmentName = fieldSetFlags()[1] ? this.departmentName : (java.lang.CharSequence) defaultValue(fields()[1]); return record;
} catch (java.lang.Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumWriter<EmployeeKey> WRITER$ = (org.apache.avro.io.DatumWriter<EmployeeKey>)MODEL$.createDatumWriter(SCHEMA$); @Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { WRITER$.write(this, SpecificData.getEncoder(out)); } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumReader<EmployeeKey> READER$ = (org.apache.avro.io.DatumReader<EmployeeKey>)MODEL$.createDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { READER$.read(this, SpecificData.getDecoder(in)); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\EmployeeKey.java
1
请完成以下Java代码
public DataFetcherResult<CommentsConnection> articleComments( @InputArgument("first") Integer first, @InputArgument("after") String after, @InputArgument("last") Integer last, @InputArgument("before") String before, DgsDataFetchingEnvironment dfe) { if (first == null && last == null) { throw new IllegalArgumentException("first 和 last 必须只存在一个"); } User current = SecurityUtil.getCurrentUser().orElse(null); Article article = dfe.getSource(); Map<String, ArticleData> map = dfe.getLocalContext(); ArticleData articleData = map.get(article.getSlug()); CursorPager<CommentData> comments; if (first != null) { comments = commentQueryService.findByArticleIdWithCursor( articleData.getId(), current, new CursorPageParameter<>(DateTimeCursor.parse(after), first, Direction.NEXT)); } else { comments = commentQueryService.findByArticleIdWithCursor( articleData.getId(), current, new CursorPageParameter<>(DateTimeCursor.parse(before), last, Direction.PREV)); } graphql.relay.PageInfo pageInfo = buildCommentPageInfo(comments); CommentsConnection result = CommentsConnection.newBuilder() .pageInfo(pageInfo) .edges( comments.getData().stream() .map( a -> CommentEdge.newBuilder() .cursor(a.getCursor().toString()) .node(buildCommentResult(a)) .build()) .collect(Collectors.toList())) .build(); return DataFetcherResult.<CommentsConnection>newResult()
.data(result) .localContext( comments.getData().stream().collect(Collectors.toMap(CommentData::getId, c -> c))) .build(); } private DefaultPageInfo buildCommentPageInfo(CursorPager<CommentData> comments) { return new DefaultPageInfo( comments.getStartCursor() == null ? null : new DefaultConnectionCursor(comments.getStartCursor().toString()), comments.getEndCursor() == null ? null : new DefaultConnectionCursor(comments.getEndCursor().toString()), comments.hasPrevious(), comments.hasNext()); } private Comment buildCommentResult(CommentData comment) { return Comment.newBuilder() .id(comment.getId()) .body(comment.getBody()) .updatedAt(ISODateTimeFormat.dateTime().withZoneUTC().print(comment.getCreatedAt())) .createdAt(ISODateTimeFormat.dateTime().withZoneUTC().print(comment.getCreatedAt())) .build(); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\CommentDatafetcher.java
1
请完成以下Java代码
private static AdWindowId resolveWindowId(@Nullable final AdWindowId soWindowId, @Nullable final AdWindowId poWindowId) { // Case 1: Only SO window is defined if (soWindowId != null && poWindowId == null) { return soWindowId; } // Case 2: Only PO window is defined if (soWindowId == null && poWindowId != null) { return poWindowId; } // Case 3: Both defined OR both null // Return null to allow IsSOTrx-based window selection return null; } public ADRefTable retrieveAccountTableRefInfo() { return ADRefTable.builder() .identifier("Account - C_ValidCombination_ID") .tableName(I_C_ValidCombination.Table_Name) .keyColumn(I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID) .autoComplete(true) .tooltipType(adTableDAO.getTooltipTypeByTableName(I_C_ValidCombination.Table_Name)) .build(); } public boolean existListValue(final int adReferenceId, final String value) {
final ADRefListItem item = retrieveListItemOrNull(adReferenceId, value); return item != null; } @Nullable public ColorId getColorId(@NonNull final Object model, @NonNull final String columnName, @Nullable final String refListValue) { if (Check.isBlank(refListValue)) { return null; } final ReferenceId referenceId = InterfaceWrapperHelper.getPO(model).getPOInfo().getColumnReferenceValueId(columnName); if (referenceId == null) { return null; } final ADRefListItem refListItem = retrieveListItemOrNull(referenceId, refListValue); return refListItem != null ? refListItem.getColorId() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ad_reference\ADReferenceService.java
1
请在Spring Boot框架中完成以下Java代码
class ColumnInfo { TableAndColumnInfoRepository repository; // String tableName; String columnName; boolean isUpdatable; boolean isMandatory; int displayType; /** * i.e. AD_Column.AD_Reference_Value_ID */ int adReferenceId; int fieldLength; String defaultValue; String valueMin; String valueMax; String vFormat; String callout; String name; String description; boolean virtualColumn; boolean lazyLoading; boolean isEncrypted; boolean isKey; int seqNo; int adTableId; boolean isIdentifier; String tableIdColumnName; boolean isRestAPICustomColumn; @Builder private ColumnInfo( @NonNull final TableAndColumnInfoRepository repository, final String tableName, final String columnName, final boolean isUpdatable, final boolean isMandatory, final int displayType, final int adReferenceId, final int fieldLength, final String defaultValue, final String valueMin, final String valueMax, final String vFormat, final String callout, final String name, final String description, final boolean virtualColumn, final boolean isEncrypted, final boolean isKey, final boolean isIdentifier, final boolean lazyLoading, final int seqNo, final int adTableId, final String tableIdColumnName, final boolean isRestAPICustomColumn) {
this.repository = repository; this.tableName = tableName; this.columnName = columnName; this.isUpdatable = isUpdatable; this.isMandatory = isMandatory; this.displayType = displayType; this.adReferenceId = adReferenceId; this.fieldLength = fieldLength; this.defaultValue = defaultValue; this.valueMin = valueMin; this.valueMax = valueMax; this.vFormat = vFormat; this.callout = callout; this.name = name; this.description = description; this.virtualColumn = virtualColumn; this.isEncrypted = isEncrypted; this.isKey = isKey; this.isIdentifier = isIdentifier; this.lazyLoading = lazyLoading; this.seqNo = seqNo; this.adTableId = adTableId; this.tableIdColumnName = tableIdColumnName; this.isRestAPICustomColumn = isRestAPICustomColumn; } /** * Gets referenced table info (in case of Table or Search references which have the AD_Reference_Value_ID set) */ public Optional<TableReferenceInfo> getTableReferenceInfo() { return repository.getTableReferenceInfo(getAdReferenceId()); } public Optional<ListInfo> getListInfo() { return repository.getListInfo(getAdReferenceId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\ColumnInfo.java
2
请完成以下Java代码
public class UpgradeMojo extends AbstractReencryptMojo { @Parameter(property = "jasypt.plugin.old.major-version", defaultValue = "2") private int oldMajorVersion = 2; /** {@inheritDoc} */ @Override protected void configure(JasyptEncryptorConfigurationProperties properties) { Environment environment = getEnvironment(); setIfNotNull(properties::setPassword, environment.getProperty("jasypt.encryptor.password")); setIfNotNull(properties::setPrivateKeyFormat, environment.getProperty("jasypt.encryptor.private-key-format", AsymmetricCryptography.KeyFormat.class)); setIfNotNull(properties::setPrivateKeyString, environment.getProperty("jasypt.encryptor.private-key-string")); setIfNotNull(properties::setPrivateKeyLocation, environment.getProperty("jasypt.encryptor.private-key-location")); if (oldMajorVersion == 2) { upgradeFrom2(properties); } else {
throw new RuntimeException("Unrecognised major version " + oldMajorVersion); } } private void upgradeFrom2(JasyptEncryptorConfigurationProperties properties) { properties.setAlgorithm("PBEWithMD5AndDES"); properties.setKeyObtentionIterations("1000"); properties.setPoolSize("1"); properties.setProviderName(null); properties.setProviderClassName(null); properties.setSaltGeneratorClassname("org.jasypt.salt.RandomSaltGenerator"); properties.setIvGeneratorClassname("org.jasypt.iv.NoIvGenerator"); properties.setStringOutputType("base64"); } }
repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\UpgradeMojo.java
1
请完成以下Java代码
public PartyIdentification32CH getUltmtDbtr() { return ultmtDbtr; } /** * Sets the value of the ultmtDbtr property. * * @param value * allowed object is * {@link PartyIdentification32CH } * */ public void setUltmtDbtr(PartyIdentification32CH value) { this.ultmtDbtr = value; } /** * Gets the value of the chrgBr property. * * @return * possible object is * {@link ChargeBearerType1Code } * */ public ChargeBearerType1Code getChrgBr() { return chrgBr; } /** * Sets the value of the chrgBr property. * * @param value * allowed object is * {@link ChargeBearerType1Code } * */ public void setChrgBr(ChargeBearerType1Code value) { this.chrgBr = value; } /** * Gets the value of the chrgsAcct property. * * @return * possible object is * {@link CashAccount16CHIdAndCurrency } * */ public CashAccount16CHIdAndCurrency getChrgsAcct() { return chrgsAcct; } /** * Sets the value of the chrgsAcct property. * * @param value * allowed object is * {@link CashAccount16CHIdAndCurrency } * */
public void setChrgsAcct(CashAccount16CHIdAndCurrency value) { this.chrgsAcct = value; } /** * Gets the value of the cdtTrfTxInf 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 cdtTrfTxInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCdtTrfTxInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CreditTransferTransactionInformation10CH } * * */ public List<CreditTransferTransactionInformation10CH> getCdtTrfTxInf() { if (cdtTrfTxInf == null) { cdtTrfTxInf = new ArrayList<CreditTransferTransactionInformation10CH>(); } return this.cdtTrfTxInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentInstructionInformation3CH.java
1
请在Spring Boot框架中完成以下Java代码
public class DeviceDataValidator extends AbstractHasOtaPackageValidator<Device> { @Autowired private DeviceDao deviceDao; @Autowired private TenantService tenantService; @Autowired private CustomerDao customerDao; @Override protected void validateCreate(TenantId tenantId, Device device) { validateNumberOfEntitiesPerTenant(tenantId, EntityType.DEVICE); } @Override protected Device validateUpdate(TenantId tenantId, Device device) { Device old = deviceDao.findById(device.getTenantId(), device.getId().getId()); if (old == null) { throw new DataValidationException("Can't update non existing device!"); } return old; } @Override protected void validateDataImpl(TenantId tenantId, Device device) { validateString("Device name", device.getName()); if (device.getTenantId() == null) { throw new DataValidationException("Device should be assigned to tenant!"); } else { if (!tenantService.tenantExists(device.getTenantId())) { throw new DataValidationException("Device is referencing to non-existent tenant!");
} } if (device.getCustomerId() == null) { device.setCustomerId(new CustomerId(NULL_UUID)); } else if (!device.getCustomerId().getId().equals(NULL_UUID)) { Customer customer = customerDao.findById(device.getTenantId(), device.getCustomerId().getId()); if (customer == null) { throw new DataValidationException("Can't assign device to non-existent customer!"); } if (!customer.getTenantId().getId().equals(device.getTenantId().getId())) { throw new DataValidationException("Can't assign device to customer from different tenant!"); } } Optional.ofNullable(device.getDeviceData()) .flatMap(deviceData -> Optional.ofNullable(deviceData.getTransportConfiguration())) .ifPresent(DeviceTransportConfiguration::validate); validateOtaPackage(tenantId, device, device.getDeviceProfileId()); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\DeviceDataValidator.java
2
请完成以下Java代码
public int getMobileUI_UserProfile_Picking_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * PickingJobAggregationType AD_Reference_ID=541931 * Reference name: PickingJobAggregationType */ public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931; /** sales_order = sales_order */ public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order"; /** product = product */ public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product"; /** delivery_location = delivery_location */ public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location"; @Override public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } /** * PickingLineGroupBy AD_Reference_ID=541899 * Reference name: PickingLineGroupByValues */
public static final int PICKINGLINEGROUPBY_AD_Reference_ID=541899; /** Product_Category = product_category */ public static final String PICKINGLINEGROUPBY_Product_Category = "product_category"; @Override public void setPickingLineGroupBy (final @Nullable java.lang.String PickingLineGroupBy) { set_Value (COLUMNNAME_PickingLineGroupBy, PickingLineGroupBy); } @Override public java.lang.String getPickingLineGroupBy() { return get_ValueAsString(COLUMNNAME_PickingLineGroupBy); } /** * PickingLineSortBy AD_Reference_ID=541900 * Reference name: PickingLineSortByValues */ public static final int PICKINGLINESORTBY_AD_Reference_ID=541900; /** ORDER_LINE_SEQ_NO = ORDER_LINE_SEQ_NO */ public static final String PICKINGLINESORTBY_ORDER_LINE_SEQ_NO = "ORDER_LINE_SEQ_NO"; /** QTY_TO_PICK_ASC = QTY_TO_PICK_ASC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_ASC = "QTY_TO_PICK_ASC"; /** QTY_TO_PICK_DESC = QTY_TO_PICK_DESC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_DESC = "QTY_TO_PICK_DESC"; @Override public void setPickingLineSortBy (final @Nullable java.lang.String PickingLineSortBy) { set_Value (COLUMNNAME_PickingLineSortBy, PickingLineSortBy); } @Override public java.lang.String getPickingLineSortBy() { return get_ValueAsString(COLUMNNAME_PickingLineSortBy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking.java
1
请完成以下Java代码
public class BankToCustomerStatementV04 { @XmlElement(name = "GrpHdr", required = true) protected GroupHeader58 grpHdr; @XmlElement(name = "Stmt", required = true) protected List<AccountStatement4> stmt; @XmlElement(name = "SplmtryData") protected List<SupplementaryData1> splmtryData; /** * Gets the value of the grpHdr property. * * @return * possible object is * {@link GroupHeader58 } * */ public GroupHeader58 getGrpHdr() { return grpHdr; } /** * Sets the value of the grpHdr property. * * @param value * allowed object is * {@link GroupHeader58 } * */ public void setGrpHdr(GroupHeader58 value) { this.grpHdr = value; } /** * Gets the value of the stmt 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 stmt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStmt().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AccountStatement4 } * * */ public List<AccountStatement4> getStmt() { if (stmt == null) { stmt = new ArrayList<AccountStatement4>(); } return this.stmt; } /** * Gets the value of the splmtryData 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 splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\BankToCustomerStatementV04.java
1
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set ISO Währungscode. @param ISO_Code Three letter ISO 4217 Code of the Currency */ @Override public void setISO_Code (java.lang.String ISO_Code) { set_ValueNoCheck (COLUMNNAME_ISO_Code, ISO_Code); } /** Get ISO Währungscode. @return Three letter ISO 4217 Code of the Currency */ @Override public java.lang.String getISO_Code () { return (java.lang.String)get_Value(COLUMNNAME_ISO_Code); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_Location getOrg_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class); } @Override public void setOrg_Location(org.compiere.model.I_C_Location Org_Location) { set_ValueFromPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class, Org_Location); } /** Set Org Address. @param Org_Location_ID Organization Location/Address */ @Override public void setOrg_Location_ID (int Org_Location_ID) { if (Org_Location_ID < 1) set_ValueNoCheck (COLUMNNAME_Org_Location_ID, null); else set_ValueNoCheck (COLUMNNAME_Org_Location_ID, Integer.valueOf(Org_Location_ID)); } /** Get Org Address. @return Organization Location/Address */ @Override public int getOrg_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Org_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { set_ValueNoCheck (COLUMNNAME_Phone, Phone);
} /** Get Telefon. @return Beschreibt eine Telefon Nummer */ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Steuer-ID. @param TaxID Tax Identification */ @Override public void setTaxID (java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } /** Get Steuer-ID. @return Tax Identification */ @Override public java.lang.String getTaxID () { return (java.lang.String)get_Value(COLUMNNAME_TaxID); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java
1
请完成以下Java代码
public String getLauncherClassName() { return "org.springframework.boot.loader.launch.WarLauncher"; } @Override public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) { return SCOPE_LOCATION.get(scope); } @Override public String getClassesLocation() { return "WEB-INF/classes/"; } @Override public String getClasspathIndexFileLocation() { return "WEB-INF/classpath.idx";
} @Override public String getLayersIndexFileLocation() { return "WEB-INF/layers.idx"; } @Override public boolean isExecutable() { return true; } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java
1
请完成以下Java代码
public static void resetTimeSource() { timeSource = null; } /** * @param newTimeSource the given TimeSource will be used for the time returned by the * methods of this class (unless it is null). */ public static void setTimeSource(@NonNull final TimeSource newTimeSource) { timeSource = newTimeSource; } public static void setFixedTimeSource(@NonNull final ZonedDateTime date) { setTimeSource(FixedTimeSource.ofZonedDateTime(date)); } /** * @param zonedDateTime ISO 8601 date time format (see {@link ZonedDateTime#parse(CharSequence)}). * e.g. 2018-02-28T13:13:13+01:00[Europe/Berlin] */ public static void setFixedTimeSource(@NonNull final String zonedDateTime) { setTimeSource(FixedTimeSource.ofZonedDateTime(ZonedDateTime.parse(zonedDateTime))); } public static long millis() { return getTimeSource().millis(); } public static ZoneId zoneId() { return getTimeSource().zoneId(); } public static GregorianCalendar asGregorianCalendar() { final GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(millis()); return cal; } public static Date asDate() { return new Date(millis()); } public static Timestamp asTimestamp() { return new Timestamp(millis()); } /** * Same as {@link #asTimestamp()} but the returned date will be truncated to DAY. */ public static Timestamp asDayTimestamp() { final GregorianCalendar cal = asGregorianCalendar(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Timestamp(cal.getTimeInMillis()); } public static Instant asInstant() { return Instant.ofEpochMilli(millis()); } public static LocalDateTime asLocalDateTime() { return asZonedDateTime().toLocalDateTime(); } @NonNull public static LocalDate asLocalDate() { return asLocalDate(zoneId()); } @NonNull public static LocalDate asLocalDate(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId).toLocalDate(); } public static ZonedDateTime asZonedDateTime() { return asZonedDateTime(zoneId()); } public static ZonedDateTime asZonedDateTimeAtStartOfDay() { return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS); } public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId) .toLocalDate() .atTime(LocalTime.MAX) .atZone(zoneId); } public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId) { return asInstant().atZone(zoneId); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
1
请完成以下Java代码
public boolean isNotBlank(@Nullable final String str) { return !isEmpty(str, true); } /** * Is String Empty * * @param str string * @param trimWhitespaces trim whitespaces * @return true if >= 1 char */ @Contract("null, _ -> true") public boolean isEmpty(@Nullable final String str, final boolean trimWhitespaces) { if (str == null) { return true; } if (trimWhitespaces) { return str.trim().isEmpty(); } else { return str.isEmpty(); }
} // isEmpty /** * @return true if the array is null or it's length is zero. */ @Contract("null -> true") public <T> boolean isEmpty(@Nullable final T[] arr) { return arr == null || arr.length == 0; } /** * @return true if given collection is <code>null</code> or it has no elements */ @Contract("null -> true") public boolean isEmpty(@Nullable final Collection<?> collection) { return collection == null || collection.isEmpty(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\EmptyUtil.java
1
请完成以下Java代码
public boolean isCallOrder(@NonNull final DocTypeId docTypeId) { final I_C_DocType dt = docTypesRepo.getById(docTypeId); return (X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType()) || X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType())) && X_C_DocType.DOCSUBTYPE_CallOrder.equals(dt.getDocSubType()); } @Override public void save(@NonNull final I_C_DocType dt) { docTypesRepo.save(dt); } @NonNull public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId) { return docTypesRepo.retrieveForSelection(pinstanceId); } public DocTypeId cloneToOrg(@NonNull final I_C_DocType fromDocType, @NonNull final OrgId toOrgId) { final String newName = fromDocType.getName() + "_cloned"; final I_C_DocType newDocType = InterfaceWrapperHelper.copy() .setFrom(fromDocType) .setSkipCalculatedColumns(true) .copyToNew(I_C_DocType.class);
newDocType.setAD_Org_ID(toOrgId.getRepoId()); // dev-note: unique index (ad_client_id, name) newDocType.setName(newName); final DocSequenceId fromDocSequenceId = DocSequenceId.ofRepoIdOrNull(fromDocType.getDocNoSequence_ID()); if (fromDocType.isDocNoControlled() && fromDocSequenceId != null) { final DocSequenceId clonedDocSequenceId = sequenceDAO.cloneToOrg(fromDocSequenceId, toOrgId); newDocType.setDocNoSequence_ID(clonedDocSequenceId.getRepoId()); newDocType.setIsDocNoControlled(true); } save(newDocType); return DocTypeId.ofRepoId(newDocType.getC_DocType_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeBL.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(_id, company, name, companyName, additionalCompanyName, address, postalCode, city, phone, fax, email, website, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Hospital {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" company: ").append(toIndentedString(company)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" companyName: ").append(toIndentedString(companyName)).append("\n"); sb.append(" additionalCompanyName: ").append(toIndentedString(additionalCompanyName)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" website: ").append(toIndentedString(website)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Hospital.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]"; } // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name;
this.bytes = bytes; } @Override public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return Objects.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntity.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<String>> queryDepartPermission(@RequestParam(name = "departId", required = true) String departId) { Result<List<String>> result = new Result<>(); try { List<SysDepartPermission> list = sysDepartPermissionService.list(new QueryWrapper<SysDepartPermission>().lambda().eq(SysDepartPermission::getDepartId, departId)); result.setResult(list.stream().map(sysDepartPermission -> String.valueOf(sysDepartPermission.getPermissionId())).collect(Collectors.toList())); result.setSuccess(true); } catch (Exception e) { log.error(e.getMessage(), e); } return result; } /** * 保存部门授权 * * @return */ @RequestMapping(value = "/saveDepartPermission", method = RequestMethod.POST) @RequiresPermissions("system:permission:saveDepart") public Result<String> saveDepartPermission(@RequestBody JSONObject json) {
long start = System.currentTimeMillis(); Result<String> result = new Result<>(); try { String departId = json.getString("departId"); String permissionIds = json.getString("permissionIds"); String lastPermissionIds = json.getString("lastpermissionIds"); this.sysDepartPermissionService.saveDepartPermission(departId, permissionIds, lastPermissionIds); result.success("保存成功!"); log.info("======部门授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒"); } catch (Exception e) { result.error500("授权失败!"); log.error(e.getMessage(), e); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysPermissionController.java
2
请完成以下Java代码
public class RequiredValidator implements FormFieldValidator { public boolean validate(Object submittedValue, FormFieldValidatorContext validatorContext) { if(submittedValue == null) { var variableName = validatorContext.getFormFieldHandler().getId(); TypedValue value = validatorContext.getVariableScope().getVariableTyped(variableName); if (value != null) { return value.getValue() != null; } // check if there is a default value var defaultValueExpression = validatorContext.getFormFieldHandler().getDefaultValueExpression(); if (defaultValueExpression != null) { var variableValue = defaultValueExpression.getValue(validatorContext.getVariableScope()); if (variableValue != null) { // set default value
validatorContext.getVariableScope().setVariable(variableName, variableValue); return true; } } return false; } else { if (submittedValue instanceof String) { return !((String)submittedValue).isEmpty(); } else { return true; } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\validator\RequiredValidator.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteAll() { repository.deleteAll(); } /** * 保存客户 * @param customer 客户 */ public void save(Customer customer) { repository.save(customer); } /** * 查询所有客户列表 * @return 客户列表 */ public Iterable<Customer> findAll() { return repository.findAll(); } /** * 通过名查找某个客户 * @param firstName
* @return */ public Customer findByFirstName(String firstName) { return repository.findByFirstName(firstName); } /** * 通过姓查找客户列表 * @param lastName * @return */ public List<Customer> findByLastName(String lastName) { return repository.findByLastName(lastName); } }
repos\SpringBootBucket-master\springboot-mongodb\src\main\java\com\xncoding\pos\service\CustomerService.java
2
请完成以下Java代码
public SpinXmlDataFormatException unableToCreateUnmarshaller(Throwable cause) { return new SpinXmlDataFormatException(exceptionMessage("031", "Cannot create unmarshaller"), cause); } public SpinXmlDataFormatException unableToSetEventHandler(String className, Throwable cause) { return new SpinXmlDataFormatException(exceptionMessage("032", "Cannot set event handler to '{}'", className), cause); } public SpinXmlDataFormatException unableToSetProperty(String propertyName, String className, Throwable cause) { return new SpinXmlDataFormatException(exceptionMessage("033", "Cannot set property '{}' to '{}'", propertyName, className), cause); } public SpinXPathException notAllowedXPathExpression(String expression) { return new SpinXPathException(exceptionMessage("034", "XPath expression '{}' not allowed", expression)); } public SpinXPathException unableToFindXPathExpression(String expression) { return new SpinXPathException(exceptionMessage("035", "Unable to find XPath expression '{}'", expression)); } public SpinXmlElementException elementIsNotChildOfThisElement(SpinXmlElement existingChildElement, SpinXmlElement parentDomElement) {
return new SpinXmlElementException(exceptionMessage("036", "The element with namespace '{}' and name '{}' " + "is not a child element of the element with namespace '{}' and name '{}'", existingChildElement.namespace(), existingChildElement.name(), parentDomElement.namespace(), parentDomElement.name() )); } public SpinXmlDataFormatException unableToFindStripSpaceXsl(String expression) { return new SpinXmlDataFormatException(exceptionMessage("037", "No formatting configuration defined and unable to find the default '{}'", expression)); } public SpinXmlDataFormatException unableToLoadFormattingTemplates(Throwable cause) { return new SpinXmlDataFormatException(exceptionMessage("038", "Failed to get formatting templates"), cause); } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlLogger.java
1
请完成以下Java代码
public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg
Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessorLog.java
1
请完成以下Java代码
public void setSQL_Details_WhereClause (final @Nullable java.lang.String SQL_Details_WhereClause) { set_Value (COLUMNNAME_SQL_Details_WhereClause, SQL_Details_WhereClause); } @Override public java.lang.String getSQL_Details_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_Details_WhereClause); } @Override public void setSQL_From (final @Nullable java.lang.String SQL_From) { set_Value (COLUMNNAME_SQL_From, SQL_From); } @Override public java.lang.String getSQL_From() { return get_ValueAsString(COLUMNNAME_SQL_From); } @Override public void setSQL_GroupAndOrderBy (final @Nullable java.lang.String SQL_GroupAndOrderBy) { set_Value (COLUMNNAME_SQL_GroupAndOrderBy, SQL_GroupAndOrderBy); } @Override public java.lang.String getSQL_GroupAndOrderBy() { return get_ValueAsString(COLUMNNAME_SQL_GroupAndOrderBy); } @Override public void setSQL_WhereClause (final @Nullable java.lang.String SQL_WhereClause) { set_Value (COLUMNNAME_SQL_WhereClause, SQL_WhereClause); }
@Override public java.lang.String getSQL_WhereClause() { return get_ValueAsString(COLUMNNAME_SQL_WhereClause); } @Override public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID) { if (WEBUI_KPI_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID); } @Override public int getWEBUI_KPI_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI.java
1
请完成以下Java代码
public static class ScadaSymbolMetadataInfo { private String title; private String description; private String[] searchTags; private int widgetSizeX; private int widgetSizeY; public ScadaSymbolMetadataInfo(String fileName, JsonNode metaData) { if (metaData != null && metaData.has("title")) { title = metaData.get("title").asText(); } else { title = fileName; } if (metaData != null && metaData.has("description")) { description = metaData.get("description").asText(); } else { description = ""; } if (metaData != null && metaData.has("searchTags") && metaData.get("searchTags").isArray()) { var tagsNode = (ArrayNode) metaData.get("searchTags"); searchTags = new String[tagsNode.size()]; for (int i = 0; i < tagsNode.size(); i++) { searchTags[i] = tagsNode.get(i).asText();
} } else { searchTags = new String[0]; } if (metaData != null && metaData.has("widgetSizeX")) { widgetSizeX = metaData.get("widgetSizeX").asInt(); } else { widgetSizeX = 3; } if (metaData != null && metaData.has("widgetSizeY")) { widgetSizeY = metaData.get("widgetSizeY").asInt(); } else { widgetSizeY = 3; } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\ImageUtils.java
1
请在Spring Boot框架中完成以下Java代码
public static DateAndSeqNo atTimeNoSeqNo(@NonNull final Instant date) { return builder() .date(date) .build(); } public static DateAndSeqNo ofCandidate(@NonNull final Candidate candidate) { return builder() .date(candidate.getDate()) .seqNo(candidate.getSeqNo()) .build(); } public static DateAndSeqNo ofAddToResultGroupRequest(@NonNull final AddToResultGroupRequest addToResultGroupRequest) { return builder() .date(addToResultGroupRequest.getDate()) .seqNo(addToResultGroupRequest.getSeqNo()) .build(); } public enum Operator { INCLUSIVE, EXCLUSIVE } @Builder(toBuilder = true) private DateAndSeqNo( @NonNull final Instant date, final int seqNo, @Nullable final Operator operator) { this.date = date; this.seqNo = seqNo; this.operator = operator; } /** * @return {@code true} if this instances {@code date} is after the {@code other}'s {@code date} * or if this instance's {@code seqNo} is greater than the {@code other}'s {@code seqNo}. */ public boolean isAfter(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isAfter(other.getDate())) { return true; } if (date.isBefore(other.getDate())) { return false; } return seqNo > other.getSeqNo(); } /** * Analog to {@link #isAfter(DateAndSeqNo)}. */ public boolean isBefore(@NonNull final DateAndSeqNo other) { // note that we avoid using equals here, a timestamp and a date that are both "Date" might not be equal even if they have the same time. if (date.isBefore(other.getDate())) {
return true; } if (date.isAfter(other.getDate())) { return false; } return seqNo < other.getSeqNo(); } public DateAndSeqNo min(@Nullable final DateAndSeqNo other) { if (other == null) { return this; } else { return this.isBefore(other) ? this : other; } } public DateAndSeqNo max(@Nullable final DateAndSeqNo other) { if (other == null) { return this; } return this.isAfter(other) ? this : other; } public DateAndSeqNo withOperator(@Nullable final Operator operator) { return this .toBuilder() .operator(operator) .build(); } public static boolean equals(@Nullable final DateAndSeqNo value1, @Nullable final DateAndSeqNo value2) {return Objects.equals(value1, value2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\DateAndSeqNo.java
2
请完成以下Java代码
public HistoricMilestoneInstanceQuery milestoneInstanceReachedBefore(Date reachedBefore) { this.reachedBefore = reachedBefore; return this; } @Override public HistoricMilestoneInstanceQuery milestoneInstanceReachedAfter(Date reachedAfter) { this.reachedAfter = reachedAfter; return this; } @Override public HistoricMilestoneInstanceQuery orderByMilestoneName() { return orderBy(MilestoneInstanceQueryProperty.MILESTONE_NAME); } @Override public HistoricMilestoneInstanceQuery orderByTimeStamp() { return orderBy(MilestoneInstanceQueryProperty.MILESTONE_TIMESTAMP); } @Override public HistoricMilestoneInstanceQuery milestoneInstanceTenantId(String tenantId) { if (tenantId == null) { throw new FlowableIllegalArgumentException("tenant id is null"); } this.tenantId = tenantId; return this; } @Override public HistoricMilestoneInstanceQuery milestoneInstanceTenantIdLike(String tenantIdLike) { if (tenantIdLike == null) { throw new FlowableIllegalArgumentException("tenant id is null"); } this.tenantIdLike = tenantIdLike; return this; } @Override public HistoricMilestoneInstanceQuery milestoneInstanceWithoutTenantId() { this.withoutTenantId = true; return this; } @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstanceCountByQueryCriteria(this); }
@Override public List<HistoricMilestoneInstance> executeList(CommandContext commandContext) { return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstancesByQueryCriteria(this); } @Override public String getId() { return id; } public String getName() { return name; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseDefinitionId() { return caseDefinitionId; } public Date getReachedBefore() { return reachedBefore; } public Date getReachedAfter() { return reachedAfter; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void clearRepository(TenantId tenantId) throws IOException { GitRepository repository = repositories.remove(tenantId); if (repository != null) { log.debug("[{}] Clear tenant repository started.", tenantId); FileUtils.deleteDirectory(new File(repository.getDirectory())); log.debug("[{}] Clear tenant repository completed.", tenantId); } } private EntityVersion toVersion(GitRepository.Commit commit) { return new EntityVersion(commit.getTimestamp(), commit.getId(), commit.getMessage(), this.getAuthor(commit)); } private String getAuthor(GitRepository.Commit commit) { String author = String.format("<%s>", commit.getAuthorEmail()); if (StringUtils.isNotBlank(commit.getAuthorName())) { author = String.format("%s %s", commit.getAuthorName(), author); } return author; }
public static EntityId fromRelativePath(String path) { EntityType entityType = EntityType.valueOf(StringUtils.substringBefore(path, "/").toUpperCase()); String entityId = StringUtils.substringBetween(path, "/", ".json"); return EntityIdFactory.getByTypeAndUuid(entityType, entityId); } private GitRepository openOrCloneRepository(TenantId tenantId, RepositorySettings settings, boolean fetch) throws Exception { log.debug("[{}] Init tenant repository started.", tenantId); Path repositoryDirectory = Path.of(repositoriesFolder, settings.isLocalOnly() ? "local_" + settings.getRepositoryUri() : tenantId.getId().toString()); GitRepository repository = GitRepository.openOrClone(repositoryDirectory, settings, fetch); repositories.put(tenantId, repository); log.debug("[{}] Init tenant repository completed.", tenantId); return repository; } }
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitRepositoryService.java
2
请完成以下Java代码
public static Future<Long> factorialUsingCompletableFuture(int number) { CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); return completableFuture; } /** * Finds factorial of a number using EA Async * @param number * @return */ @Loggable public static long factorialUsingEAAsync(int number) { CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> factorial(number)); long result = await(completableFuture); return result; } /** * Finds factorial of a number using Async of Cactoos * @param number * @return * @throws InterruptedException * @throws ExecutionException */ @Loggable public static Future<Long> factorialUsingCactoos(int number) throws InterruptedException, ExecutionException { org.cactoos.func.Async<Integer, Long> asyncFunction = new org.cactoos.func.Async<Integer, Long>(input -> factorial(input)); Future<Long> asyncFuture = asyncFunction.apply(number); return asyncFuture; } /** * Finds factorial of a number using Guava's ListeningExecutorService.submit() * @param number * @return */ @Loggable public static ListenableFuture<Long> factorialUsingGuavaServiceSubmit(int number) { ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
ListenableFuture<Long> factorialFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number)); return factorialFuture; } /** * Finds factorial of a number using Guava's Futures.submitAsync() * @param number * @return */ @Loggable public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) { ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() { public Long call() { return factorial(number); } }, service); return Futures.submitAsync(asyncCallable, service); } /** * Finds factorial of a number using @Async of jcabi-aspects * @param number * @return */ @Async @Loggable public static Future<Long> factorialUsingJcabiAspect(int number) { Future<Long> factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); return factorialFuture; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\async\JavaAsync.java
1
请完成以下Java代码
public static boolean isHighVolume(final DocumentFilterList stickyFilters) { final HUIdsFilterData huIdsFilterData = HUIdsFilterHelper.extractFilterData(stickyFilters).orElse(null); return huIdsFilterData == null || huIdsFilterData.isPossibleHighVolume(HIGHVOLUME_THRESHOLD); } private static class DefaultSelectionHolder { private final HUEditorViewRepository huEditorViewRepository; private final ViewEvaluationCtx viewEvaluationCtx; private final ViewId viewId; private final DocumentFilterList filters; private final DocumentQueryOrderByList orderBys; private final SqlDocumentFilterConverterContext filterConverterCtx; private final SynchronizedMutable<ViewRowIdsOrderedSelection> defaultSelectionRef; @Builder private DefaultSelectionHolder( @NonNull final HUEditorViewRepository huEditorViewRepository, final ViewEvaluationCtx viewEvaluationCtx, final ViewId viewId, @NonNull final DocumentFilterList filters, @Nullable final DocumentQueryOrderByList orderBys, final SqlDocumentFilterConverterContext filterConverterCtx) { this.huEditorViewRepository = huEditorViewRepository; this.viewEvaluationCtx = viewEvaluationCtx; this.viewId = viewId; this.filters = filters; this.orderBys = orderBys; this.filterConverterCtx = filterConverterCtx; defaultSelectionRef = Mutables.synchronizedMutable(create()); } private ViewRowIdsOrderedSelection create() { return huEditorViewRepository.createSelection(viewEvaluationCtx, viewId, filters, orderBys, filterConverterCtx); } public ViewRowIdsOrderedSelection get() { return defaultSelectionRef.computeIfNull(this::create); } /**
* @return true if selection was really changed */ public boolean change(@NonNull final UnaryOperator<ViewRowIdsOrderedSelection> mapper) { final ViewRowIdsOrderedSelection defaultSelectionOld = defaultSelectionRef.getValue(); defaultSelectionRef.computeIfNull(this::create); // make sure it's not null (might be null if it was invalidated) final ViewRowIdsOrderedSelection defaultSelectionNew = defaultSelectionRef.compute(mapper); return !ViewRowIdsOrderedSelection.equals(defaultSelectionOld, defaultSelectionNew); } public void delete() { defaultSelectionRef.computeIfNotNull(defaultSelection -> { huEditorViewRepository.deleteSelection(defaultSelection); return null; }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_HighVolume.java
1
请完成以下Java代码
public int[] simple_for_loop() { int[] arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i; LOGGER.debug("Simple for loop: i - " + i); } return arr; } public int[] enhanced_for_each_loop() { int[] intArr = { 0, 1, 2, 3, 4 }; int[] arr = new int[5]; for (int num : intArr) { arr[num] = num; LOGGER.debug("Enhanced for-each loop: i - " + num); } return arr; } public int[] while_loop() { int i = 0;
int[] arr = new int[5]; while (i < 5) { arr[i] = i; LOGGER.debug("While loop: i - " + i++); } return arr; } public int[] do_while_loop() { int i = 0; int[] arr = new int[5]; do { arr[i] = i; LOGGER.debug("Do-While loop: i - " + i++); } while (i < 5); return arr; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-3\src\main\java\com\baeldung\loops\LoopsInJava.java
1
请完成以下Java代码
public class RatpackPromiseApp { /** * Try hitting http://localhost:5050/movies or http://localhost:5050/movie to see the application in action. * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { RxRatpack.initialize(); Handler movieHandler = (ctx) -> { MovieObservableService movieSvc = ctx.get(MovieObservableService.class); Observable<Movie> movieObs = movieSvc.getMovie(); RxRatpack.promiseSingle(movieObs)
.then(movie -> ctx.render(Jackson.json(movie))); }; Handler moviesHandler = (ctx) -> { MovieObservableService movieSvc = ctx.get(MovieObservableService.class); Observable<Movie> movieObs = movieSvc.getMovies(); RxRatpack.promise(movieObs) .then(movie -> ctx.render(Jackson.json(movie))); }; RatpackServer.start(def -> def.registryOf(rSpec -> rSpec.add(MovieObservableService.class, new MovieObservableServiceImpl())) .handlers(chain -> chain.get("movie", movieHandler) .get("movies", moviesHandler))); } }
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\rxjava\RatpackPromiseApp.java
1
请完成以下Java代码
public ProcessDefinitionEntity findProcessDefinitionByParentDeploymentAndKeyAndTenantId(String parentDeploymentId, String processDefinitionKey, String tenantId) { return dataManager.findProcessDefinitionByParentDeploymentAndKeyAndTenantId(parentDeploymentId, processDefinitionKey, tenantId); } @Override public ProcessDefinition findProcessDefinitionByKeyAndVersionAndTenantId(String processDefinitionKey, Integer processDefinitionVersion, String tenantId) { if (tenantId == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(tenantId)) { return dataManager.findProcessDefinitionByKeyAndVersion(processDefinitionKey, processDefinitionVersion); } else { return dataManager.findProcessDefinitionByKeyAndVersionAndTenantId(processDefinitionKey, processDefinitionVersion, tenantId); } } @Override public List<ProcessDefinition> findProcessDefinitionsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findProcessDefinitionsByNativeQuery(parameterMap); }
@Override public long findProcessDefinitionCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findProcessDefinitionCountByNativeQuery(parameterMap); } @Override public void updateProcessDefinitionTenantIdForDeployment(String deploymentId, String newTenantId) { dataManager.updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId); } @Override public void updateProcessDefinitionVersionForProcessDefinitionId(String processDefinitionId, int version) { dataManager.updateProcessDefinitionVersionForProcessDefinitionId(processDefinitionId, version); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityManagerImpl.java
1
请完成以下Java代码
public class MIndexColumn extends X_AD_Index_Column { /** * */ private static final long serialVersionUID = 1907712672821691643L; public MIndexColumn(Properties ctx, int AD_Index_Column_ID, String trxName) { super(ctx, AD_Index_Column_ID, trxName); } public MIndexColumn(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } /** * Get Column Name * * @return column name */ public String getColumnName() { String sql = getColumnSQL(); if (!Check.isEmpty(sql, true)) { return sql; } int AD_Column_ID = getAD_Column_ID(); return MColumn.getColumnName(getCtx(), AD_Column_ID); } @Override public String toString() { StringBuffer sb = new StringBuffer("MIndexColumn[").append(get_ID()) .append(", AD_Column_ID=").append(getAD_Column_ID()) .append("]"); return sb.toString(); } public static MIndexColumn retrieveOrCreate(final MIndexTable indexTable, final String columnName, final int seqNo) { final Properties ctx = indexTable.getCtx(); final String trxName = indexTable.get_TrxName(); final MTable table = (MTable) indexTable.getAD_Table(); final MColumn column = table.getColumn(columnName); if (column == null) { throw new IllegalArgumentException("Illegal column name '"
+ columnName + "' for table " + table); } final String whereClause = COLUMNNAME_AD_Index_Table_ID + "=? AND " + COLUMNNAME_AD_Column_ID + "=?"; final Object[] params = { indexTable.get_ID(), column.get_ID() }; MIndexColumn indexColumn = new Query(ctx, Table_Name, whereClause, trxName).setParameters(params).firstOnly(MIndexColumn.class); if (indexColumn == null) { indexColumn = new MIndexColumn(ctx, 0, trxName); indexColumn.setAD_Index_Table_ID(indexTable.get_ID()); indexColumn.setAD_Column_ID(column.get_ID()); } indexColumn.setSeqNo(seqNo); indexColumn.saveEx(); return indexColumn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexColumn.java
1
请完成以下Spring Boot application配置
server: port: 8083 spring: application: name: account-service datasource: url: jdbc:mysql://127.0.0.1:3306/seata_account?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root password: cloud: # Nacos 作为注册中心的配置项 nacos: discovery: server-addr: 127.0.0.1:8848 # Seata 配置项,对应 SeataProperties 类 seata: application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name} tx-service-group: ${spring.appl
ication.name}-group # Seata 事务组编号,用于 TC 集群名 # 服务配置项,对应 ServiceProperties 类 service: # 虚拟组和分组的映射 vgroup-mapping: account-service-group: default # 分组和 Seata 服务的映射 grouplist: default: 127.0.0.1:8091
repos\SpringBoot-Labs-master\labx-17\labx-17-sc-seata-at-feign-demo\labx-17-sc-seata-at-feign-demo-account-service\src\main\resources\application-file.yaml
2
请完成以下Java代码
public void setCaseDate(XMLGregorianCalendar value) { this.caseDate = value; } /** * Gets the value of the contractNumber property. * * @return * possible object is * {@link String } * */ 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代码
private void setAutoSendAfterEachConfirm(final boolean autoSendAfterEachConfirm) { this.autoSendAfterEachConfirm = autoSendAfterEachConfirm; } public synchronized void send() { // Do nothing if there is nothing to send if (syncConfirmations.isEmpty()) { return; } final PutConfirmationToProcurementWebRequest syncConfirmationRequest = PutConfirmationToProcurementWebRequest.of(syncConfirmations); senderToProcurementWebUI.send(syncConfirmationRequest); syncConfirmations.clear(); } /** * Generates a {@link SyncConfirmation} instance to be send either directly after the next commit. */
public void confirm(final IConfirmableDTO syncModel, final String serverEventId) { if (syncModel.getSyncConfirmationId() <= 0) { return; // nothing to do } final SyncConfirmation syncConfirmation = SyncConfirmation.forConfirmId(syncModel.getSyncConfirmationId()); syncConfirmation.setDateConfirmed(SystemTime.asDate()); syncConfirmation.setServerEventId(serverEventId); syncConfirmations.add(syncConfirmation); if (autoSendAfterEachConfirm) { send(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncConfirmationsSender.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeResource { @Autowired private EmployeeService employeeService; @RequestMapping(method = RequestMethod.GET, path = "/") public List<Employee> getEmployees() { return employeeService.getAllEmployees(); } @RequestMapping(method = RequestMethod.GET, path = "/v2") public EmployeeList getEmployeesUsingWrapperClass() { List<Employee> employees = employeeService.getAllEmployees();
return new EmployeeList(employees); } @RequestMapping(method = RequestMethod.POST, path = "/") public void addEmployees(@RequestBody List<Employee> employees) { employeeService.addEmployees(employees); } @RequestMapping(method = RequestMethod.POST, path = "/v2") public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper) { employeeService.addEmployees(employeeWrapper.getEmployees()); } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-1\src\main\java\com\baeldung\resttemplate\lists\controller\EmployeeResource.java
2
请完成以下Java代码
private static OAuth2Error getOAuth2Error(ErrorObject errorObject) { if (errorObject == null) { return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR); } String code = (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR; String description = errorObject.getDescription(); String uri = (errorObject.getURI() != null) ? errorObject.getURI().toString() : null; return new OAuth2Error(code, description, uri); } private static OAuth2AccessTokenResponse oauth2AccessTokenResponse(AccessTokenResponse accessTokenResponse) { AccessToken accessToken = accessTokenResponse.getTokens().getAccessToken(); OAuth2AccessToken.TokenType accessTokenType = null; if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessToken.getType().getValue())) { accessTokenType = OAuth2AccessToken.TokenType.BEARER; } long expiresIn = accessToken.getLifetime(); Set<String> scopes = (accessToken.getScope() != null) ? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet(); String refreshToken = null; if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue(); } Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters()); // @formatter:off return OAuth2AccessTokenResponse.withToken(accessToken.getValue()) .tokenType(accessTokenType) .expiresIn(expiresIn) .scopes(scopes) .refreshToken(refreshToken) .additionalParameters(additionalParameters) .build(); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\web\reactive\function\OAuth2AccessTokenResponseBodyExtractor.java
1
请在Spring Boot框架中完成以下Java代码
public static String getDefinitionDeploymentId(CaseDefinition caseDefinition, CmmnEngineConfiguration cmmnEngineConfiguration) { CmmnDeploymentManager deploymentManager = cmmnEngineConfiguration.getDeploymentManager(); CmmnDeploymentEntity caseDeployment = deploymentManager.getDeploymentEntityManager().findById(caseDefinition.getDeploymentId()); if (StringUtils.isEmpty(caseDeployment.getParentDeploymentId())) { return caseDefinition.getDeploymentId(); } return caseDeployment.getParentDeploymentId(); } protected static CaseDefinition getCaseDefinition(String caseDefinitionId, CmmnDeploymentManager deploymentManager, CaseDefinitionCacheEntry cacheEntry) { if (cacheEntry != null) { return cacheEntry.getCaseDefinition(); } return deploymentManager.findDeployedCaseDefinitionById(caseDefinitionId); }
public static CmmnModel getCmmnModel(String caseDefinitionId) { CmmnDeploymentManager deploymentManager = CommandContextUtil.getCmmnEngineConfiguration().getDeploymentManager(); CaseDefinitionCacheEntry cacheEntry = deploymentManager.getCaseDefinitionCache().get(caseDefinitionId); if (cacheEntry != null) { return cacheEntry.getCmmnModel(); } deploymentManager.findDeployedCaseDefinitionById(caseDefinitionId); return deploymentManager.getCaseDefinitionCache().get(caseDefinitionId).getCmmnModel(); } public static Case getCase(String caseDefinitionId) { return getCmmnModel(caseDefinitionId).getPrimaryCase(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CaseDefinitionUtil.java
2
请完成以下Java代码
public ImmutableMap<HuId, ImmutableSet<OrderId>> getOpenPickingOrderIdsByHuId(@NonNull final ImmutableSet<HuId> huIds) { final ImmutableList<PickingCandidate> openPickingCandidates = pickingCandidateRepository.getByHUIds(huIds) .stream() .filter(pickingCandidate -> !pickingCandidate.isProcessed()) .collect(ImmutableList.toImmutableList()); final ImmutableListMultimap<HuId, ShipmentScheduleId> huId2ShipmentScheduleIds = openPickingCandidates .stream() .collect(ImmutableListMultimap.toImmutableListMultimap(pickingCandidate -> pickingCandidate.getPickFrom().getHuId(), PickingCandidate::getShipmentScheduleId)); final ImmutableMap<ShipmentScheduleId, OrderId> scheduleId2OrderId = shipmentSchedulePA.getByIds(ImmutableSet.copyOf(huId2ShipmentScheduleIds.values())) .values() .stream() .filter(shipmentSchedule -> shipmentSchedule.getC_Order_ID() > 0) .collect(ImmutableMap.toImmutableMap(shipSchedule -> ShipmentScheduleId.ofRepoId(shipSchedule.getM_ShipmentSchedule_ID()), shipSchedule -> OrderId.ofRepoId(shipSchedule.getC_Order_ID()))); return huIds.stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), huId -> { final ImmutableList<ShipmentScheduleId> scheduleIds = Optional .ofNullable(huId2ShipmentScheduleIds.get(huId)) .orElseGet(ImmutableList::of); return scheduleIds.stream() .map(scheduleId2OrderId::get) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); })); } @Override public void beforeReleasePickingSlot(final @NonNull ReleasePickingSlotRequest request) { final boolean clearedAllUnprocessedHUs = clearPickingSlot(request.getPickingSlotId(), request.isRemoveUnprocessedHUsFromSlot()); if (!clearedAllUnprocessedHUs)
{ throw new AdempiereException(DRAFTED_PICKING_CANDIDATES_ERR_MSG).markAsUserValidationError(); } } /** * @return true, if all drafted picking candidates have been removed from the slot, false otherwise */ private boolean clearPickingSlot(@NonNull final PickingSlotId pickingSlotId, final boolean removeUnprocessedHUsFromSlot) { if (removeUnprocessedHUsFromSlot) { RemoveHUFromPickingSlotCommand.builder() .pickingCandidateRepository(pickingCandidateRepository) .pickingSlotId(pickingSlotId) .build() .perform(); } return !pickingCandidateRepository.hasDraftCandidatesForPickingSlot(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateService.java
1
请完成以下Java代码
default PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic) { return PriceAndTax.NONE; } default void setShipmentSchedule(final I_C_Invoice_Candidate ic) { /* do nothing */ }; /** * * Method responsible for setting * <ul> * <li>Bill_BPartner_ID * <li>Bill_Location_ID * <li>Bill_User_ID * </ul> * of the given invoice candidate. */ void setBPartnerData(I_C_Invoice_Candidate ic); default void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate ic) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); ic.setC_InvoiceSchedule_ID(bpartnerDAO.getById(ic.getBill_BPartner_ID()).getC_InvoiceSchedule_ID()); invoiceCandBL.set_DateToInvoice_DefaultImpl(ic); } /** * Price and tax info calculation result. * <p>
* All fields are optional and only those filled will be set back to invoice candidate. */ @lombok.Value @lombok.Builder class PriceAndTax { public static final PriceAndTax NONE = builder().build(); PricingSystemId pricingSystemId; PriceListVersionId priceListVersionId; CurrencyId currencyId; BigDecimal priceEntered; BigDecimal priceActual; UomId priceUOMId; Percent discount; InvoicableQtyBasedOn invoicableQtyBasedOn; Boolean taxIncluded; TaxId taxId; TaxCategoryId taxCategoryId; BigDecimal compensationGroupBaseAmt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\IInvoiceCandidateHandler.java
1
请完成以下Java代码
public class TbMsgDeleteAttributesNode implements TbNode { private TbMsgDeleteAttributesNodeConfiguration config; private List<String> keys; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesNodeConfiguration.class); keys = config.getKeys(); } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { List<String> keysToDelete = keys.stream() .map(keyPattern -> TbNodeUtils.processPattern(keyPattern, msg)) .distinct() .filter(StringUtils::isNotBlank) .collect(Collectors.toList()); if (keysToDelete.isEmpty()) { ctx.tellSuccess(msg); } else { AttributeScope scope = getScope(msg.getMetaData().getValue(SCOPE)); ctx.getTelemetryService().deleteAttributes(AttributesDeleteRequest.builder() .tenantId(ctx.getTenantId()) .entityId(msg.getOriginator()) .scope(scope) .keys(keysToDelete)
.notifyDevice(checkNotifyDevice(msg.getMetaData().getValue(NOTIFY_DEVICE_METADATA_KEY), scope)) .previousCalculatedFieldIds(msg.getPreviousCalculatedFieldIds()) .tbMsgId(msg.getId()) .tbMsgType(msg.getInternalType()) .callback(config.isSendAttributesDeletedNotification() ? new AttributesDeleteNodeCallback(ctx, msg, scope.name(), keysToDelete) : new TelemetryNodeCallback(ctx, msg)) .build()); } } private AttributeScope getScope(String mdScopeValue) { if (StringUtils.isNotEmpty(mdScopeValue)) { return AttributeScope.valueOf(mdScopeValue); } return AttributeScope.valueOf(config.getScope()); } private boolean checkNotifyDevice(String notifyDeviceMdValue, AttributeScope scope) { return (AttributeScope.SHARED_SCOPE == scope) && (config.isNotifyDevice() || Boolean.parseBoolean(notifyDeviceMdValue)); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\telemetry\TbMsgDeleteAttributesNode.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public boolean hasNewProcessDefinitionId() { return StringUtils.isNotBlank(newProcessDefinitionId); } public String getNewProcessDefinitionId() { return newProcessDefinitionId; } public String getTenantId() { return tenantId; } public boolean hasCorrelationParameterValues() { return correlationParameterValues.size() > 0; } public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues; } @Override public void migrateToLatestProcessDefinition() { checkValidInformation(); runtimeService.migrateProcessInstanceStartEventSubscriptionsToProcessDefinitionVersion(this); } @Override public void migrateToProcessDefinition(String processDefinitionId) { this.newProcessDefinitionId = processDefinitionId; checkValidInformation(); runtimeService.migrateProcessInstanceStartEventSubscriptionsToProcessDefinitionVersion(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionId)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the exact id of the version the subscription was registered for."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionModificationBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ElementValueId implements RepoIdAware { @JsonCreator @NonNull public static ElementValueId ofRepoId(final int repoId) { return new ElementValueId(repoId); } @Nullable public static ElementValueId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } int repoId; private ElementValueId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "C_ElementValue_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final ElementValueId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(@Nullable final ElementValueId id1, @Nullable final ElementValueId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\ElementValueId.java
2
请完成以下Java代码
private static Timestamp getPreparationTime(final I_M_TourVersion tourVersion, final int dayOfWeek) { Check.assumeNotNull(tourVersion, "tourVersion not null"); final Timestamp preparationTime; if (dayOfWeek == Calendar.MONDAY) { preparationTime = tourVersion.getPreparationTime_1(); } else if (dayOfWeek == Calendar.TUESDAY) { preparationTime = tourVersion.getPreparationTime_2(); } else if (dayOfWeek == Calendar.WEDNESDAY) { preparationTime = tourVersion.getPreparationTime_3(); } else if (dayOfWeek == Calendar.THURSDAY) { preparationTime = tourVersion.getPreparationTime_4(); } else if (dayOfWeek == Calendar.FRIDAY) { preparationTime = tourVersion.getPreparationTime_5(); } else if (dayOfWeek == Calendar.SATURDAY) { preparationTime = tourVersion.getPreparationTime_6(); } else if (dayOfWeek == Calendar.SUNDAY) { preparationTime = tourVersion.getPreparationTime_7(); } else { throw new IllegalArgumentException("Invalid day of week: " + dayOfWeek); } return preparationTime; } @Override public Timestamp getPreparationDateTime(final I_M_TourVersion tourVersion, final Date deliveryDate) { Check.assumeNotNull(tourVersion, "tourVersion not null"); Check.assumeNotNull(deliveryDate, "deliveryDate not null");
// // Get DeliveryDate's Day of the Week final GregorianCalendar deliveryDateCal = new GregorianCalendar(); deliveryDateCal.setTimeInMillis(deliveryDate.getTime()); final int deliveryDayOfWeek = deliveryDateCal.get(Calendar.DAY_OF_WEEK); final Timestamp preparationTime = getPreparationTime(tourVersion, deliveryDayOfWeek); if (preparationTime == null) { return null; } final Timestamp preparationDateTime = TimeUtil.getDayTime(deliveryDate, preparationTime); return preparationDateTime; } @Override public IDeliveryDayGenerator createDeliveryDayGenerator(final IContextAware context) { return new DeliveryDayGenerator(context); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourBL.java
1
请完成以下Java代码
public <T extends RepoIdAware> T toId(@NonNull final IntFunction<T> mapper) { return mapper.apply(toInt()); } private static final class IntDocumentId extends DocumentId { private final int idInt; private IntDocumentId(final int idInt) { super(); this.idInt = idInt; } @Override public String toJson() { if (idInt == NEW_ID) { return NEW_ID_STRING; } return String.valueOf(idInt); } @Override public int hashCode() { return Objects.hash(idInt); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof IntDocumentId)) { return false; } final IntDocumentId other = (IntDocumentId)obj; return idInt == other.idInt; } @Override public boolean isInt() { return true; } @Override public int toInt() { return idInt; } @Override public boolean isNew() { return idInt == NEW_ID; } @Override public boolean isComposedKey() { return false; } @Override public List<Object> toComposedKeyParts() { return ImmutableList.of(idInt); } } private static final class StringDocumentId extends DocumentId { private final String idStr;
private StringDocumentId(final String idStr) { Check.assumeNotEmpty(idStr, "idStr is not empty"); this.idStr = idStr; } @Override public String toJson() { return idStr; } @Override public int hashCode() { return Objects.hash(idStr); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof StringDocumentId)) { return false; } final StringDocumentId other = (StringDocumentId)obj; return Objects.equals(idStr, other.idStr); } @Override public boolean isInt() { return false; } @Override public int toInt() { if (isComposedKey()) { throw new AdempiereException("Composed keys cannot be converted to int: " + this); } else { throw new AdempiereException("String document IDs cannot be converted to int: " + this); } } @Override public boolean isNew() { return false; } @Override public boolean isComposedKey() { return idStr.contains(COMPOSED_KEY_SEPARATOR); } @Override public List<Object> toComposedKeyParts() { final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder(); COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add); return composedKeyParts.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java
1
请完成以下Java代码
public String getApplicationName() { return this.applicationName; } /** * Sets the application name. * @param applicationName the application name */ public void setApplicationName(String applicationName) { this.applicationName = applicationName; } @Override public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return this.groupId + "." + this.artifactId; } return null; } /** * Sets the package name. * @param packageName the package name */ public void setPackageName(String packageName) { this.packageName = packageName; }
@Override public String getBaseDirectory() { return this.baseDirectory; } /** * Sets the base directory. * @param baseDirectory the base directory */ public void setBaseDirectory(String baseDirectory) { this.baseDirectory = baseDirectory; } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java
1
请完成以下Java代码
public class LwM2MServerBootstrap { String clientPublicKeyOrId = ""; String clientSecretKey = ""; String serverPublicKey = ""; Integer clientHoldOffTime = 1; Integer bootstrapServerAccountTimeout = 0; String host = "0.0.0.0"; Integer port = 0; String securityHost = "0.0.0.0"; Integer securityPort = 0; SecurityMode securityMode = SecurityMode.NO_SEC; Integer serverId = 123; boolean bootstrapServerIs = false; public LwM2MServerBootstrap() { }
public LwM2MServerBootstrap(LwM2MServerBootstrap bootstrapFromCredential, LwM2MServerBootstrap profileServerBootstrap) { this.clientPublicKeyOrId = bootstrapFromCredential.getClientPublicKeyOrId(); this.clientSecretKey = bootstrapFromCredential.getClientSecretKey(); this.serverPublicKey = profileServerBootstrap.getServerPublicKey(); this.clientHoldOffTime = profileServerBootstrap.getClientHoldOffTime(); this.bootstrapServerAccountTimeout = profileServerBootstrap.getBootstrapServerAccountTimeout(); this.host = (profileServerBootstrap.getHost().equals("0.0.0.0")) ? "localhost" : profileServerBootstrap.getHost(); this.port = profileServerBootstrap.getPort(); this.securityHost = (profileServerBootstrap.getSecurityHost().equals("0.0.0.0")) ? "localhost" : profileServerBootstrap.getSecurityHost(); this.securityPort = profileServerBootstrap.getSecurityPort(); this.securityMode = profileServerBootstrap.getSecurityMode(); this.serverId = profileServerBootstrap.getServerId(); this.bootstrapServerIs = profileServerBootstrap.bootstrapServerIs; } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\secure\LwM2MServerBootstrap.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<String> getProductGroupIdentifierByProductId(@NonNull final ProductId productId) { final I_M_Product product = productDAO.getById(productId); final ExternalSystem externalSystem = externalSystemRepository.getByType(ExternalSystemType.Alberta); final GetExternalReferenceByRecordIdReq getExternalReferenceByRecordIdReq = GetExternalReferenceByRecordIdReq.builder() .recordId(product.getM_Product_Category_ID()) .externalSystem(externalSystem) .externalReferenceType(ProductCategoryExternalReferenceType.PRODUCT_CATEGORY) .build(); return externalReferenceRepository.getExternalReferenceByMFReference(getExternalReferenceByRecordIdReq) .map(ExternalReference::getExternalReference); }
@NonNull private Optional<String> getAlbertaArticleIdByProductId(@NonNull final ProductId productId) { final ExternalSystem externalSystem = externalSystemRepository.getByType(ExternalSystemType.Alberta); final GetExternalReferenceByRecordIdReq getExternalReferenceByRecordIdReq = GetExternalReferenceByRecordIdReq.builder() .recordId(productId.getRepoId()) .externalSystem(externalSystem) .externalReferenceType(ProductExternalReferenceType.PRODUCT) .build(); return externalReferenceRepository.getExternalReferenceByMFReference(getExternalReferenceByRecordIdReq) .map(ExternalReference::getExternalReference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\service\AlbertaProductService.java
2
请完成以下Java代码
protected String getImportOrderBySql() { return I_I_Pharma_Product.COLUMNNAME_A01GDAT; } @Override public I_I_Pharma_Product retrieveImportRecord(final Properties ctx, final ResultSet rs) { return new X_I_Pharma_Product(ctx, rs, ITrx.TRXNAME_ThreadInherited); } @Override protected void updateAndValidateImportRecordsImpl() { final ImportRecordsSelection selection = getImportRecordsSelection(); MProductImportTableSqlUpdater.builder() .selection(selection) .ctx(getCtx()) .tableName(getImportTableName()) .valueName(I_I_Pharma_Product.COLUMNNAME_A00PZN) .build() .updateIPharmaProduct(); } @Override protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state, @NonNull final I_I_Pharma_Product importRecord, final boolean isInsertOnly) throws Exception { final org.compiere.model.I_M_Product existentProduct = productDAO.retrieveProductByValue(importRecord.getA00PZN()); final String operationCode = importRecord.getA00SSATZ(); if (DEACTIVATE_OPERATION_CODE.equals(operationCode) && existentProduct != null) { IFAProductImportHelper.deactivateProduct(existentProduct); return ImportRecordResult.Updated; } else if (!DEACTIVATE_OPERATION_CODE.equals(operationCode)) { final I_M_Product product; final boolean newProduct = existentProduct == null || importRecord.getM_Product_ID() <= 0; if (!newProduct && isInsertOnly) { // #4994 do not update entries return ImportRecordResult.Nothing; } if (newProduct)
{ product = IFAProductImportHelper.createProduct(importRecord); } else { product = IFAProductImportHelper.updateProduct(importRecord, existentProduct); } importRecord.setM_Product_ID(product.getM_Product_ID()); ModelValidationEngine.get().fireImportValidate(this, importRecord, importRecord.getM_Product(), IImportInterceptor.TIMING_AFTER_IMPORT); IFAProductImportHelper.importPrices(importRecord, true); return newProduct ? ImportRecordResult.Inserted : ImportRecordResult.Updated; } return ImportRecordResult.Nothing; } @Override protected void markImported(@NonNull final I_I_Pharma_Product importRecord) { //set this to Yes because in initial import we don't want the prices to be copied importRecord.setIsPriceCopied(true); importRecord.setI_IsImported(X_I_Pharma_Product.I_ISIMPORTED_Imported); importRecord.setProcessed(true); InterfaceWrapperHelper.save(importRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\IFAInitialImportProcess2.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getOrderLine() { return orderLine; } /** * Sets the value of the orderLine property. * * @param value * allowed object is * {@link BigInteger } * */ public void setOrderLine(BigInteger value) { this.orderLine = value; } /** * Gets the value of the externalSeqNo property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getExternalSeqNo() { return externalSeqNo; } /** * Sets the value of the externalSeqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setExternalSeqNo(BigInteger value) { this.externalSeqNo = value; } /** * Gets the value of the cuombPartnerID property. * * @return * possible object is * {@link EDIExpCUOMType } * */ public EDIExpCUOMType getCUOMBPartnerID() { return cuombPartnerID; } /** * Sets the value of the cuombPartnerID property. * * @param value * allowed object is * {@link EDIExpCUOMType } * */ public void setCUOMBPartnerID(EDIExpCUOMType value) { this.cuombPartnerID = value; } /** * Gets the value of the qtyEnteredInBPartnerUOM property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getQtyEnteredInBPartnerUOM() { return qtyEnteredInBPartnerUOM; } /** * Sets the value of the qtyEnteredInBPartnerUOM property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setQtyEnteredInBPartnerUOM(BigDecimal value) { this.qtyEnteredInBPartnerUOM = value; } /** * Gets the value of the bPartnerQtyItemCapacity property. * * @return
* possible object is * {@link BigDecimal } * */ public BigDecimal getBPartnerQtyItemCapacity() { return bPartnerQtyItemCapacity; } /** * Sets the value of the bPartnerQtyItemCapacity property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setBPartnerQtyItemCapacity(BigDecimal value) { this.bPartnerQtyItemCapacity = value; } /** * Gets the value of the upctu property. * * @return * possible object is * {@link String } * */ public String getUPCTU() { return upctu; } /** * Sets the value of the upctu property. * * @param value * allowed object is * {@link String } * */ public void setUPCTU(String value) { this.upctu = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvLineType.java
2
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ @Override public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ @Override public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class); } @Override public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory) { set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory); }
/** Set Status Category. @param R_StatusCategory_ID Request Status Category */ @Override public void setR_StatusCategory_ID (int R_StatusCategory_ID) { if (R_StatusCategory_ID < 1) set_Value (COLUMNNAME_R_StatusCategory_ID, null); else set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID)); } /** Get Status Category. @return Request Status Category */ @Override public int getR_StatusCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestType.java
1
请完成以下Java代码
public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public boolean isTenantIdSet() { return isTenantIdSet; } public List<HistoricTaskInstanceQueryImpl> getQueries() { return queries; } public boolean isOrQueryActive() { return isOrQueryActive; } public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; }
@Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请完成以下Java代码
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (getExternalSystemParam().equals(parameter.getColumnName())) { final ImmutableList<ExternalSystemParentConfig> activeConfigs = externalSystemConfigRepo.getActiveByType(getExternalSystemType()) .stream() .collect(ImmutableList.toImmutableList()); return activeConfigs.size() == 1 ? activeConfigs.get(0).getChildConfig().getId().getRepoId() : IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { final Optional<ProcessPreconditionsResolution> customPreconditions = applyCustomPreconditionsIfAny(context); if (customPreconditions.isPresent()) { return customPreconditions.get(); } if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { addLog("Calling with params: externalSystemChildConfigId: {}", getExternalSystemChildConfigId()); final Iterator<I_C_BPartner> bPartnerIterator = getSelectedBPartnerRecords(); final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId(); while (bPartnerIterator.hasNext()) { final TableRecordReference bPartnerRecordRef = TableRecordReference.of(bPartnerIterator.next()); getExportToBPartnerExternalSystem().exportToExternalSystem(externalSystemChildConfigId, bPartnerRecordRef, getPinstanceId()); } return JavaProcess.MSG_OK;
} @NonNull private Iterator<I_C_BPartner> getSelectedBPartnerRecords() { final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class); return bPartnerQuery .create() .iterate(I_C_BPartner.class); } protected Optional<ProcessPreconditionsResolution> applyCustomPreconditionsIfAny(final @NonNull IProcessPreconditionsContext context) { return Optional.empty(); } protected abstract ExternalSystemType getExternalSystemType(); protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId(); protected abstract String getExternalSystemParam(); protected abstract ExportToExternalSystemService getExportToBPartnerExternalSystem(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\bpartner\C_BPartner_SyncTo_ExternalSystem.java
1
请完成以下Java代码
public int getCM_WebProject_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Fully Qualified Domain Name. @param FQDN Fully Qualified Domain Name i.e. www.comdivision.com */ public void setFQDN (String FQDN) { set_Value (COLUMNNAME_FQDN, FQDN); } /** Get Fully Qualified Domain Name. @return Fully Qualified Domain Name i.e. www.comdivision.com */ public String getFQDN () { return (String)get_Value(COLUMNNAME_FQDN); }
/** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject_Domain.java
1
请在Spring Boot框架中完成以下Java代码
public void setAreas(String areas) { this.areas = areas; } public String getBankAccountName() { return bankAccountName; } public void setBankAccountName(String bankAccountName) { this.bankAccountName = bankAccountName; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getBankAccountType() { return bankAccountType; } public void setBankAccountType(String bankAccountType) { this.bankAccountType = bankAccountType; } public String getCardType() { return cardType; } public void setCardType(String cardType) { this.cardType = cardType; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public String getBankCode() { return bankCode; } public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getUserNo() { return userNo; }
public void setUserNo(String userNo) { this.userNo = userNo; } public String getCvn2() { return cvn2; } public void setCvn2(String cvn2) { this.cvn2 = cvn2; } public String getExpDate() { return expDate; } public void setExpDate(String expDate) { this.expDate = expDate; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } public String getIsAuth() { return isAuth; } public void setIsAuth(String isAuth) { this.isAuth = isAuth; } public String getStatusDesc() { if (StringUtil.isEmpty(this.getStatus())) { return ""; } else { return PublicStatusEnum.getEnum(this.getStatus()).getDesc(); } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserQuickPayBankAccount.java
2
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } DefaultOAuth2User that = (DefaultOAuth2User) obj; if (!this.getName().equals(that.getName())) { return false; } if (!this.getAuthorities().equals(that.getAuthorities())) { return false; } return this.getAttributes().equals(that.getAttributes()); } @Override public int hashCode() { int result = this.getName().hashCode();
result = 31 * result + this.getAuthorities().hashCode(); result = 31 * result + this.getAttributes().hashCode(); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ["); sb.append(this.getName()); sb.append("], Granted Authorities: ["); sb.append(getAuthorities()); sb.append("], User Attributes: ["); sb.append(getAttributes()); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\user\DefaultOAuth2User.java
1
请在Spring Boot框架中完成以下Java代码
public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.notNull(authentication, "No authentication data provided"); RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials(); SecurityUser unsafeUser = tokenFactory.parseRefreshToken(rawAccessToken.token()); UserPrincipal principal = unsafeUser.getUserPrincipal(); SecurityUser securityUser; if (principal.getType() == UserPrincipal.Type.USER_NAME) { securityUser = authenticateByUserId(TenantId.SYS_TENANT_ID, unsafeUser.getId()); } else { securityUser = authenticateByPublicId(principal.getValue()); } securityUser.setSessionId(unsafeUser.getSessionId()); if (tokenOutdatingService.isOutdated(rawAccessToken.token(), securityUser.getId())) { throw new CredentialsExpiredException("Token is outdated");
} return new RefreshAuthenticationToken(securityUser); } private SecurityUser authenticateByPublicId(String publicId) { return super.authenticateByPublicId(publicId, "Refresh token", null); } @Override public boolean supports(Class<?> authentication) { return (RefreshAuthenticationToken.class.isAssignableFrom(authentication)); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\RefreshTokenAuthenticationProvider.java
2
请完成以下Java代码
private void createPrintPackage0(final I_C_Print_Package printPackage, final I_C_Print_Job_Instructions jobInstructions, final IPrintPackageCtx printPackageCtx, final String trxName) { final String jobInstructionsTrxName = InterfaceWrapperHelper.getTrxName(jobInstructions); final ITrxManager trxManager = Services.get(ITrxManager.class); Check.assume(trxManager.isSameTrxName(trxName, jobInstructionsTrxName), "Same transaction (Param 'trxName': {}, jobInstructions' trxName: {}; jobInstructions={})", trxName, jobInstructionsTrxName, jobInstructions); printPackage.setCopies(jobInstructions.getCopies()); final IPrintJobLinesAggregator aggregator = createPrintJobLinesAggregator(printPackageCtx, jobInstructions); aggregator.setPrintPackageToUse(printPackage); final Mutable<ArrayKey> lastKey = new Mutable<>(); final Iterator<I_C_Print_Job_Line> jobLines = Services.get(IPrintingDAO.class).retrievePrintJobLines(jobInstructions); for (final I_C_Print_Job_Line jobLine : IteratorUtils.asIterable(jobLines)) { aggregator.add(jobLine, lastKey); } final I_C_Print_Package printPackageCreated = aggregator.createPrintPackage(); Check.assumeNotNull(printPackageCreated, "Print package created for {}", jobInstructions); InterfaceWrapperHelper.save(printPackage); } protected IPrintJobLinesAggregator createPrintJobLinesAggregator( @NonNull final IPrintPackageCtx printPackageCtx, @NonNull final I_C_Print_Job_Instructions jobInstructions) { return new PrintJobLinesAggregator(printingDataFactory, printPackageCtx, jobInstructions); } @Override
public IPrintPackageCtx createEmptyInitialCtx() { return new PrintPackageCtx(); } @Override public IPrintPackageCtx createInitialCtx(@NonNull final Properties ctx) { final PrintPackageCtx printCtx = new PrintPackageCtx(); final MFSession session = Services.get(ISessionBL.class).getCurrentSession(ctx); if (session == null) { throw new AdempiereException("The given ctx has no session.") .appendParametersToMessage() .setParameter("ctx", ctx); } logger.debug("Session: {}", session); final String hostKey = session.getOrCreateHostKey(ctx); Check.assumeNotEmpty(hostKey, "{} has a hostKey", session); printCtx.setHostKey(hostKey); logger.debug("Print package context: {}", printCtx); return printCtx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintPackageBL.java
1
请完成以下Java代码
public class Activator implements BundleActivator { private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class); private List<Runnable> callbacks = new ArrayList<>(); @Override public void start(BundleContext context) throws Exception { callbacks.add(new Service(context, URLStreamHandlerService.class.getName(), new BpmnURLHandler(), props("url.handler.protocol", "bpmn"))); callbacks.add(new Service(context, URLStreamHandlerService.class.getName(), new BarURLHandler(), props("url.handler.protocol", "bar"))); try { callbacks.add(new Service(context, new String[]{ArtifactUrlTransformer.class.getName(), ArtifactListener.class.getName()}, new BpmnDeploymentListener(), null)); callbacks.add(new Service(context, new String[]{ArtifactUrlTransformer.class.getName(), ArtifactListener.class.getName()}, new BarDeploymentListener(), null)); } catch (NoClassDefFoundError e) { LOGGER.warn("FileInstall package is not available, disabling fileinstall support"); LOGGER.debug("FileInstall package is not available, disabling fileinstall support", e); } callbacks.add(new Tracker(new Extender(context))); } @Override public void stop(BundleContext context) throws Exception { for (Runnable r : callbacks) { r.run(); } } private static Dictionary<String, String> props(String... args) { Dictionary<String, String> props = new Hashtable<>(); for (int i = 0; i < args.length / 2; i++) { props.put(args[2 * i], args[2 * i + 1]); } return props; } @SuppressWarnings({"rawtypes"}) private static class Service implements Runnable { private final ServiceRegistration registration; public Service(BundleContext context, String clazz, Object service, Dictionary props) { this.registration = context.registerService(clazz, service, props); } public Service(BundleContext context, String[] clazz, Object service, Dictionary props) { this.registration = context.registerService(clazz, service, props); }
@Override public void run() { registration.unregister(); } } private static class Tracker implements Runnable { private final Extender extender; private Tracker(Extender extender) { this.extender = extender; this.extender.open(); } @Override public void run() { extender.close(); } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\Activator.java
1
请在Spring Boot框架中完成以下Java代码
public String getSalesOrderDocumentNo(@NonNull final OrderId salesOrderId) { return salesOrderDocumentNosCache.computeIfAbsent(salesOrderId, orderService::getDocumentNoById); } @Override public void warmUpBPartnerNamesCache(@NonNull final Set<BPartnerId> bpartnerIds) { CollectionUtils.getAllOrLoad(bpartnerNamesCache, bpartnerIds, bpartnerService::getBPartnerNames); } @Override public String getBPartnerName(@NonNull final BPartnerId bpartnerId) { return bpartnerNamesCache.computeIfAbsent(bpartnerId, bpartnerService::getBPartnerName); } @Override public ZonedDateTime toZonedDateTime(@NonNull final java.sql.Timestamp timestamp, @NonNull final OrgId orgId) { final ZoneId zoneId = orgDAO.getTimeZone(orgId); return TimeUtil.asZonedDateTime(timestamp, zoneId); } @Override public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotIdAndCaptionsCache.computeIfAbsent(pickingSlotId, pickingSlotService::getPickingSlotIdAndCaption); } @Override public String getProductNo(@NonNull final ProductId productId) { return getProductInfo(productId).getProductNo(); } @Override public Optional<GS1ProductCodes> getGS1ProductCodes(@NonNull final ProductId productId, @Nullable final BPartnerId customerId) { return getProductInfo(productId).getGs1ProductCodes().getEffectiveCodes(customerId); } @Override public ProductCategoryId getProductCategoryId(@NonNull final ProductId productId) { return getProductInfo(productId).getProductCategoryId(); } @Override
public ITranslatableString getProductName(@NonNull final ProductId productId) { return getProductInfo(productId).getName(); } private ProductInfo getProductInfo(@NonNull final ProductId productId) { return productInfoCache.computeIfAbsent(productId, productService::getById); } @Override public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId) { return huService.getPackingInfo(huPIItemProductId); } @Override public String getPICaption(@NonNull final HuPackingInstructionsId piId) { return huService.getPI(piId).getName(); } @Override public String getLocatorName(@NonNull final LocatorId locatorId) { return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById); } @Override public HUQRCode getQRCodeByHUId(final HuId huId) { return huService.getQRCodeByHuId(huId); } @Override public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return pickingJobLockService.getLocks(scheduleIds); } @Override public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId) { return orderService.getSalesOrderLineSeqNo(orderAndLineId); } // // // }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
2
请完成以下Java代码
public final class DefaultViewInvalidationAdvisor implements IViewInvalidationAdvisor { public static final DefaultViewInvalidationAdvisor instance = new DefaultViewInvalidationAdvisor(); private DefaultViewInvalidationAdvisor() { } @Override public WindowId getWindowId() { // this method shall never be called throw new UnsupportedOperationException(); } @Override public Set<DocumentId> findAffectedRowIds(
@NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend, @NonNull IView view) { final String viewTableName = view.getTableNameOrNull(); if (viewTableName == null) { return ImmutableSet.of(); } return recordRefs.streamByTableName(viewTableName) .map(recordRef -> DocumentId.of(recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\DefaultViewInvalidationAdvisor.java
1
请完成以下Java代码
public KafkaStreamBrancher<K, V> defaultBranch(Consumer<? super KStream<K, V>> consumer) { this.defaultConsumer = Objects.requireNonNull(consumer); return this; } /** * Terminating method that builds branches on top of given {@code KStream}. * Applies each predicate-consumer pair sequentially to create branches. * If a default consumer exists, it will handle all records that don't match any predicates. * @param stream {@code KStream} to split * @return the processed stream * @throws NullPointerException if stream is null * @throws IllegalStateException if number of predicates doesn't match number of consumers */ public KStream<K, V> onTopOf(KStream<K, V> stream) { if (this.defaultConsumer != null) { this.predicateList.add((k, v) -> true); this.consumerList.add(this.defaultConsumer); } // Validate predicate and consumer lists match
if (this.predicateList.size() != this.consumerList.size()) { throw new IllegalStateException("Number of predicates (" + this.predicateList.size() + ") must match number of consumers (" + this.consumerList.size() + ")"); } BranchedKStream<K, V> branchedKStream = stream.split(); Iterator<Consumer<? super KStream<K, V>>> consumerIterator = this.consumerList.iterator(); // Process each predicate-consumer pair for (Predicate<? super K, ? super V> predicate : this.predicateList) { branchedKStream = branchedKStream.branch(predicate, Branched.withConsumer(adaptConsumer(consumerIterator.next()))); } return stream; } private Consumer<KStream<K, V>> adaptConsumer(Consumer<? super KStream<K, V>> consumer) { return consumer::accept; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\KafkaStreamBrancher.java
1
请完成以下Java代码
class BankAccount { String name; LocalDateTime opened; double balance; @Override public String toString() { return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance); } public String getName() { return name; } public LocalDateTime getOpened() { return opened; } public double getBalance() { return this.balance; } } class BankAccountEmptyConstructor extends BankAccount { public BankAccountEmptyConstructor() { this.name = ""; this.opened = LocalDateTime.now(); this.balance = 0.0d; } } class BankAccountParameterizedConstructor extends BankAccount { public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) { this.name = name; this.opened = opened; this.balance = balance; }
} class BankAccountCopyConstructor extends BankAccount { public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) { this.name = name; this.opened = opened; this.balance = balance; } public BankAccountCopyConstructor(BankAccount other) { this.name = other.name; this.opened = LocalDateTime.now(); this.balance = 0.0f; } } class BankAccountChainedConstructors extends BankAccount { public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) { this.name = name; this.opened = opened; this.balance = balance; } public BankAccountChainedConstructors(String name) { this(name, LocalDateTime.now(), 0.0f); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\constructors\BankAccount.java
1
请在Spring Boot框架中完成以下Java代码
public class RuleChainExportService extends BaseEntityExportService<RuleChainId, RuleChain, RuleChainExportData> { private final RuleChainService ruleChainService; @Override protected void setRelatedEntities(EntitiesExportCtx<?> ctx, RuleChain ruleChain, RuleChainExportData exportData) { RuleChainMetaData metaData = ruleChainService.loadRuleChainMetaData(ctx.getTenantId(), ruleChain.getId()); Optional.ofNullable(metaData.getNodes()).orElse(Collections.emptyList()) .forEach(ruleNode -> { ruleNode.setRuleChainId(null); ctx.putExternalId(ruleNode.getId(), ruleNode.getExternalId()); ruleNode.setId(ctx.getExternalId(ruleNode.getId())); ruleNode.setCreatedTime(0); ruleNode.setExternalId(null); replaceUuidsRecursively(ctx, ruleNode.getConfiguration(), Collections.emptySet(), PROCESSED_CONFIG_FIELDS_PATTERN); }); Optional.ofNullable(metaData.getRuleChainConnections()).orElse(Collections.emptyList()) .forEach(ruleChainConnectionInfo -> { ruleChainConnectionInfo.setTargetRuleChainId(getExternalIdOrElseInternal(ctx, ruleChainConnectionInfo.getTargetRuleChainId())); });
exportData.setMetaData(metaData); if (ruleChain.getFirstRuleNodeId() != null) { ruleChain.setFirstRuleNodeId(ctx.getExternalId(ruleChain.getFirstRuleNodeId())); } } @Override protected RuleChainExportData newExportData() { return new RuleChainExportData(); } @Override public Set<EntityType> getSupportedEntityTypes() { return Set.of(EntityType.RULE_CHAIN); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\exporting\impl\RuleChainExportService.java
2
请完成以下Java代码
public boolean isDefaultLU() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "inbound", allowableValues = "inbound,outbound") public String getType() { return type; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "kafka") public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } @ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "2") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2") public String getDeploymentUrl() { return deploymentUrl; }
public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "oneChannel.channel") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneChannel.channel", value = "Contains the actual deployed channel definition JSON.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a channel definition for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResponse.java
2
请完成以下Java代码
public String getProductCategoryName() { return productCategoryName; } public void setProductCategoryName(String productCategoryName) { this.productCategoryName = productCategoryName; } public String getParentCategoryName() { return parentCategoryName; } public void setParentCategoryName(String parentCategoryName) { this.parentCategoryName = parentCategoryName; } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", couponId=").append(couponId); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", productCategoryName=").append(productCategoryName); sb.append(", parentCategoryName=").append(parentCategoryName); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponProductCategoryRelation.java
1
请完成以下Java代码
public class JsonRequestProductPrice { @ApiModelProperty(required = true) private String orgCode; @ApiModelProperty(required = true, value = PRODUCT_IDENTIFIER) private String productIdentifier; @ApiModelProperty(required = true) private TaxCategory taxCategory; @ApiModelProperty(required = true) private BigDecimal priceStd; private BigDecimal priceLimit; @ApiModelProperty(hidden = true) private boolean priceLimitSet; private BigDecimal priceList; @ApiModelProperty(hidden = true) private boolean priceListSet; private Integer seqNo; @ApiModelProperty(hidden = true) private boolean seqNoSet; private Boolean active; @ApiModelProperty(hidden = true) private boolean activeSet; private SyncAdvise syncAdvise; @ApiModelProperty(hidden = true) private boolean syncAdviseSet; @ApiModelProperty private String uomCode; @ApiModelProperty(hidden = true) private boolean uomCodeSet; public void setOrgCode(final String orgCode) { this.orgCode = orgCode; } public void setProductIdentifier(final String productId) { this.productIdentifier = productId; } public void setPriceLimit(final BigDecimal priceLimit) { this.priceLimit = priceLimit; this.priceLimitSet = true; } public void setPriceList(final BigDecimal priceList) { this.priceList = priceList; this.priceListSet = true; } public void setPriceStd(final BigDecimal priceStd) { this.priceStd = priceStd; } public void setSeqNo(final Integer seqNo) { this.seqNo = seqNo; this.seqNoSet = true; }
public void setTaxCategory(final TaxCategory taxCategory) { this.taxCategory = taxCategory; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setUomCode(final String uomCode) { this.uomCode = uomCode; this.uomCodeSet = true; } @NonNull public String getOrgCode() { return orgCode; } @NonNull public String getProductIdentifier() { return productIdentifier; } @NonNull public TaxCategory getTaxCategory() { return taxCategory; } @NonNull public BigDecimal getPriceStd() { return priceStd; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-pricing\src\main\java\de\metas\common\pricing\v2\productprice\JsonRequestProductPrice.java
1
请在Spring Boot框架中完成以下Java代码
public List<GenericEntity> findAll() { return entityList; } @PostMapping("/entity") public GenericEntity addEntity(GenericEntity entity) { entityList.add(entity); return entity; } @GetMapping("/entity/findby/{id}") public GenericEntity findById(@PathVariable Long id) { return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); }
@GetMapping("/entity/findbydate/{date}") public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { return entityList.stream().findFirst().get(); } @GetMapping("/entity/findbymode/{mode}") public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { return entityList.stream().findFirst().get(); } @GetMapping("/entity/findbyversion") public ResponseEntity findByVersion(@Version String version) { return version != null ? new ResponseEntity<>(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-3\src\main\java\com\baeldung\boot\controller\GenericEntityController.java
2
请在Spring Boot框架中完成以下Java代码
public DeploymentBuilder name(String name) { deployment.setName(name); return this; } public DeploymentBuilder category(String category) { deployment.setCategory(category); return this; } public DeploymentBuilder key(String key) { deployment.setKey(key); return this; } public DeploymentBuilder disableBpmnValidation() { this.isProcessValidationEnabled = false; return this; } public DeploymentBuilder disableSchemaValidation() { this.isBpmn20XsdValidationEnabled = false; return this; } public DeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; } public DeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this; } public DeploymentBuilder activateProcessDefinitionsOn(Date date) { this.processDefinitionsActivationDate = date; return this; } @Override public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) { deploymentProperties.put(propertyKey, propertyValue);
return this; } public Deployment deploy() { return repositoryService.deploy(this); } // getters and setters // ////////////////////////////////////////////////////// public DeploymentEntity getDeployment() { return deployment; } public boolean isProcessValidationEnabled() { return isProcessValidationEnabled; } public boolean isBpmn20XsdValidationEnabled() { return isBpmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } public Date getProcessDefinitionsActivationDate() { return processDefinitionsActivationDate; } public Map<String, Object> getDeploymentProperties() { return deploymentProperties; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java
2
请完成以下Java代码
public class Document { @XmlElement(name = "CstmrCdtTrfInitn", required = true) protected CustomerCreditTransferInitiationV03CH cstmrCdtTrfInitn; /** * Gets the value of the cstmrCdtTrfInitn property. * * @return * possible object is * {@link CustomerCreditTransferInitiationV03CH } * */ public CustomerCreditTransferInitiationV03CH getCstmrCdtTrfInitn() { return cstmrCdtTrfInitn;
} /** * Sets the value of the cstmrCdtTrfInitn property. * * @param value * allowed object is * {@link CustomerCreditTransferInitiationV03CH } * */ public void setCstmrCdtTrfInitn(CustomerCreditTransferInitiationV03CH value) { this.cstmrCdtTrfInitn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\Document.java
1
请完成以下Java代码
public Descriptors.Descriptor getRpcResponseDynamicMessageDescriptor(String deviceRpcResponseProtoSchema) { return DynamicProtoUtils.getDescriptor(deviceRpcResponseProtoSchema, RPC_RESPONSE_PROTO_SCHEMA); } public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder(String deviceRpcRequestProtoSchema) { return DynamicProtoUtils.getDynamicMessageBuilder(deviceRpcRequestProtoSchema, RPC_REQUEST_PROTO_SCHEMA); } public String getDeviceRpcResponseProtoSchema() { if (StringUtils.isNotEmpty(deviceRpcResponseProtoSchema)) { return deviceRpcResponseProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcResponseMsg {\n" + " optional string payload = 1;\n" + "}"; }
} public String getDeviceRpcRequestProtoSchema() { if (StringUtils.isNotEmpty(deviceRpcRequestProtoSchema)) { return deviceRpcRequestProtoSchema; } else { return "syntax =\"proto3\";\n" + "package rpc;\n" + "\n" + "message RpcRequestMsg {\n" + " optional string method = 1;\n" + " optional int32 requestId = 2;\n" + " optional string params = 3;\n" + "}"; } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\profile\ProtoTransportPayloadConfiguration.java
1
请完成以下Java代码
public void setM_SerNoCtlExclude_ID (int M_SerNoCtlExclude_ID) { if (M_SerNoCtlExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_SerNoCtlExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_SerNoCtlExclude_ID, Integer.valueOf(M_SerNoCtlExclude_ID)); } /** Get Exclude SerNo. @return Exclude the ability to create Serial Numbers in Attribute Sets */ public int getM_SerNoCtlExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtlExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_SerNoCtl getM_SerNoCtl() throws RuntimeException { return (I_M_SerNoCtl)MTable.get(getCtx(), I_M_SerNoCtl.Table_Name) .getPO(getM_SerNoCtl_ID(), get_TrxName()); } /** Set Serial No Control. @param M_SerNoCtl_ID Product Serial Number Control */ public void setM_SerNoCtl_ID (int M_SerNoCtl_ID) {
if (M_SerNoCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID)); } /** Get Serial No Control. @return Product Serial Number Control */ public int getM_SerNoCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtlExclude.java
1
请在Spring Boot框架中完成以下Java代码
public static class FTSConfigsMap { @Getter private final ImmutableList<FTSConfig> configs; private final ImmutableMap<String, FTSConfig> configsByESIndexName; private final ImmutableMap<FTSConfigId, FTSConfig> configsById; @Getter private final FTSConfigSourceTablesMap sourceTables; private FTSConfigsMap( @NonNull final List<FTSConfig> configs, @NonNull final FTSConfigSourceTablesMap sourceTables) { this.configs = ImmutableList.copyOf(configs); this.configsByESIndexName = Maps.uniqueIndex(configs, FTSConfig::getEsIndexName); this.configsById = Maps.uniqueIndex(configs, FTSConfig::getId); this.sourceTables = sourceTables .filter(sourceTable -> configsById.containsKey(sourceTable.getFtsConfigId())); // only active configs
} public Optional<FTSConfig> getByESIndexName(@NonNull final String esIndexName) { return Optional.ofNullable(configsByESIndexName.get(esIndexName)); } public FTSConfig getById(@NonNull final FTSConfigId ftsConfigId) { final FTSConfig config = configsById.get(ftsConfigId); if (config == null) { throw new AdempiereException("No config found for " + ftsConfigId); } return config; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigRepository.java
2
请完成以下Java代码
public class DateIntervalIntersectionQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter { @NonNull private final ModelColumnNameValue<T> lowerBoundColumnName; @NonNull private final ModelColumnNameValue<T> upperBoundColumnName; @Nullable private final Instant lowerBoundValue; @Nullable private final Instant upperBoundValue; private String sqlWhereClause; // lazy private List<Object> sqlParams; // lazy public DateIntervalIntersectionQueryFilter( @NonNull final ModelColumnNameValue<T> lowerBoundColumnName, @NonNull final ModelColumnNameValue<T> upperBoundColumnName, @Nullable final Instant lowerBoundValue, @Nullable final Instant upperBoundValue) { this.lowerBoundColumnName = lowerBoundColumnName; this.upperBoundColumnName = upperBoundColumnName; this.lowerBoundValue = lowerBoundValue; this.upperBoundValue = upperBoundValue; } @Override public boolean accept(@NonNull final T model) { final Range<Instant> range1 = closedOpenRange( TimeUtil.asInstant(lowerBoundColumnName.getValue(model)), TimeUtil.asInstant(upperBoundColumnName.getValue(model))); final Range<Instant> range2 = closedOpenRange(lowerBoundValue, upperBoundValue); return isOverlapping(range1, range2); } public static Range<Instant> closedOpenRange(@Nullable final Instant lowerBound, @Nullable final Instant upperBound) { if (lowerBound == null) { return upperBound == null ? Range.all() : Range.upTo(upperBound, BoundType.OPEN); } else { return upperBound == null ? Range.downTo(lowerBound, BoundType.CLOSED) : Range.closedOpen(lowerBound, upperBound); } } public static boolean isOverlapping(@NonNull final Range<Instant> range1, @NonNull final Range<Instant> range2) { if (!range1.isConnected(range2)) { return false; } return !range1.intersection(range2).isEmpty(); } @Deprecated @Override public String toString() { return getSql(); } @Override public String getSql() {
buildSqlIfNeeded(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return getSqlParams(); } public List<Object> getSqlParams() { buildSqlIfNeeded(); return sqlParams; } private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql(); } else { sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:postgresql://${db_server}/mydatabase spring.datasource.username=${USERNAME} spring.datasource.password=${PASSWORD} spring.redis.host=${redis_host} spring.redis.port=6379 # upstream services upstream.serv
ice.users.url=${upstream.host}/api/users upstream.service.products.url=${upstream.host}/api/products
repos\tutorials-master\maven-modules\maven-plugins\spring-properties-cleaner\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class GenericEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String value; public GenericEntity() { } public GenericEntity(String value) { this.value = value; } public GenericEntity(Long id, String value) { this.id = id; this.value = value; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\boot\domain\GenericEntity.java
2
请完成以下Java代码
public String[] getDecisionDefinitionKeyIn() { return decisionDefinitionKeyIn; } public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; } public Date getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(Date currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String[] getTenantIdIn() { return tenantIdIn; } public void setTenantIdIn(String[] tenantIdIn) { this.tenantIdIn = tenantIdIn; } public boolean isTenantIdSet() {
return isTenantIdSet; } public boolean isCompact() { return isCompact; } protected void provideHistoryCleanupStrategy(CommandContext commandContext) { String historyCleanupStrategy = commandContext.getProcessEngineConfiguration() .getHistoryCleanupStrategy(); isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy); } public boolean isHistoryCleanupStrategyRemovalTimeBased() { return isHistoryCleanupStrategyRemovalTimeBased; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricDecisionInstanceReportImpl.java
1
请完成以下Java代码
public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; private String apiKey; private String apiKeyPrefix; public ApiKeyAuth(String location, String paramName) { this.location = location; this.paramName = paramName; } public String getLocation() { return location; } public String getParamName() { return paramName; } public String getApiKey() { return apiKey; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } public String getApiKeyPrefix() { return apiKeyPrefix; } public void setApiKeyPrefix(String apiKeyPrefix) { this.apiKeyPrefix = apiKeyPrefix; } @Override public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) { if (apiKey == null) {
return; } String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; } else { value = apiKey; } if (location.equals("query")) { queryParams.add(paramName, value); } else if (location.equals("header")) { headerParams.add(paramName, value); } else if (location.equals("cookie")) { cookieParams.add(paramName, value); } } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\invoker\auth\ApiKeyAuth.java
1
请在Spring Boot框架中完成以下Java代码
public String getScopeDefinitionId() { return scopeDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCorrelationId() { return correlationId; } public boolean isOnlyTimers() { return onlyTimers; } public boolean isOnlyMessages() { return onlyMessages; } public boolean isExecutable() { return executable; }
public boolean isOnlyExternalWorkers() { return onlyExternalWorkers; } public Date getDuedateHigherThan() { return duedateHigherThan; } public Date getDuedateLowerThan() { return duedateLowerThan; } public Date getDuedateHigherThanOrEqual() { return duedateHigherThanOrEqual; } public Date getDuedateLowerThanOrEqual() { return duedateLowerThanOrEqual; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\DeadLetterJobQueryImpl.java
2
请完成以下Java代码
public List<Book> processReaderDataFromObjectArray() { Mono<Object[]> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Object[].class).log(); Object[] objects = response.block(); return Arrays.stream(objects) .map(object -> mapper.convertValue(object, Reader.class)) .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @Override public List<Book> processReaderDataFromReaderArray() { Mono<Reader[]> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Reader[].class).log(); Reader[] readers = response.block(); return Arrays.stream(readers) .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @Override public List<Book> processReaderDataFromReaderList() { Mono<List<Reader>> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(new ParameterizedTypeReference<List<Reader>>() {}); List<Reader> readers = response.block(); return readers.stream() .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @Override public List<String> processNestedReaderDataFromReaderArray() {
Mono<Reader[]> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Reader[].class).log(); Reader[] readers = response.block(); return Arrays.stream(readers) .flatMap(reader -> reader.getBooksRead().stream()) .map(Book::getAuthor) .collect(Collectors.toList()); } @Override public List<String> processNestedReaderDataFromReaderList() { Mono<List<Reader>> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(new ParameterizedTypeReference<List<Reader>>() {}); List<Reader> readers = response.block(); return readers.stream() .flatMap(reader -> reader.getBooksRead().stream()) .map(Book::getAuthor) .collect(Collectors.toList()); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\json\ReaderConsumerServiceImpl.java
1
请完成以下Java代码
public static ThingsboardErrorResponse of(final String message, final ThingsboardErrorCode errorCode, HttpStatus status) { return new ThingsboardErrorResponse(message, errorCode, status); } @Schema(description = "HTTP Response Status Code", example = "401", accessMode = Schema.AccessMode.READ_ONLY) public Integer getStatus() { return status.value(); } @Schema(description = "Error message", example = "Authentication failed", accessMode = Schema.AccessMode.READ_ONLY) public String getMessage() { return message; } @Schema(description = "Platform error code:" + "\n* `2` - General error (HTTP: 500 - Internal Server Error)" + "\n\n* `10` - Authentication failed (HTTP: 401 - Unauthorized)" + "\n\n* `11` - JWT token expired (HTTP: 401 - Unauthorized)" + "\n\n* `15` - Credentials expired (HTTP: 401 - Unauthorized)" + "\n\n* `20` - Permission denied (HTTP: 403 - Forbidden)" +
"\n\n* `30` - Invalid arguments (HTTP: 400 - Bad Request)" + "\n\n* `31` - Bad request params (HTTP: 400 - Bad Request)" + "\n\n* `32` - Item not found (HTTP: 404 - Not Found)" + "\n\n* `33` - Too many requests (HTTP: 429 - Too Many Requests)" + "\n\n* `34` - Too many updates (Too many updates over Websocket session)" + "\n\n* `40` - Subscription violation (HTTP: 403 - Forbidden)" + "\n\n* `41` - Entities limit exceeded (HTTP: 403 - Forbidden)", example = "10", type = "integer", accessMode = Schema.AccessMode.READ_ONLY) public ThingsboardErrorCode getErrorCode() { return errorCode; } @Schema(description = "Timestamp", accessMode = Schema.AccessMode.READ_ONLY) public long getTimestamp() { return timestamp; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\exception\ThingsboardErrorResponse.java
1
请在Spring Boot框架中完成以下Java代码
public ItemProcessor<Transaction, Transaction> retryItemProcessor() { return new RetryItemProcessor(); } @Bean public ItemWriter<Transaction> itemWriter(Marshaller marshaller) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>(); itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(outputXml); return itemWriter; } @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean public Step retryStep( JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("retryItemProcessor") ItemProcessor<Transaction, Transaction> processor,
ItemWriter<Transaction> writer) { return new StepBuilder("retryStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(writer) .faultTolerant() .retryLimit(3) .retry(ConnectTimeoutException.class) .retry(DeadlockLoserDataAccessException.class) .build(); } @Bean(name = "retryBatchJob") public Job retryJob(JobRepository jobRepository, @Qualifier("retryStep") Step retryStep) { return new JobBuilder("retryBatchJob", jobRepository) .start(retryStep) .build(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\SpringBatchRetryConfig.java
2