instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public GenericEventListenerInstanceQuery name(String name) { innerQuery.planItemInstanceName(name); return this; } @Override public GenericEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public GenericEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public GenericEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public GenericEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public GenericEventListenerInstanceQuery asc() { innerQuery.asc(); return this; } @Override public GenericEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; }
@Override public long count() { return innerQuery.count(); } @Override public GenericEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return GenericEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<GenericEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<GenericEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<GenericEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(GenericEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
public BigDecimal getQty() { return qty; } @Override public void setQty(final BigDecimal qty) { this.qty = qty; } @Override public BigDecimal getQtyProjected() { return qtyProjected; } @Override public void setQtyProjected(final BigDecimal qtyProjected) { this.qtyProjected = qtyProjected; } @Override public BigDecimal getPercentage() { return percentage; } @Override public void setPercentage(final BigDecimal percentage) { this.percentage = percentage; } @Override public boolean isNegateQtyInReport() { return negateQtyInReport; } @Override public void setNegateQtyInReport(final boolean negateQtyInReport) { this.negateQtyInReport = negateQtyInReport; } @Override public String getComponentType() { return componentType; } @Override public void setComponentType(final String componentType) { this.componentType = componentType; }
@Override public String getVariantGroup() { return variantGroup; } @Override public void setVariantGroup(final String variantGroup) { this.variantGroup = variantGroup; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } @Override public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } @Override public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { handlingUnitsInfoProjected = handlingUnitsInfo; } @Override public IHandlingUnitsInfo getHandlingUnitsInfoProjected() { return handlingUnitsInfoProjected; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java
1
请完成以下Java代码
public static BPartnerCompositeLookupKey ofGln(@NonNull final GLN gln) { return new BPartnerCompositeLookupKey(null, null, null, gln, null); } public static BPartnerCompositeLookupKey ofGlnWithLabel(@NonNull final GlnWithLabel glnWithLabel) { return new BPartnerCompositeLookupKey(null, null, null, null, glnWithLabel); } public static BPartnerCompositeLookupKey ofIdentifierString(@NonNull final IdentifierString bpartnerIdentifier) { switch (bpartnerIdentifier.getType()) { case EXTERNAL_ID: return BPartnerCompositeLookupKey.ofJsonExternalId(bpartnerIdentifier.asJsonExternalId()); case VALUE: return BPartnerCompositeLookupKey.ofCode(bpartnerIdentifier.asValue()); case GLN: return BPartnerCompositeLookupKey.ofGln(bpartnerIdentifier.asGLN()); case GLN_WITH_LABEL: return BPartnerCompositeLookupKey.ofGlnWithLabel(bpartnerIdentifier.asGlnWithLabel()); case METASFRESH_ID: return BPartnerCompositeLookupKey.ofMetasfreshId(bpartnerIdentifier.asMetasfreshId()); default: throw new AdempiereException("Unexpected type=" + bpartnerIdentifier.getType()); } } MetasfreshId metasfreshId; JsonExternalId jsonExternalId; String code;
GLN gln; GlnWithLabel glnWithLabel; private BPartnerCompositeLookupKey( @Nullable final MetasfreshId metasfreshId, @Nullable final JsonExternalId jsonExternalId, @Nullable final String code, @Nullable final GLN gln, @Nullable final GlnWithLabel glnWithLabel) { this.metasfreshId = metasfreshId; this.jsonExternalId = jsonExternalId; this.code = code; this.gln = gln; this.glnWithLabel = glnWithLabel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerCompositeLookupKey.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnableAutoReconnect() { return this.enableAutoReconnect; } public void setEnableAutoReconnect(boolean enableAutoReconnect) { this.enableAutoReconnect = enableAutoReconnect; } public int getLockLease() { return this.lockLease; } public void setLockLease(int lockLease) { this.lockLease = lockLease; } public int getLockTimeout() { return this.lockTimeout; } public void setLockTimeout(int lockTimeout) { this.lockTimeout = lockTimeout; }
public int getMessageSyncInterval() { return this.messageSyncInterval; } public void setMessageSyncInterval(int messageSyncInterval) { this.messageSyncInterval = messageSyncInterval; } public int getSearchTimeout() { return this.searchTimeout; } public void setSearchTimeout(int searchTimeout) { this.searchTimeout = searchTimeout; } public boolean isUseClusterConfiguration() { return this.useClusterConfiguration; } public void setUseClusterConfiguration(boolean useClusterConfiguration) { this.useClusterConfiguration = useClusterConfiguration; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PeerCacheProperties.java
2
请完成以下Java代码
public void setPO_Window_ID (int PO_Window_ID) { if (PO_Window_ID < 1) set_Value (COLUMNNAME_PO_Window_ID, null); else set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID)); } /** Get PO Window. @return Purchase Order Window */ public int getPO_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Query. @param Query SQL */ public void setQuery (String Query) { set_Value (COLUMNNAME_Query, Query); } /** Get Query. @return SQL */ public String getQuery () { return (String)get_Value(COLUMNNAME_Query); } /** Set Search Type. @param SearchType Which kind of search is used (Query or Table)
*/ public void setSearchType (String SearchType) { set_Value (COLUMNNAME_SearchType, SearchType); } /** Get Search Type. @return Which kind of search is used (Query or Table) */ public String getSearchType () { return (String)get_Value(COLUMNNAME_SearchType); } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ public void setTransactionCode (String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ public String getTransactionCode () { return (String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
1
请完成以下Java代码
public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } @Nullable public String getBaseUrl() {
return baseUrl; } public void setBaseUrl(@Nullable String baseUrl) { this.baseUrl = baseUrl; } public Map<String, Object> getAdditionalProperties() { return additionalProperties; } public void setAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MailNotifier.java
1
请完成以下Java代码
Order validatedOrders(Message<?> orderMessage) throws JsonProcessingException { ObjectNode on = (ObjectNode) orderMessage.getPayload(); Order order = om.treeToValue(on, Order.class); return order; } @ServiceActivator(inputChannel = "orderProcessor") void processOrder(Order order){ log.info("Processing order: id={}, symbol={}, qty={}, price={}", order.getId(), order.getSymbol(), order.getQuantity(), order.getPrice()); BigDecimal orderTotal = order.getQuantity().multiply(order.getPrice()); if ( order.getOrderType() == OrderType.SELL) { orderTotal = orderTotal.negate(); } BigDecimal sum = orderSummary.get(order.getSymbol()); if ( sum == null) { sum = orderTotal;
} else { sum = sum.add(orderTotal); } orderSummary.put(order.getSymbol(), sum); orderSemaphore.release(); } public BigDecimal getTotalBySymbol(String symbol) { return orderSummary.get(symbol); } public boolean awaitNextMessage(long time, TimeUnit unit) throws InterruptedException { return orderSemaphore.tryAcquire(time, unit); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\postgresqlnotify\PostgresqlPubSubExample.java
1
请在Spring Boot框架中完成以下Java代码
public FlowableServlet getServlet() { return servlet; } public boolean isEnableProcessDefinitionHistoryLevel() { return enableProcessDefinitionHistoryLevel; } public void setEnableProcessDefinitionHistoryLevel(boolean enableProcessDefinitionHistoryLevel) { this.enableProcessDefinitionHistoryLevel = enableProcessDefinitionHistoryLevel; } public int getDefinitionCacheLimit() { return definitionCacheLimit; } public void setDefinitionCacheLimit(int definitionCacheLimit) { this.definitionCacheLimit = definitionCacheLimit; } public boolean isEnableSafeXml() { return enableSafeXml; } public void setEnableSafeXml(boolean enableSafeXml) { this.enableSafeXml = enableSafeXml; } public boolean isEventRegistryStartProcessInstanceAsync() { return eventRegistryStartProcessInstanceAsync; } public void setEventRegistryStartProcessInstanceAsync(boolean eventRegistryStartProcessInstanceAsync) { this.eventRegistryStartProcessInstanceAsync = eventRegistryStartProcessInstanceAsync; }
public boolean isEventRegistryUniqueProcessInstanceCheckWithLock() { return eventRegistryUniqueProcessInstanceCheckWithLock; } public void setEventRegistryUniqueProcessInstanceCheckWithLock(boolean eventRegistryUniqueProcessInstanceCheckWithLock) { this.eventRegistryUniqueProcessInstanceCheckWithLock = eventRegistryUniqueProcessInstanceCheckWithLock; } public Duration getEventRegistryUniqueProcessInstanceStartLockTime() { return eventRegistryUniqueProcessInstanceStartLockTime; } public void setEventRegistryUniqueProcessInstanceStartLockTime(Duration eventRegistryUniqueProcessInstanceStartLockTime) { this.eventRegistryUniqueProcessInstanceStartLockTime = eventRegistryUniqueProcessInstanceStartLockTime; } public static class AsyncHistory { private boolean enabled; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\process\FlowableProcessProperties.java
2
请完成以下Java代码
public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPlannedAmt (final BigDecimal PlannedAmt) { set_Value (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt) { set_Value (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt); }
@Override public BigDecimal getPlannedMarginAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedPrice (final BigDecimal PlannedPrice) { set_Value (COLUMNNAME_PlannedPrice, PlannedPrice); } @Override public BigDecimal getPlannedPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedQty (final BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectLine.java
1
请完成以下Java代码
public class TbKafkaAdmin implements TbQueueAdmin, TbEdgeQueueAdmin { private final TbKafkaSettings settings; private final Map<String, String> topicConfigs; @Getter private final int numPartitions; public TbKafkaAdmin(TbKafkaSettings settings, Map<String, String> topicConfigs) { this.settings = settings; this.topicConfigs = topicConfigs; String numPartitionsStr = topicConfigs.get(TbKafkaTopicConfigs.NUM_PARTITIONS_SETTING); if (numPartitionsStr != null) { numPartitions = Integer.parseInt(numPartitionsStr); } else { numPartitions = 1; } } @Override public void createTopicIfNotExists(String topic, String properties, boolean force) { settings.getAdmin().createTopicIfNotExists(topic, PropertyUtils.getProps(topicConfigs, properties), force); } @Override public void deleteTopic(String topic) { settings.getAdmin().deleteTopic(topic);
} @Override public void destroy() { } /** * Sync edge notifications offsets from a fat group to a single group per edge * */ public void syncEdgeNotificationsOffsets(String fatGroupId, String newGroupId) { try { log.info("syncEdgeNotificationsOffsets [{}][{}]", fatGroupId, newGroupId); settings.getAdmin().syncOffsetsUnsafe(fatGroupId, newGroupId, newGroupId); } catch (Exception e) { log.warn("Failed to syncEdgeNotificationsOffsets from {} to {}", fatGroupId, newGroupId, e); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaAdmin.java
1
请在Spring Boot框架中完成以下Java代码
public class FileItemReaderDemo { // 任务创建工厂 @Autowired private JobBuilderFactory jobBuilderFactory; // 步骤创建工厂 @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job fileItemReaderJob() { return jobBuilderFactory.get("fileItemReaderJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(fileItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> fileItemReader() { FlatFileItemReader<TestData> reader = new FlatFileItemReader<>(); reader.setResource(new ClassPathResource("file")); // 设置文件资源地址 reader.setLinesToSkip(1); // 忽略第一行 // AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取, // 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符 DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); // 设置属性名,类似于表头 tokenizer.setNames("id", "field1", "field2", "field3"); // 将每行数据转换为TestData对象
DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>(); mapper.setLineTokenizer(tokenizer); // 设置映射方式 mapper.setFieldSetMapper(fieldSet -> { TestData data = new TestData(); data.setId(fieldSet.readInt("id")); data.setField1(fieldSet.readString("field1")); data.setField2(fieldSet.readString("field2")); data.setField3(fieldSet.readString("field3")); return data; }); reader.setLineMapper(mapper); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\FileItemReaderDemo.java
2
请完成以下Java代码
public void setR_AvsAddr (final @Nullable java.lang.String R_AvsAddr) { set_ValueNoCheck (COLUMNNAME_R_AvsAddr, R_AvsAddr); } @Override public java.lang.String getR_AvsAddr() { return get_ValueAsString(COLUMNNAME_R_AvsAddr); } /** * R_AvsZip AD_Reference_ID=213 * Reference name: C_Payment AVS */ public static final int R_AVSZIP_AD_Reference_ID=213; /** Match = Y */ public static final String R_AVSZIP_Match = "Y"; /** NoMatch = N */ public static final String R_AVSZIP_NoMatch = "N"; /** Unavailable = X */ public static final String R_AVSZIP_Unavailable = "X"; @Override public void setR_AvsZip (final @Nullable java.lang.String R_AvsZip) { set_ValueNoCheck (COLUMNNAME_R_AvsZip, R_AvsZip); } @Override public java.lang.String getR_AvsZip() { return get_ValueAsString(COLUMNNAME_R_AvsZip); } @Override public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{ set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } @Override public void setSEPA_CreditorIdentifier (final @Nullable java.lang.String SEPA_CreditorIdentifier) { set_Value (COLUMNNAME_SEPA_CreditorIdentifier, SEPA_CreditorIdentifier); } @Override public java.lang.String getSEPA_CreditorIdentifier() { return get_ValueAsString(COLUMNNAME_SEPA_CreditorIdentifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount.java
1
请完成以下Java代码
public void bindActivityBehaviourService(ActivityBehavior delegate, Map props) { String name = (String) props.get("osgi.service.blueprint.compname"); activityBehaviourMap.put(name, delegate); LOGGER.info("added Flowable service to activity behaviour cache {}", name); } @SuppressWarnings("rawtypes") public void unbindActivityBehaviourService(ActivityBehavior delegate, Map props) { String name = (String) props.get("osgi.service.blueprint.compname"); if (activityBehaviourMap.containsKey(name)) { activityBehaviourMap.remove(name); } LOGGER.info("removed Flowable service from activity behaviour cache {}", name); } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return true; }
@Override public void setValue(ELContext context, Object base, Object property, Object value) { } @Override public Class<?> getCommonPropertyType(ELContext context, Object arg) { return Object.class; } @Override public Class<?> getType(ELContext context, Object arg1, Object arg2) { return Object.class; } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BlueprintELResolver.java
1
请完成以下Java代码
public static final boolean isNull(@Nullable final InvoiceCandRecomputeTag recomputeTag) { return recomputeTag == null || recomputeTag == NULL; } /** * @return AD_PInstance_ID or null if the tag {@link #isNull(InvoiceCandRecomputeTag)}. */ public static final PInstanceId getPinstanceIdOrNull(@Nullable final InvoiceCandRecomputeTag recomputeTag) { if (isNull(recomputeTag)) { return null; } return recomputeTag.getPinstanceId(); } @Getter private final PInstanceId pinstanceId; private InvoiceCandRecomputeTag(@Nullable final PInstanceId pinstanceId) { this.pinstanceId = pinstanceId; } @Override public final String toString() {
return asString(); } /** * @return tag as string * @see #fromString(String) */ public final String asString() { if (pinstanceId == null) { return "NULL"; } // NOTE: keep in sync with fromString() return String.valueOf(pinstanceId.getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\InvoiceCandRecomputeTag.java
1
请完成以下Java代码
public class MessageSender { private QueueConnectionFactory factory; private QueueConnection connection; private QueueSession session; private QueueSender sender; public MessageSender() { } public void initialize() throws JMSException { factory = new JMSSetup().createConnectionFactory(); connection = factory.createQueueConnection(); session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("QUEUE1"); sender = session.createSender(queue); connection.start(); } public void sendMessage(String messageText) { try { TextMessage message = session.createTextMessage(); message.setText(messageText); sender.send(message); log("Message sent: " + messageText); } catch (JMSException e) { // handle exception
} finally { try { if (sender != null) { sender.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } catch (JMSException e) { // handle exception } } } }
repos\tutorials-master\messaging-modules\ibm-mq\src\main\java\com\baeldung\ibmmq\MessageSender.java
1
请完成以下Java代码
public void setC_Activity_ID (int C_Activity_ID) { if (C_Activity_ID < 1) set_Value (COLUMNNAME_C_Activity_ID, null); else set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID)); } /** Get Activity. @return Business Activity */ public int getC_Activity_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_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 Payroll Department. @param HR_Department_ID Payroll Department */ public void setHR_Department_ID (int HR_Department_ID) { if (HR_Department_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Department_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Department_ID, Integer.valueOf(HR_Department_ID)); } /** Get Payroll Department. @return Payroll Department */ public int getHR_Department_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Department_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()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Department.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public boolean isContinueOnError() { return this.continueOnError; } public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } public String getSeparator() {
return this.separator; } public void setSeparator(String separator) { this.separator = separator; } public @Nullable Charset getEncoding() { return this.encoding; } public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } public DatabaseInitializationMode getMode() { return this.mode; } public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\autoconfigure\init\SqlInitializationProperties.java
2
请在Spring Boot框架中完成以下Java代码
private void init() { requestTemplate = queueFactory.createEdqsRequestTemplate(); requestTemplate.init(); } @Override public ListenableFuture<EdqsResponse> processRequest(TenantId tenantId, CustomerId customerId, EdqsRequest request) { var requestMsg = ToEdqsMsg.newBuilder() .setTenantIdMSB(tenantId.getId().getMostSignificantBits()) .setTenantIdLSB(tenantId.getId().getLeastSignificantBits()) .setTs(System.currentTimeMillis()) .setRequestMsg(TransportProtos.EdqsRequestMsg.newBuilder() .setValue(JacksonUtil.toString(request)) .build()); if (customerId != null && !customerId.isNullUid()) { requestMsg.setCustomerIdMSB(customerId.getId().getMostSignificantBits()); requestMsg.setCustomerIdLSB(customerId.getId().getLeastSignificantBits()); } UUID key = UUID.randomUUID();
Integer partition = edqsPartitionService.resolvePartition(tenantId, key); ListenableFuture<TbProtoQueueMsg<FromEdqsMsg>> resultFuture = requestTemplate.send(new TbProtoQueueMsg<>(key, requestMsg.build()), partition); return Futures.transform(resultFuture, msg -> { TransportProtos.EdqsResponseMsg responseMsg = msg.getValue().getResponseMsg(); return JacksonUtil.fromString(responseMsg.getValue(), EdqsResponse.class); }, MoreExecutors.directExecutor()); } @Override public boolean isSupported() { return true; } @PreDestroy private void stop() { requestTemplate.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edqs\DefaultEdqsApiService.java
2
请完成以下Java代码
public class Dest { @Override public String toString() { return "Dest [name=" + name + ", age=" + age + "]"; } private String name; private int age; public Dest() { } public Dest(String name, int age) { this.name = name; this.age = age; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\orika\src\main\java\com\baeldung\orika\Dest.java
1
请完成以下Java代码
public void setAD_AttachmentEntry_ID (final int AD_AttachmentEntry_ID) { if (AD_AttachmentEntry_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, AD_AttachmentEntry_ID); } @Override public int getAD_AttachmentEntry_ID() { return get_ValueAsInt(COLUMNNAME_AD_AttachmentEntry_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setFileName_Override (final @Nullable java.lang.String FileName_Override) { set_Value (COLUMNNAME_FileName_Override, FileName_Override); } @Override
public java.lang.String getFileName_Override() { return get_ValueAsString(COLUMNNAME_FileName_Override); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_MultiRef.java
1
请在Spring Boot框架中完成以下Java代码
public void logPointCut() { } @Before("logPointCut()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 loggger.info("请求地址 : " + request.getRequestURL().toString()); loggger.info("HTTP METHOD : " + request.getMethod()); loggger.info("IP : " + request.getRemoteAddr()); loggger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); loggger.info("参数 : " + Arrays.toString(joinPoint.getArgs())); // loggger.info("参数 : " + joinPoint.getArgs());
} @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致 public void doAfterReturning(Object ret) throws Throwable { // 处理完请求,返回内容 loggger.info("返回值 : " + ret); } @Around("logPointCut()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long startTime = System.currentTimeMillis(); Object ob = pjp.proceed();// ob 为方法的返回值 loggger.info("耗时 : " + (System.currentTimeMillis() - startTime)); return ob; } }
repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\config\WebLogAspect.java
2
请完成以下Java代码
public Set<String> getParameters() { return ImmutableSet.of(); } /** * * @return evaluation context */ public IValidationContext getValidationContext() { return IValidationContext.NULL; } /** * Suggests a valid value for given value * * @param value * @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned */
public NamePair suggestValidValue(final NamePair value) { return null; } /** * Returns true if given <code>display</code> value was rendered for a not found item. * To be used together with {@link #getDisplay} methods. * * @param display * @return true if <code>display</code> contains not found markers */ public boolean isNotFoundDisplayValue(String display) { return false; } } // Lookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
1
请完成以下Java代码
public class RegistrationDeserializer extends StdDeserializer<Registration> { @Serial private static final long serialVersionUID = 1L; public RegistrationDeserializer() { super(Registration.class); } @Override public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonNode node = p.readValueAsTree(); Registration.Builder builder = Registration.builder(); builder.name(firstNonNullAsText(node, "name")); if (node.hasNonNull("url")) { String url = firstNonNullAsText(node, "url"); builder.healthUrl(url.replaceFirst("/+$", "") + "/health").managementUrl(url); } else { builder.healthUrl(firstNonNullAsText(node, "healthUrl", "health_url")); builder.managementUrl(firstNonNullAsText(node, "managementUrl", "management_url")); builder.serviceUrl(firstNonNullAsText(node, "serviceUrl", "service_url")); } if (node.has("metadata")) {
node.get("metadata") .properties() .forEach((entry) -> builder.metadata(entry.getKey(), entry.getValue().asText())); } builder.source(firstNonNullAsText(node, "source")); return builder.build(); } private String firstNonNullAsText(JsonNode node, String... fieldNames) { for (String fieldName : fieldNames) { if (node.hasNonNull(fieldName)) { return node.get(fieldName).asText(); } } return null; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\utils\jackson\RegistrationDeserializer.java
1
请在Spring Boot框架中完成以下Java代码
public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); //处理bigDecimal objectMapper.enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN); objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); //处理失败 objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false); //默认的处理日期时间格式 objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss"))); objectMapper.registerModule(javaTimeModule); return objectMapper; } // /** // * SpringBootAdmin的Httptrace不见了 // * https://blog.csdn.net/u013810234/article/details/110097201 // */ // @Bean // public InMemoryHttpTraceRepository getInMemoryHttpTrace(){ // return new InMemoryHttpTraceRepository(); // } /** * 在Bean初始化完成后立即配置PrometheusMeterRegistry,避免在Meter注册后才配置MeterFilter * for [QQYUN-12558]【监控】系统监控的头两个tab不好使,接口404 * @author chenrui * @date 2025/5/26 16:46 */
@PostConstruct public void initPrometheusMeterRegistry() { // 确保在应用启动早期就配置MeterFilter,避免警告 if (null != meterRegistryPostProcessor && null != prometheusMeterRegistry) { meterRegistryPostProcessor.postProcessAfterInitialization(prometheusMeterRegistry, "prometheusMeterRegistry"); log.info("PrometheusMeterRegistry 配置完成"); } } // /** // * 注册拦截器【拦截器拦截参数,自动切换数据源——后期实现多租户切换数据源功能】 // * @param registry // */ // @Override // public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new DynamicDatasourceInterceptor()).addPathPatterns("/test/dynamic/**"); // } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\WebMvcConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public XMLGregorianCalendar getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = value; } } } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;simpleContent&gt; * &lt;extension base="&lt;http://erpel.at/schemas/1p0/documents/extensions/edifact&gt;Decimal4Type"&gt; * &lt;attribute ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}Date"/&gt; * &lt;/extension&gt; * &lt;/simpleContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class ConfirmedQuantity { @XmlValue protected BigDecimal value; @XmlAttribute(name = "Date", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar date;
/** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDate() { return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ORDRSPListLineItemExtensionType.java
2
请完成以下Java代码
public FindPanelBuilder setGridController(final GridController gridController) { Check.assumeNotNull(gridController, "gridController not null"); this.gridController = gridController; setParentFrame(SwingUtils.getFrame(gridController)); final GridTab gridTab = gridController.getMTab(); setGridTab(gridTab); return this; } public GridController getGridController() { return gridController; } /** * Initialize the parameters based on given gridTab. * * NOTE: this method will configure ALL other parameters, so make sure, if you want to tune some of them, you are calling the setters AFTER this method. * * @param gridTab */ public FindPanelBuilder setGridTab(@NonNull final GridTab gridTab) { this.gridTab = gridTab; final int targetWindowNo = gridTab.getWindowNo(); setTitle(gridTab.getName()); // title setAD_Tab_ID(gridTab.getAD_Tab_ID()); setTemplateTabId(gridTab.getTemplateTabId()); setMaxQueryRecordsPerTab(gridTab.getMaxQueryRecords()); setTargetWindowNo(targetWindowNo); setTargetTabNo(gridTab.getTabNo()); // metas-2009_0021_AP1_G113 setAD_Table_ID(gridTab.getAD_Table_ID()); setTableName(gridTab.getTableName()); setWhereExtended(gridTab.getWhereExtended()); setQuery(gridTab.getQuery()); setSearchPanelCollapsed(gridTab.isSearchCollapsed()); // NOTE: not setting them because they will be rendered on request // final GridField[] findFields = GridField.createFields(Env.getCtx(), targetWindowNo, 0, adTabId); // setFindFields(findFields); return this; } public GridTab getGridTab() { return gridTab; } /** * Sets if the find panel will be embedded in the window. */ public FindPanelBuilder setEmbedded(final boolean embedded) { this.embedded = embedded; return this; } /** @return true if the find panel will be embedded in the window */ public boolean isEmbedded() {
return this.embedded; } public FindPanelBuilder setHideStatusBar(boolean hideStatusBar) { this.hideStatusBar = hideStatusBar; return this; } public boolean isHideStatusBar() { return hideStatusBar; } public FindPanelBuilder setSearchPanelCollapsed(final boolean searchPanelCollapsed) { this.searchPanelCollapsed = searchPanelCollapsed; return this; } public boolean isSearchPanelCollapsed() { return searchPanelCollapsed; } public FindPanelBuilder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab) { this.maxQueryRecordsPerTab = maxQueryRecordsPerTab; return this; } public int getMaxQueryRecordsPerTab() { if (maxQueryRecordsPerTab != null) { return maxQueryRecordsPerTab; } else if (gridTab != null) { return gridTab.getMaxQueryRecords(); } return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\FindPanelBuilder.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(this.id, this.version, this.separator); } @Override public String toString() { return new StringJoiner(", ", Qualifier.class.getSimpleName() + "[", "]").add("id='" + this.id + "'") .add("version=" + this.version) .add("separator='" + this.separator + "'") .toString(); } } /** * Define the supported version format. */ public enum Format { /** * Original version format, i.e. {@code Major.Minor.Patch.Qualifier} using * {@code BUILD-SNAPSHOT} as the qualifier for snapshots and {@code RELEASE} for * GAs. */ V1, /** * SemVer-compliant format, i.e. {@code Major.Minor.Patch-Qualifier} using * {@code SNAPSHOT} as the qualifier for snapshots and no qualifier for GAs. */ V2 } private static final class VersionQualifierComparator implements Comparator<Qualifier> { static final String RELEASE = "RELEASE"; static final String BUILD_SNAPSHOT = "BUILD-SNAPSHOT"; static final String SNAPSHOT = "SNAPSHOT"; static final String MILESTONE = "M"; static final String RC = "RC"; static final List<String> KNOWN_QUALIFIERS = Arrays.asList(MILESTONE, RC, BUILD_SNAPSHOT, SNAPSHOT, RELEASE); @Override
public int compare(Qualifier o1, Qualifier o2) { Qualifier first = (o1 != null) ? o1 : new Qualifier(RELEASE); Qualifier second = (o2 != null) ? o2 : new Qualifier(RELEASE); int qualifier = compareQualifier(first, second); return (qualifier != 0) ? qualifier : compareQualifierVersion(first, second); } private static int compareQualifierVersion(Qualifier first, Qualifier second) { Integer firstVersion = (first.getVersion() != null) ? first.getVersion() : 0; Integer secondVersion = (second.getVersion() != null) ? second.getVersion() : 0; return firstVersion.compareTo(secondVersion); } private static int compareQualifier(Qualifier first, Qualifier second) { int firstIndex = getQualifierIndex(first.getId()); int secondIndex = getQualifierIndex(second.getId()); // Unknown qualifier, alphabetic ordering if (firstIndex == -1 && secondIndex == -1) { return first.getId().compareTo(second.getId()); } else { return Integer.compare(firstIndex, secondIndex); } } private static int getQualifierIndex(String qualifier) { return (StringUtils.hasText(qualifier) ? KNOWN_QUALIFIERS.indexOf(qualifier) : 0); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\Version.java
1
请完成以下Java代码
public org.compiere.model.I_GL_Journal getReversal() { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class); } @Override public void setReversal(final org.compiere.model.I_GL_Journal Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_Journal.class, Reversal); } @Override public void setReversal_ID (final int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Reversal_ID); } @Override public int getReversal_ID() { return get_ValueAsInt(COLUMNNAME_Reversal_ID); } @Override public void setSAP_GLJournal_ID (final int SAP_GLJournal_ID) { if (SAP_GLJournal_ID < 1) set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, null); else set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, SAP_GLJournal_ID); } @Override public int getSAP_GLJournal_ID() { return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID); }
@Override public void setTotalCr (final BigDecimal TotalCr) { set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr); } @Override public BigDecimal getTotalCr() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalCr); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalDr (final BigDecimal TotalDr) { set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr); } @Override public BigDecimal getTotalDr() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalDr); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournal.java
1
请在Spring Boot框架中完成以下Java代码
public void setLocalFields(List<String> localFields) { this.localFields = localFields; } public void setTagFields(List<String> tagFields) { this.tagFields = tagFields; } public static class Correlation { /** * Whether to enable correlation of the baggage context with logging contexts. */ private boolean enabled = true; /** * List of fields that should be correlated with the logging context. That * means that these fields would end up as key-value pairs in e.g. MDC. */ private List<String> fields = new ArrayList<>(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getFields() { return this.fields; } public void setFields(List<String> fields) { this.fields = fields; } } } public static class Propagation { /** * Tracing context propagation types produced and consumed by the application. * Setting this property overrides the more fine-grained propagation type * properties. */ private @Nullable List<PropagationType> type; /** * Tracing context propagation types produced by the application. */ private List<PropagationType> produce = List.of(PropagationType.W3C); /** * Tracing context propagation types consumed by the application. */ private List<PropagationType> consume = List.of(PropagationType.values()); public void setType(@Nullable List<PropagationType> type) {
this.type = type; } public void setProduce(List<PropagationType> produce) { this.produce = produce; } public void setConsume(List<PropagationType> consume) { this.consume = consume; } public @Nullable List<PropagationType> getType() { return this.type; } public List<PropagationType> getProduce() { return this.produce; } public List<PropagationType> getConsume() { return this.consume; } /** * Supported propagation types. The declared order of the values matter. */ public enum PropagationType { /** * <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation. */ W3C, /** * <a href="https://github.com/openzipkin/b3-propagation#single-header">B3 * single header</a> propagation. */ B3, /** * <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3 * multiple headers</a> propagation. */ B3_MULTI } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Date getBillDate() { return billDate; } public void setBillDate(Date billDate) { this.billDate = billDate; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public String getMerchantOrderNo() { return merchantOrderNo; } public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim(); } public String getTrxNo() { return trxNo; } public void setTrxNo(String trxNo) { this.trxNo = trxNo == null ? null : trxNo.trim(); } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo == null ? null : bankOrderNo.trim(); } public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim(); } public BigDecimal getOrderAmount() { return orderAmount; } public void setOrderAmount(BigDecimal orderAmount) { this.orderAmount = orderAmount; } public BigDecimal getPlatIncome() { return platIncome; } public void setPlatIncome(BigDecimal platIncome) { this.platIncome = platIncome; } public BigDecimal getFeeRate() { return feeRate; } public void setFeeRate(BigDecimal feeRate) { this.feeRate = feeRate; } public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); }
public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime; } public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<ShipmentScheduleId> ids) { if (ids.isEmpty()) { return ImmutableSet.of(); } return ids.stream().map(ShipmentScheduleId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static ImmutableSet<ShipmentScheduleId> fromIntSet(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(ShipmentScheduleId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } int repoId; private ShipmentScheduleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipmentSchedule_ID");
} @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final ShipmentScheduleId id) { return id != null ? id.getRepoId() : -1; } public TableRecordReference toTableRecordReference() { return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, getRepoId()); } public static boolean equals(@Nullable final ShipmentScheduleId id1, @Nullable final ShipmentScheduleId id2) {return Objects.equals(id1, id2);} public static TableRecordReferenceSet toTableRecordReferenceSet(@NonNull final Collection<ShipmentScheduleId> ids) { return TableRecordReferenceSet.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\ShipmentScheduleId.java
1
请完成以下Java代码
public static SCryptPasswordEncoder defaultsForSpringSecurity_v5_8() { return new SCryptPasswordEncoder(DEFAULT_CPU_COST, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_KEY_LENGTH, DEFAULT_SALT_LENGTH); } @Override protected String encodeNonNullPassword(String rawPassword) { return digest(rawPassword, this.saltGenerator.generateKey()); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { return decodeAndCheckMatches(rawPassword, encodedPassword); } @Override protected boolean upgradeEncodingNonNull(String encodedPassword) { String[] parts = encodedPassword.split("\\$"); if (parts.length != 4) { throw new IllegalArgumentException("Encoded password does not look like SCrypt: " + encodedPassword); } long params = Long.parseLong(parts[1], 16); int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff); int memoryCost = (int) params >> 8 & 0xff; int parallelization = (int) params & 0xff; return cpuCost < this.cpuCost || memoryCost < this.memoryCost || parallelization < this.parallelization; } private boolean decodeAndCheckMatches(CharSequence rawPassword, String encodedPassword) { String[] parts = encodedPassword.split("\\$"); if (parts.length != 4) { return false; } long params = Long.parseLong(parts[1], 16); byte[] salt = decodePart(parts[2]); byte[] derived = decodePart(parts[3]);
int cpuCost = (int) Math.pow(2, params >> 16 & 0xffff); int memoryCost = (int) params >> 8 & 0xff; int parallelization = (int) params & 0xff; byte[] generated = SCrypt.generate(Utf8.encode(rawPassword), salt, cpuCost, memoryCost, parallelization, this.keyLength); return MessageDigest.isEqual(derived, generated); } private String digest(CharSequence rawPassword, byte[] salt) { byte[] derived = SCrypt.generate(Utf8.encode(rawPassword), salt, this.cpuCost, this.memoryCost, this.parallelization, this.keyLength); String params = Long.toString( ((int) (Math.log(this.cpuCost) / Math.log(2)) << 16L) | this.memoryCost << 8 | this.parallelization, 16); StringBuilder sb = new StringBuilder((salt.length + derived.length) * 2); sb.append("$").append(params).append('$'); sb.append(encodePart(salt)).append('$'); sb.append(encodePart(derived)); return sb.toString(); } private byte[] decodePart(String part) { return Base64.getDecoder().decode(Utf8.encode(part)); } private String encodePart(byte[] part) { return Utf8.decode(Base64.getEncoder().encode(part)); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\scrypt\SCryptPasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
public class FTSFilterDescriptorId implements RepoIdAware { @JsonCreator public static FTSFilterDescriptorId ofRepoId(final int repoId) { return new FTSFilterDescriptorId(repoId); } @Nullable public static FTSFilterDescriptorId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new FTSFilterDescriptorId(repoId) : null; } int repoId; private FTSFilterDescriptorId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "ES_FTS_Filter_ID"); } @JsonValue @Override public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final FTSFilterDescriptorId id) { return id != null ? id.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSFilterDescriptorId.java
2
请在Spring Boot框架中完成以下Java代码
public ApiKeyInfo updateApiKeyDescription( @Parameter(description = API_KEY_ID_PARAM_DESCRIPTION, required = true) @PathVariable UUID id, @Parameter(description = "New description for the API key", example = "Description") @RequestBody Optional<String> description) throws Exception { ApiKeyId apiKeyId = new ApiKeyId(id); ApiKey apiKey = checkApiKeyId(apiKeyId, Operation.WRITE); checkUserId(apiKey.getUserId(), Operation.WRITE); apiKey.setDescription(description.orElse(null)); return apiKeyService.saveApiKey(apiKey.getTenantId(), apiKey); } @ApiOperation(value = "Enable or disable API key (enableApiKey)", notes = "Updates api key with enabled = true/false. " + AVAILABLE_FOR_ANY_AUTHORIZED_USER) @PreAuthorize("hasAnyAuthority('SYS_ADMIN','TENANT_ADMIN', 'CUSTOMER_USER')") @PutMapping(value = "/apiKey/{id}/enabled/{enabledValue}") public ApiKeyInfo enableApiKey( @Parameter(description = "Unique identifier of the API key to enable/disable", required = true) @PathVariable UUID id, @Parameter(description = "Enabled or disabled api key", required = true) @PathVariable(value = "enabledValue") Boolean enabledValue) throws ThingsboardException { ApiKeyId apiKeyId = new ApiKeyId(id);
ApiKey apiKey = checkApiKeyId(apiKeyId, Operation.WRITE); checkUserId(apiKey.getUserId(), Operation.WRITE); apiKey.setEnabled(enabledValue); return apiKeyService.saveApiKey(apiKey.getTenantId(), apiKey); } @ApiOperation(value = "Delete API key by ID (deleteApiKey)", notes = "Deletes the API key. Referencing non-existing ApiKey Id will cause an error." + AVAILABLE_FOR_ANY_AUTHORIZED_USER) @PreAuthorize("hasAnyAuthority('SYS_ADMIN','TENANT_ADMIN', 'CUSTOMER_USER')") @DeleteMapping(value = "/apiKey/{id}") public void deleteApiKey(@PathVariable UUID id) throws ThingsboardException { ApiKeyId apiKeyId = new ApiKeyId(id); ApiKey apiKey = checkApiKeyId(apiKeyId, Operation.DELETE); checkUserId(apiKey.getUserId(), Operation.WRITE); apiKeyService.deleteApiKey(apiKey.getTenantId(), apiKey, false); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\ApiKeyController.java
2
请在Spring Boot框架中完成以下Java代码
public String getBatchDocument(@ApiParam(name = "batchId") @PathVariable String batchId, HttpServletResponse response) { Batch batch = getBatchById(batchId); String batchDocument = managementService.getBatchDocument(batchId); if (batchDocument == null) { throw new FlowableObjectNotFoundException("Batch with id '" + batch.getId() + "' does not have a batch document.", String.class); } response.setContentType("application/json"); return batchDocument; } @ApiOperation(value = "Delete a batch", tags = { "Batches" }, nickname = "deleteBatch", code = 204) @ApiResponses(value = { @ApiResponse(code = 204, message = "Indicates the batch was found and has been deleted. Response-body is intentionally empty."), @ApiResponse(code = 404, message = "Indicates the requested batch was not found.") })
@DeleteMapping("/management/batches/{batchId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteJob(@ApiParam(name = "batchId") @PathVariable String batchId) { Batch batch = getBatchById(batchId); if (restApiInterceptor != null) { restApiInterceptor.deleteBatch(batch); } try { managementService.deleteBatch(batchId); } catch (FlowableObjectNotFoundException aonfe) { // Re-throw to have consistent error-messaging across REST-api throw new FlowableObjectNotFoundException("Could not find a batch with id '" + batchId + "'.", Batch.class); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResource.java
2
请完成以下Java代码
public Builder setParametersLayoutType(final PanelLayoutType parametersLayoutType) { this.parametersLayoutType = parametersLayoutType; return this; } private PanelLayoutType getParametersLayoutType() { return parametersLayoutType != null ? parametersLayoutType : PanelLayoutType.Panel; } public Builder setFacetFilter(final boolean facetFilter) { this.facetFilter = facetFilter; return this; } public boolean hasParameters() { return !parameters.isEmpty(); } public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter) { parameters.add(parameter); return this; }
public Builder addInternalParameter(final String parameterName, final Object constantValue) { return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue)); } public Builder addInternalParameter(final DocumentFilterParam parameter) { internalParameters.add(parameter); return this; } public Builder putDebugProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put("debug-" + name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
1
请完成以下Java代码
public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM) { set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM); } @Override
public BigDecimal getQtyDeliveredInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEntered (final BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM) { set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM); } @Override public BigDecimal getQtyInvoicedInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderSummary.java
1
请完成以下Java代码
public class CombinationChartExample { public static void main(String[] args) { // Create datasets DefaultCategoryDataset lineDataset = new DefaultCategoryDataset(); lineDataset.addValue(200, "Sales", "January"); lineDataset.addValue(150, "Sales", "February"); lineDataset.addValue(180, "Sales", "March"); DefaultCategoryDataset barDataset = new DefaultCategoryDataset(); barDataset.addValue(400, "Profit", "January"); barDataset.addValue(300, "Profit", "February"); barDataset.addValue(250, "Profit", "March"); // Create a combination chart CategoryPlot plot = new CategoryPlot(); plot.setDataset(0, lineDataset); plot.setRenderer(0, new LineAndShapeRenderer()); plot.setDataset(1, barDataset); plot.setRenderer(1, new BarRenderer()); plot.setDomainAxis(new CategoryAxis("Month")); plot.setRangeAxis(new NumberAxis("Value"));
plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinesVisible(true); JFreeChart chart = new JFreeChart( "Monthly Sales and Profit", // chart title null, // null means to use default font plot, // combination chart as CategoryPlot true); // legend // Display the chart ChartPanel chartPanel = new ChartPanel(chart); JFrame frame = new JFrame(); frame.setSize(800, 600); frame.setContentPane(chartPanel); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\jfreechart\CombinationChartExample.java
1
请完成以下Java代码
public class CustomLoggingAdvisor implements CallAroundAdvisor { private final static Logger logger = LoggerFactory.getLogger(CustomLoggingAdvisor.class); @Override public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) { advisedRequest = this.before(advisedRequest); AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest); this.observeAfter(advisedResponse); return advisedResponse; } private void observeAfter(AdvisedResponse advisedResponse) { logger.info(advisedResponse.response() .getResult() .getOutput()
.getText()); } private AdvisedRequest before(AdvisedRequest advisedRequest) { logger.info(advisedRequest.userText()); return advisedRequest; } @Override public String getName() { return "CustomLoggingAdvisor"; } @Override public int getOrder() { return Integer.MAX_VALUE; } }
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springai\advisors\CustomLoggingAdvisor.java
1
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { if (success) { updateHeader(); if (newRecord || is_ValueChanged("S_ResourceAssignment_ID")) { int S_ResourceAssignment_ID = getS_ResourceAssignment_ID(); int old_S_ResourceAssignment_ID = 0; if (!newRecord) { Object ii = get_ValueOld("S_ResourceAssignment_ID"); if (ii instanceof Integer) { old_S_ResourceAssignment_ID = ((Integer)ii).intValue(); // Changed Assignment if (old_S_ResourceAssignment_ID != S_ResourceAssignment_ID && old_S_ResourceAssignment_ID != 0) { MResourceAssignment ra = new MResourceAssignment (getCtx(), old_S_ResourceAssignment_ID, get_TrxName()); ra.delete(false); } } } // Sync Assignment if (S_ResourceAssignment_ID != 0) { MResourceAssignment ra = new MResourceAssignment (getCtx(), S_ResourceAssignment_ID, get_TrxName()); if (getQty().compareTo(ra.getQty()) != 0) { ra.setQty(getQty()); if (getDescription() != null && getDescription().length() > 0) { ra.setDescription(getDescription()); } ra.save(); } } } } return success; } // afterSave /** * After Delete * @param success success * @return success */ @Override protected boolean afterDelete (boolean success) { if (success) { updateHeader(); // Object ii = get_ValueOld("S_ResourceAssignment_ID"); if (ii instanceof Integer) {
int old_S_ResourceAssignment_ID = ((Integer)ii).intValue(); // Deleted Assignment if (old_S_ResourceAssignment_ID != 0) { MResourceAssignment ra = new MResourceAssignment (getCtx(), old_S_ResourceAssignment_ID, get_TrxName()); ra.delete(false); } } } return success; } // afterDelete /** * Update Header. * Set Approved Amount */ private void updateHeader() { String sql = "UPDATE S_TimeExpense te" + " SET ApprovalAmt = " + "(SELECT SUM(Qty*ConvertedAmt) FROM S_TimeExpenseLine tel " + "WHERE te.S_TimeExpense_ID=tel.S_TimeExpense_ID) " + "WHERE S_TimeExpense_ID=" + getS_TimeExpense_ID(); int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); } // updateHeader } // MTimeExpenseLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MTimeExpenseLine.java
1
请完成以下Java代码
public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); }
@Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
1
请完成以下Java代码
public Element setLang(String lang) { addAttribute("lang", lang); addAttribute("xml:lang", lang); return this; } /** * * Adds an Element to the element. * * @param hashcode name of element for hash table * * @param element Adds an Element to the element. * */ public comment addElement(String hashcode, Element element) { addElementToRegistry(hashcode, element); return (this); } /** * * Adds an Element to the element. * * @param hashcode name of element for hash table * * @param element Adds an Element to the element. * */ public comment addElement(String hashcode, String element) { addElementToRegistry(hashcode, element); return (this); } /** * * Adds an Element to the element. * * @param element Adds an Element to the element. * */ public comment addElement(Element element) { addElementToRegistry(element); return (this); } /** * * Adds an Element to the element. * * @param element Adds an Element to the element. * */ public comment addElement(String element) { addElementToRegistry(element); return (this); } /** * * Removes an Element from the element. * * @param hashcode the name of the element to be removed. * */ public comment removeElement(String hashcode) { removeElementFromRegistry(hashcode);
return (this); } protected String createStartTag() { setEndTagChar(' '); StringBuffer out = new StringBuffer(); out.append(getStartTagChar()); if (getBeginStartModifierDefined()) { out.append(getBeginStartModifier()); } out.append(getElementType()); if (getBeginEndModifierDefined()) { out.append(getBeginEndModifier()); } out.append(getEndTagChar()); setEndTagChar('>'); // put back the end tag character. return (out.toString()); } protected String createEndTag() { StringBuffer out = new StringBuffer(); setStartTagChar(' '); setEndStartModifier(' '); out.append(getStartTagChar()); if (getEndStartModifierDefined()) { out.append(getEndStartModifier()); } out.append(getElementType()); if (getEndEndModifierDefined()) { out.append(getEndEndModifier()); } out.append(getEndTagChar()); setStartTagChar('<'); // put back the tag start character return (out.toString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\comment.java
1
请在Spring Boot框架中完成以下Java代码
public String deleteAll(){ try { solrService.deleteAll(db_core); return "success"; } catch (Exception e) { e.printStackTrace(); } return "error"; } /** * 根据id查询索引 * @return * @throws Exception */ @RequestMapping("getById/{id}") public String getById(@PathVariable String id) throws Exception { SolrDocument document = solrService.getById(db_core,id); System.out.println(document); return document.toString(); } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("search/{q}") public SolrDocumentList search(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(db_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) { e.printStackTrace(); } return results; } /** * 文件创建索引 */ @RequestMapping("doc/dataimport")
public String dataimport(){ // 1、清空索引,生产环境不建议这样使用,可以保存文件新建及更新时间,增量创建索引 try { solrService.deleteAll(file_core); } catch (Exception e) { e.printStackTrace(); } // 2、创建索引 Mono<String> result = WebClient.create(solrHost) .get() .uri(fileDataImport) .retrieve() .bodyToMono(String.class); System.out.println(result.block()); return "success"; } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("doc/search/{q}") public SolrDocumentList docSearch(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(file_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) { e.printStackTrace(); } return results; } }
repos\springboot-demo-master\solr\src\main\java\demo\et59\solr\controller\SolrController.java
2
请在Spring Boot框架中完成以下Java代码
public ISyncAfterCommitCollector add(@NonNull final WeekSupply weeklySupply) { createAndStoreSyncConfirmRecord(weeklySupply); weeklySupplies.add(weeklySupply); return this; } @Override public ISyncAfterCommitCollector add(@NonNull final Rfq rfq) { createAndStoreSyncConfirmRecord(rfq); rfqs.add(rfq); return this; } @Override public ISyncAfterCommitCollector add(@NonNull final User user) { users.add(user); return this; } /** * Creates a new local DB record for the given <code>abstractEntity</code>. */ private void createAndStoreSyncConfirmRecord(final AbstractSyncConfirmAwareEntity abstractEntity) { final SyncConfirm syncConfirmRecord = new SyncConfirm(); syncConfirmRecord.setEntryType(abstractEntity.getClass().getSimpleName()); syncConfirmRecord.setEntryUuid(abstractEntity.getUuid()); syncConfirmRecord.setEntryId(abstractEntity.getId()); syncConfirmRepo.save(syncConfirmRecord); abstractEntity.setSyncConfirmId(syncConfirmRecord.getId()); } @Override public void afterCommit() { publishToMetasfreshAsync();
} public void publishToMetasfreshAsync() { logger.debug("Synchronizing: {}", this); // // Sync daily product supplies { final List<ProductSupply> productSupplies = ImmutableList.copyOf(this.productSupplies); this.productSupplies.clear(); pushDailyReportsAsync(productSupplies); } // // Sync weekly product supplies { final List<WeekSupply> weeklySupplies = ImmutableList.copyOf(this.weeklySupplies); this.weeklySupplies.clear(); pushWeeklyReportsAsync(weeklySupplies); } // // Sync RfQ changes { final List<Rfq> rfqs = ImmutableList.copyOf(this.rfqs); this.rfqs.clear(); pushRfqsAsync(rfqs); } // // Sync User changes { final List<User> users = ImmutableList.copyOf(this.users); this.users.clear(); pushUsersAsync(users); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SenderToMetasfreshService.java
2
请完成以下Java代码
public class OrdersGenerator { public static final OrdersGenerator newInstance() { return new OrdersGenerator(); } // services private final transient ITrxManager trxManager = Services.get(ITrxManager.class); private Iterator<I_PMM_PurchaseCandidate> candidates; private OrdersGenerator() { super(); } public void generate() { trxManager.run(ITrx.TRXNAME_ThreadInherited, new TrxRunnableAdapter() { @Override public void run(final String localTrxName) throws Exception { generate0(); } }); } private void generate0() { final OrdersCollector ordersCollector = OrdersCollector.newInstance(); final OrdersAggregator aggregator = OrdersAggregator.newInstance(ordersCollector); for (final Iterator<I_PMM_PurchaseCandidate> it = getCandidates(); it.hasNext();) { final I_PMM_PurchaseCandidate candidateModel = it.next(); final PurchaseCandidate candidate = PurchaseCandidate.of(candidateModel); aggregator.add(candidate); }
aggregator.closeAllGroups(); } public OrdersGenerator setCandidates(final Iterator<I_PMM_PurchaseCandidate> candidates) { Check.assumeNotNull(candidates, "candidates not null"); this.candidates = candidates; return this; } public OrdersGenerator setCandidates(final Iterable<I_PMM_PurchaseCandidate> candidates) { Check.assumeNotNull(candidates, "candidates not null"); setCandidates(candidates.iterator()); return this; } private Iterator<I_PMM_PurchaseCandidate> getCandidates() { return candidates; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\OrdersGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomerAddress { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String street; private String city; private long customer_id; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city;
} public void setCity(String city) { this.city = city; } public Long getId() { return id; } public long getCustomer_id() { return customer_id; } public void setCustomer_id(long customer_id) { this.customer_id = customer_id; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\flush\CustomerAddress.java
2
请完成以下Java代码
public List<Rate3> getRate() { if (rate == null) { rate = new ArrayList<Rate3>(); } return this.rate; } /** * Gets the value of the frToDt property. * * @return * possible object is * {@link DateTimePeriodDetails } * */ public DateTimePeriodDetails getFrToDt() { return frToDt; } /** * Sets the value of the frToDt property. * * @param value * allowed object is * {@link DateTimePeriodDetails } * */ public void setFrToDt(DateTimePeriodDetails value) { this.frToDt = value; } /** * Gets the value of the rsn property. *
* @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AccountInterest2.java
1
请完成以下Java代码
public class Country { protected String name; protected int population; protected String capital; protected Currency currency; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } public String getCapital() {
return capital; } public void setCapital(String capital) { this.capital = capital; } public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } }
repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\soap\ws\server\Country.java
1
请完成以下Java代码
public void setSupport_User_ID (int Support_User_ID) { if (Support_User_ID < 1) set_Value (COLUMNNAME_Support_User_ID, null); else set_Value (COLUMNNAME_Support_User_ID, Integer.valueOf(Support_User_ID)); } /** Get Support Benutzer. @return Benutzer für Benachrichtigungen */ @Override public int getSupport_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Support_User_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set TAN Passwort. @param TanPassword TAN Passwort benutzt für Authentifizierung */ @Override public void setTanPassword (java.lang.String TanPassword) { set_Value (COLUMNNAME_TanPassword, TanPassword); } /** Get TAN Passwort. @return TAN Passwort benutzt für Authentifizierung */ @Override public java.lang.String getTanPassword () { return (java.lang.String)get_Value(COLUMNNAME_TanPassword); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Config.java
1
请完成以下Java代码
private synchronized void addOrUpdateRow(@NonNull final ProductsProposalRowAddRequest request) { final ProductsProposalRow existingRow = getRowByProductAndASI(request.getProductId(), request.getAsiDescription()) .orElse(null); if (existingRow != null) { patchRow(existingRow.getId(), RowUpdate.builder() .price(createPrice(request.getProductId(), request.getPriceListPrice())) .lastShipmentDays(request.getLastShipmentDays()) .copiedFromProductPriceId(request.getCopiedFromProductPriceId()) .build()); } else { addRow(createRow(request)); } } private ProductProposalPrice createPrice(@NonNull final ProductId productId, @NonNull final Amount priceListPrice) { final ProductProposalCampaignPrice campaignPrice = campaignPriceProvider.getCampaignPrice(productId).orElse(null); return ProductProposalPrice.builder() .priceListPrice(priceListPrice) .campaignPrice(campaignPrice) .build(); } private ProductsProposalRow createRow(final ProductsProposalRowAddRequest request) { return ProductsProposalRow.builder() .id(nextRowIdSequence.nextDocumentId()) .product(request.getProduct()) .asiDescription(request.getAsiDescription()) .asiId(request.getAsiId()) .price(createPrice(request.getProductId(), request.getPriceListPrice())) .packingMaterialId(request.getPackingMaterialId()) .packingDescription(request.getPackingDescription()) .lastShipmentDays(request.getLastShipmentDays()) .copiedFromProductPriceId(request.getCopiedFromProductPriceId()) .build() .withExistingOrderLine(bestMatchingProductPriceIdToOrderLine.get(request.getCopiedFromProductPriceId())); } private synchronized void addRow(final ProductsProposalRow row) { rowIdsOrderedAndFiltered.add(0, row.getId()); // add first
rowIdsOrdered.add(0, row.getId()); // add first rowsById.put(row.getId(), row); } public synchronized void removeRowsByIds(@NonNull final Set<DocumentId> rowIds) { rowIdsOrderedAndFiltered.removeAll(rowIds); rowIdsOrdered.removeAll(rowIds); rowIds.forEach(rowsById::remove); } public synchronized ProductsProposalViewFilter getFilter() { return filter; } public synchronized void filter(@NonNull final ProductsProposalViewFilter filter) { if (Objects.equals(this.filter, filter)) { return; } this.filter = filter; rowIdsOrderedAndFiltered = rowIdsOrdered .stream() .filter(rowId -> rowsById.get(rowId).isMatching(filter)) .collect(Collectors.toCollection(ArrayList::new)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowsData.java
1
请完成以下Java代码
public final class RefreshTokenGrantBuilder implements Builder { private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient; private Duration clockSkew; private Clock clock; private RefreshTokenGrantBuilder() { } /** * Sets the client used when requesting an access token credential at the Token * Endpoint. * @param accessTokenResponseClient the client used when requesting an access * token credential at the Token Endpoint * @return the {@link RefreshTokenGrantBuilder} */ public RefreshTokenGrantBuilder accessTokenResponseClient( ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient) { this.accessTokenResponseClient = accessTokenResponseClient; return this; } /** * Sets the maximum acceptable clock skew, which is used when checking the access * token expiry. An access token is considered expired if * {@code OAuth2Token#getExpiresAt() - clockSkew} is before the current time * {@code clock#instant()}. * @param clockSkew the maximum acceptable clock skew * @return the {@link RefreshTokenGrantBuilder} * @see RefreshTokenReactiveOAuth2AuthorizedClientProvider#setClockSkew(Duration) */ public RefreshTokenGrantBuilder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; return this; }
/** * Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the * access token expiry. * @param clock the clock * @return the {@link RefreshTokenGrantBuilder} */ public RefreshTokenGrantBuilder clock(Clock clock) { this.clock = clock; return this; } /** * Builds an instance of * {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}. * @return the {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider} */ @Override public ReactiveOAuth2AuthorizedClientProvider build() { RefreshTokenReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenReactiveOAuth2AuthorizedClientProvider(); if (this.accessTokenResponseClient != null) { authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient); } if (this.clockSkew != null) { authorizedClientProvider.setClockSkew(this.clockSkew); } if (this.clock != null) { authorizedClientProvider.setClock(this.clock); } return authorizedClientProvider; } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\ReactiveOAuth2AuthorizedClientProviderBuilder.java
1
请完成以下Java代码
public class VStringBeanInfo extends SimpleBeanInfo { private Class beanClass = VString.class; private String iconColor16x16Filename; private String iconColor32x32Filename; private String iconMono16x16Filename; private String iconMono32x32Filename; public VStringBeanInfo() { } public PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor _display = new PropertyDescriptor("display", beanClass, "getDisplay", null); PropertyDescriptor _editable = new PropertyDescriptor("editable", beanClass, null, "setEditable"); PropertyDescriptor _mandatory = new PropertyDescriptor("mandatory", beanClass, "isMandatory", "setMandatory"); PropertyDescriptor _value = new PropertyDescriptor("value", beanClass, "getValue", "setValue"); PropertyDescriptor[] pds = new PropertyDescriptor[] { _display, _editable, _mandatory, _value}; return pds; } catch(IntrospectionException ex) { ex.printStackTrace(); return null; } } public java.awt.Image getIcon(int iconKind) { switch (iconKind) { case BeanInfo.ICON_COLOR_16x16: return iconColor16x16Filename != null ? loadImage(iconColor16x16Filename) : null; case BeanInfo.ICON_COLOR_32x32:
return iconColor32x32Filename != null ? loadImage(iconColor32x32Filename) : null; case BeanInfo.ICON_MONO_16x16: return iconMono16x16Filename != null ? loadImage(iconMono16x16Filename) : null; case BeanInfo.ICON_MONO_32x32: return iconMono32x32Filename != null ? loadImage(iconMono32x32Filename) : null; } return null; } public BeanInfo[] getAdditionalBeanInfo() { Class superclass = beanClass.getSuperclass(); try { BeanInfo superBeanInfo = Introspector.getBeanInfo(superclass); return new BeanInfo[] { superBeanInfo }; } catch(IntrospectionException ex) { ex.printStackTrace(); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VStringBeanInfo.java
1
请在Spring Boot框架中完成以下Java代码
public void setS_Parent_Issue_ID (final int S_Parent_Issue_ID) { if (S_Parent_Issue_ID < 1) set_Value (COLUMNNAME_S_Parent_Issue_ID, null); else set_Value (COLUMNNAME_S_Parent_Issue_ID, S_Parent_Issue_ID); } @Override public int getS_Parent_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Parent_Issue_ID); } /** * Status AD_Reference_ID=541142 * Reference name: S_Issue_Status */ public static final int STATUS_AD_Reference_ID=541142; /** In progress = InProgress */ public static final String STATUS_InProgress = "InProgress"; /** Closed = Closed */ public static final String STATUS_Closed = "Closed"; /** Pending = Pending */ public static final String STATUS_Pending = "Pending"; /** Delivered = Delivered */ public static final String STATUS_Delivered = "Delivered"; /** New = New */
public static final String STATUS_New = "New"; /** Invoiced = Invoiced */ public static final String STATUS_Invoiced = "Invoiced"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Issue.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isSingleProductId(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) { final Set<ProductId> distinctProductIds = retrieveDistinctProductIdsForSelection(selectionFilter); return distinctProductIds.size() == 1; } @Override public ProductId retrieveUniqueProductIdForSelectionOrNull(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) { final Set<ProductId> distinctProductsForSelection = retrieveDistinctProductIdsForSelection(selectionFilter); if (distinctProductsForSelection.isEmpty()) { return null; } if (distinctProductsForSelection.size() > 1) { throw new AdempiereException("Multiple products or none in the selected rows") .appendParametersToMessage() .setParameter("selectionFilter", selectionFilter); }
final ProductId uniqueProductId = distinctProductsForSelection.iterator().next(); return uniqueProductId; } private Set<ProductId> retrieveDistinctProductIdsForSelection(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) { final IQuery<I_M_DiscountSchemaBreak> breaksQuery = queryBL.createQueryBuilder(I_M_DiscountSchemaBreak.class) .filter(selectionFilter) .create(); final List<Integer> distinctProductRecordIds = breaksQuery.listDistinct(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, Integer.class); return ProductId.ofRepoIds(distinctProductRecordIds); } public I_M_DiscountSchemaBreak getPricingConditionsBreakbyId(@NonNull PricingConditionsBreakId discountSchemaBreakId) { return load(discountSchemaBreakId.getDiscountSchemaBreakId(), I_M_DiscountSchemaBreak.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\PricingConditionsRepository.java
2
请完成以下Java代码
public void setSalesRep_ID(int SalesRep_ID) { if (SalesRep_ID != 0) { super.setSalesRep_ID(SalesRep_ID); } else if (getSalesRep_ID() != 0) { log.warn("Ignored - Tried to set SalesRep_ID to 0 from " + getSalesRep_ID()); } } // setSalesRep_ID /** * After Save * * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave(boolean newRecord, boolean success) { if (!success) { return success; } // Create Update if (newRecord && getResult() != null) { final MRequestUpdate update = new MRequestUpdate(this); update.save(); } // sendNotifications(); // ChangeRequest - created in Request Processor if (getM_ChangeRequest_ID() != 0 && is_ValueChanged(COLUMNNAME_R_Group_ID)) // different ECN assignment? { int oldID = get_ValueOldAsInt(COLUMNNAME_R_Group_ID); if (getR_Group_ID() == 0) { setM_ChangeRequest_ID(0); // not effective as in afterSave } else { MGroup oldG = MGroup.get(getCtx(), oldID); MGroup newG = MGroup.get(getCtx(), getR_Group_ID()); if (oldG.getPP_Product_BOM_ID() != newG.getPP_Product_BOM_ID() || oldG.getM_ChangeNotice_ID() != newG.getM_ChangeNotice_ID()) { MChangeRequest ecr = new MChangeRequest(getCtx(), getM_ChangeRequest_ID(), get_TrxName()); if (!ecr.isProcessed() || ecr.getM_FixChangeNotice_ID() == 0) { ecr.setPP_Product_BOM_ID(newG.getPP_Product_BOM_ID()); ecr.setM_ChangeNotice_ID(newG.getM_ChangeNotice_ID()); ecr.save(); } } } } return success; } // afterSave
private void sendNotifications() { final UserId oldSalesRepId = getOldSalesRepId(); final UserId newSalesRepId = getNewSalesRepId(); if (!UserId.equals(oldSalesRepId, newSalesRepId)) { RequestNotificationsSender.newInstance() .notifySalesRepChanged(RequestSalesRepChanged.builder() .changedById(UserId.ofRepoIdOrNull(getUpdatedBy())) .fromSalesRepId(oldSalesRepId) .toSalesRepId(newSalesRepId) .requestDocumentNo(getDocumentNo()) .requestId(RequestId.ofRepoId(getR_Request_ID())) .build()); } } private UserId getOldSalesRepId() { final Object oldSalesRepIdObj = get_ValueOld(I_R_Request.COLUMNNAME_SalesRep_ID); if (oldSalesRepIdObj instanceof Integer) { final int repoId = ((Integer)oldSalesRepIdObj).intValue(); return UserId.ofRepoId(repoId); } else { return null; } } private UserId getNewSalesRepId() { final int repoId = getSalesRep_ID(); // NOTE: System(=0) is not a valid SalesRep anyways return repoId > 0 ? UserId.ofRepoId(repoId) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequest.java
1
请完成以下Java代码
public java.lang.String getUOMSymbol() { return get_ValueAsString(COLUMNNAME_UOMSymbol); } @Override public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID) { if (WEBUI_KPI_Field_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID); } @Override public int getWEBUI_KPI_Field_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID); } @Override public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI() { return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class);
} @Override public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI) { set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI); } @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_Field.java
1
请完成以下Java代码
private final void updateIfStale() { if (!_stale) { return; } // // Iterate all Parts and // * Compute qty and QtyWithIssues // * Collect quality notices // * Collect receipt schedule allocations final ReceiptQty qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId); final List<I_M_ReceiptSchedule_Alloc> receiptScheduleAllocs = new ArrayList<I_M_ReceiptSchedule_Alloc>(); for (final HUReceiptLinePartCandidate receiptLinePart : receiptLinePartCandidates) { // In case there are several qualityNotes, only the first one shall be remembered if (_qualityNote == null) { _qualityNote = receiptLinePart.getQualityNote(); } final ReceiptQty partQtyAndQuality = receiptLinePart.getQtyAndQuality(); if (partQtyAndQuality.isZero()) { // skip receipt line parts where Qty is ZERO // NOTE: we will also skip receipt schedule allocs but that shall be fine // because if Qty is ZERO it means it was an allocation and deallocation // so we don't need the packing materials from them continue; } qtyAndQuality.add(partQtyAndQuality); receiptScheduleAllocs.addAll(receiptLinePart.getReceiptScheduleAllocs()); } // // Update candidate's cumulated values _qtyAndQuality = qtyAndQuality; _receiptScheduleAllocs = Collections.unmodifiableList(receiptScheduleAllocs);
_stale = false; // not staled anymore } /** @return receipt schedule; never return null */ public I_M_ReceiptSchedule getM_ReceiptSchedule() { return _receiptSchedule; } public int getSubProducer_BPartner_ID() { // updateIfStale(); // no need return _subProducerBPartnerId; } public List<I_M_ReceiptSchedule_Alloc> getReceiptScheduleAllocs() { updateIfStale(); return _receiptScheduleAllocs; } public I_C_UOM getC_UOM() { return loadOutOfTrx(getM_ReceiptSchedule().getC_UOM_ID(), I_C_UOM.class); } public ReceiptQty getQtyAndQuality() { updateIfStale(); return _qtyAndQuality; } public I_M_QualityNote get_qualityNote() { return _qualityNote; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLineCandidate.java
1
请完成以下Java代码
private int hashUnit(int id) { int hashValue = 0; for (; id != 0; ++id) { // int unit = _units.get(id).unit(); int unit = _units.get(id); byte label = _labels.get(id); hashValue ^= hash(((label & 0xFF) << 24) ^ unit); // if (_units.get(id).hasSibling() == false) { if ((_units.get(id) & 1) != 1) { break; } } return hashValue; } private int hashNode(int id) { int hashValue = 0; for (; id != 0; id = _nodes.get(id).sibling) { int unit = _nodes.get(id).unit(); byte label = _nodes.get(id).label; hashValue ^= hash(((label & 0xFF) << 24) ^ unit); } return hashValue; } private int appendUnit() { _isIntersections.append(); _units.add(0); _labels.add((byte) 0); return _isIntersections.size() - 1; } private int appendNode() { int id; if (_recycleBin.empty()) { id = _nodes.size(); _nodes.add(new DawgNode()); } else {
id = _recycleBin.get(_recycleBin.size() - 1); _nodes.get(id).reset(); _recycleBin.deleteLast(); } return id; } private void freeNode(int id) { _recycleBin.add(id); } private static int hash(int key) { key = ~key + (key << 15); // key = (key << 15) - key - 1; key = key ^ (key >>> 12); key = key + (key << 2); key = key ^ (key >>> 4); key = key * 2057; // key = (key + (key << 3)) + (key << 11); key = key ^ (key >>> 16); return key; } private static final int INITIAL_TABLE_SIZE = 1 << 10; private ArrayList<DawgNode> _nodes = new ArrayList<DawgNode>(); private AutoIntPool _units = new AutoIntPool(); private AutoBytePool _labels = new AutoBytePool(); private BitVector _isIntersections = new BitVector(); private AutoIntPool _table = new AutoIntPool(); private AutoIntPool _nodeStack = new AutoIntPool(); private AutoIntPool _recycleBin = new AutoIntPool(); private int _numStates; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DawgBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public List<HREFE1> getHREFE1() { if (hrefe1 == null) { hrefe1 = new ArrayList<HREFE1>(); } return this.hrefe1; } /** * Gets the value of the hadre1 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 hadre1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHADRE1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link HADRE1 } * * */ public List<HADRE1> getHADRE1() { if (hadre1 == null) { hadre1 = new ArrayList<HADRE1>(); } return this.hadre1; } /** * Gets the value of the htrsd1 property. * * @return * possible object is * {@link HTRSD1 } * */ public HTRSD1 getHTRSD1() { return htrsd1; } /** * Sets the value of the htrsd1 property. * * @param value * allowed object is
* {@link HTRSD1 } * */ public void setHTRSD1(HTRSD1 value) { this.htrsd1 = value; } /** * Gets the value of the packin property. * * @return * possible object is * {@link PACKINXlief } * */ public PACKINXlief getPACKIN() { return packin; } /** * Sets the value of the packin property. * * @param value * allowed object is * {@link PACKINXlief } * */ public void setPACKIN(PACKINXlief value) { this.packin = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HEADERXlief.java
2
请完成以下Java代码
public class BenchMark { @State(Scope.Benchmark) public static class Log { public int x = 8; } @State(Scope.Benchmark) public static class ExecutionPlan { @Param({ "100", "200", "300", "500", "1000" }) public int iterations; public Hasher murmur3; public String password = "4v3rys3kur3p455w0rd"; @Setup(Level.Invocation) public void setUp() { murmur3 = Hashing.murmur3_128().newHasher(); } } @Fork(value = 1, warmups = 1) @Benchmark @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) public void benchMurmur3_128(ExecutionPlan plan) { for (int i = plan.iterations; i > 0; i--) { plan.murmur3.putString(plan.password, Charset.defaultCharset()); } plan.murmur3.hash(); } @Benchmark @Fork(value = 1, warmups = 1) @BenchmarkMode(Mode.Throughput) public void init() { // Do nothing } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public void doNothing() { } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public void objectCreation() { new Object(); }
@Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public Object pillarsOfCreation() { return new Object(); } @Benchmark @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.AverageTime) public void blackHole(Blackhole blackhole) { blackhole.consume(new Object()); } @Benchmark public double foldedLog() { int x = 8; return Math.log(x); } @Benchmark public double log(Log input) { return Math.log(input.x); } }
repos\tutorials-master\jmh\src\main\java\com\baeldung\BenchMark.java
1
请完成以下Java代码
public JettyClientHttpRequestFactoryBuilder withClientConnectorCustomizerCustomizer( Consumer<ClientConnector> clientConnectorCustomizerCustomizer) { Assert.notNull(clientConnectorCustomizerCustomizer, "'clientConnectorCustomizerCustomizer' must not be null"); return new JettyClientHttpRequestFactoryBuilder(getCustomizers(), this.httpClientBuilder.withClientConnectorCustomizerCustomizer(clientConnectorCustomizerCustomizer)); } /** * Return a new {@link JettyClientHttpRequestFactoryBuilder} that applies the given * customizer. This can be useful for applying pre-packaged customizations. * @param customizer the customizer to apply * @return a new {@link JettyClientHttpRequestFactoryBuilder} * @since 4.0.0 */ public JettyClientHttpRequestFactoryBuilder with(UnaryOperator<JettyClientHttpRequestFactoryBuilder> customizer) { return customizer.apply(this); } @Override protected JettyClientHttpRequestFactory createClientHttpRequestFactory(HttpClientSettings settings) { HttpClient httpClient = this.httpClientBuilder.build(settings.withTimeouts(null, null)); JettyClientHttpRequestFactory requestFactory = new JettyClientHttpRequestFactory(httpClient); PropertyMapper map = PropertyMapper.get(); map.from(settings::connectTimeout).asInt(Duration::toMillis).to(requestFactory::setConnectTimeout);
map.from(settings::readTimeout).asInt(Duration::toMillis).to(requestFactory::setReadTimeout); return requestFactory; } static class Classes { static final String HTTP_CLIENT = "org.eclipse.jetty.client.HttpClient"; static boolean present(@Nullable ClassLoader classLoader) { return ClassUtils.isPresent(HTTP_CLIENT, classLoader); } } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\JettyClientHttpRequestFactoryBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public long getAccountsByPermissionUsingCQ(Permission permission) throws ParseException { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class); Root<Account> accountRoot = criteriaQuery.from(Account.class); List<Predicate> predicateList = new ArrayList<>(); // list of predicates that will go in where clause predicateList.add(builder.equal(accountRoot.get("permission"), permission)); criteriaQuery.select(builder.count(accountRoot)) .where(builder.and(predicateList.toArray(new Predicate[0]))); return entityManager.createQuery(criteriaQuery) .getSingleResult(); } public long getAccountsByPermissionAndCreateOnUsingCQ(Permission permission, Date date) throws ParseException { // creating criteria builder and query CriteriaBuilder builder = entityManager.getCriteriaBuilder(); // create builder CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);// query instance Root<Account> accountRoot = criteriaQuery.from(Account.class); // root instance // list of predicates that will go in where clause List<Predicate> predicateList = new ArrayList<>(); predicateList.add(builder.equal(accountRoot.get("permission"), permission)); predicateList.add(builder.greaterThan(accountRoot.get("createdOn"), new Timestamp(date.getTime()))); // select query criteriaQuery.select(builder.count(accountRoot)) .where(builder.and(predicateList.toArray(new Predicate[0]))); // execute and get the result return entityManager.createQuery(criteriaQuery) .getSingleResult();
} public long getAccountsUsingJPQL() throws ParseException { Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a"); return (long) query.getSingleResult(); } public long getAccountsByPermissionUsingJPQL(Permission permission) throws ParseException { Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a WHERE a.permission = ?1"); query.setParameter(1, permission); return (long) query.getSingleResult(); } public long getAccountsByPermissionAndCreatedOnUsingJPQL(Permission permission, Date date) throws ParseException { Query query = entityManager.createQuery("SELECT COUNT(*) FROM Account a WHERE a.permission = ?1 and a.createdOn > ?2"); query.setParameter(1, permission); query.setParameter(2, new Timestamp(date.getTime())); return (long) query.getSingleResult(); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\java\com\baeldung\countrows\service\AccountStatsLogic.java
2
请在Spring Boot框架中完成以下Java代码
public List<DPLAC1> getDPLAC1() { if (dplac1 == null) { dplac1 = new ArrayList<DPLAC1>(); } return this.dplac1; } /** * Gets the value of the dadre1 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 dadre1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDADRE1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DADRE1 } * * */ public List<DADRE1> getDADRE1() { if (dadre1 == null) { dadre1 = new ArrayList<DADRE1>(); } return this.dadre1; } /** * Gets the value of the dtrsd1 property. * * @return * possible object is * {@link DTRSD1 } * */ public DTRSD1 getDTRSD1() { return dtrsd1; } /** * Sets the value of the dtrsd1 property. * * @param value * allowed object is * {@link DTRSD1 } * */ public void setDTRSD1(DTRSD1 value) { this.dtrsd1 = value; } /** * Gets the value of the dmark1 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 dmark1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDMARK1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list
* {@link DMARK1 } * * */ public List<DMARK1> getDMARK1() { if (dmark1 == null) { dmark1 = new ArrayList<DMARK1>(); } return this.dmark1; } /** * Gets the value of the dqvar1 property. * * @return * possible object is * {@link DQVAR1 } * */ public DQVAR1 getDQVAR1() { return dqvar1; } /** * Sets the value of the dqvar1 property. * * @param value * allowed object is * {@link DQVAR1 } * */ public void setDQVAR1(DQVAR1 value) { this.dqvar1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DETAILXlief.java
2
请完成以下Java代码
protected void loadDocumentDetails() { setNoCurrency(); final I_M_Requisition req = getModel(I_M_Requisition.class); setDateDoc(req.getDateDoc()); setDateAcct(req.getDateDoc()); // Amounts setAmount(AMTTYPE_Gross, req.getTotalLines()); setAmount(AMTTYPE_Net, req.getTotalLines()); setDocLines(loadLines(req)); } private List<DocLine_Requisition> loadLines(I_M_Requisition req) { final List<DocLine_Requisition> list = new ArrayList<>(); final MRequisition reqPO = LegacyAdapters.convertToPO(req); for (final I_M_RequisitionLine line : reqPO.getLines()) { DocLine_Requisition docLine = new DocLine_Requisition(line, this); list.add(docLine); }
return list; } @Override public BigDecimal getBalance() { return BigDecimal.ZERO; } // getBalance @Override public List<Fact> createFacts(AcctSchema as) { return ImmutableList.of(); } } // Doc_Requisition
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Requisition.java
1
请在Spring Boot框架中完成以下Java代码
public class DedicatedJpaAuditLogDao extends JpaAuditLogDao { @Autowired @Qualifier(EVENTS_JDBC_TEMPLATE) private JdbcTemplate jdbcTemplate; @PersistenceContext(unitName = EVENTS_PERSISTENCE_UNIT) private EntityManager entityManager; public DedicatedJpaAuditLogDao(AuditLogRepository auditLogRepository, DedicatedEventsSqlPartitioningRepository partitioningRepository) { super(auditLogRepository, partitioningRepository); } @Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER) @Override public AuditLog save(TenantId tenantId, AuditLog domain) { return super.save(tenantId, domain); } @Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER) @Override public AuditLog saveAndFlush(TenantId tenantId, AuditLog domain) { return super.saveAndFlush(tenantId, domain); } @Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER) @Override public void removeById(TenantId tenantId, UUID id) { super.removeById(tenantId, id); } @Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER)
@Override public void removeAllByIds(Collection<UUID> ids) { super.removeAllByIds(ids); } @Override protected EntityManager getEntityManager() { return entityManager; } @Override protected JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\audit\DedicatedJpaAuditLogDao.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Date> getLogins() { return logins; } public void setLogins(List<Date> logins) { this.logins = logins; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode());
return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\User.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(final String firstname) { this.firstname = firstname; }
public String getSurname() { return surname; } public void setSurname(final String surname) { this.surname = surname; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } }
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\entity\Person.java
1
请完成以下Java代码
private void shrink() { // if (HanLP.Config.DEBUG) // { // System.err.printf("释放内存 %d bytes\n", base.length - size - 65535); // } int nbase[] = new int[size + 65535]; System.arraycopy(base, 0, nbase, 0, size); base = nbase; int ncheck[] = new int[size + 65535]; System.arraycopy(check, 0, ncheck, 0, size); check = ncheck; } /** * 打印统计信息 */ // public void report() // {
// System.out.println("size: " + size); // int nonZeroIndex = 0; // for (int i = 0; i < base.length; i++) // { // if (base[i] != 0) nonZeroIndex = i; // } // System.out.println("BaseUsed: " + nonZeroIndex); // nonZeroIndex = 0; // for (int i = 0; i < check.length; i++) // { // if (check[i] != 0) nonZeroIndex = i; // } // System.out.println("CheckUsed: " + nonZeroIndex); // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\DoubleArrayTrie.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true # MySQL5Dialect doesn't lock at all # spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect # MySQL5InnoDBDialect work as expected # spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect # MySQL8Dialec
t work as expected spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.datasource.initialization-mode=always spring.datasource.platform=mysql spring.jpa.open-in-view=false
repos\Hibernate-SpringBoot-master\HibernateSpringBootDeadlockExample\src\main\resources\application.properties
2
请完成以下Java代码
public WidgetTypeId getExternalIdByInternal(WidgetTypeId internalId) { return Optional.ofNullable(widgetTypeRepository.getExternalIdById(internalId.getId())) .map(WidgetTypeId::new).orElse(null); } @Override public List<WidgetsBundleWidget> findWidgetsBundleWidgetsByWidgetsBundleId(UUID tenantId, UUID widgetsBundleId) { return DaoUtil.convertDataList(widgetsBundleWidgetRepository.findAllByWidgetsBundleId(widgetsBundleId)); } @Override public void saveWidgetsBundleWidget(WidgetsBundleWidget widgetsBundleWidget) { widgetsBundleWidgetRepository.save(new WidgetsBundleWidgetEntity(widgetsBundleWidget)); } @Override public void removeWidgetTypeFromWidgetsBundle(UUID widgetsBundleId, UUID widgetTypeId) { widgetsBundleWidgetRepository.deleteById(new WidgetsBundleWidgetCompositeKey(widgetsBundleId, widgetTypeId)); } @Override public PageData<WidgetTypeId> findAllWidgetTypesIds(PageLink pageLink) { return DaoUtil.pageToPageData(widgetTypeRepository.findAllIds(DaoUtil.toPageable(pageLink)).map(WidgetTypeId::new)); } @Override public List<WidgetTypeInfo> findByTenantAndImageLink(TenantId tenantId, String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByTenantAndImageUrl(tenantId.getId(), imageUrl, limit)); } @Override public List<WidgetTypeInfo> findByImageLink(String imageUrl, int limit) { return DaoUtil.convertDataList(widgetTypeInfoRepository.findByImageUrl(imageUrl, limit));
} @Override public PageData<WidgetTypeDetails> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override public List<WidgetTypeFields> findNextBatch(UUID id, int batchSize) { return widgetTypeRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit)); } @Override public List<EntityInfo> findByResource(String reference, int limit) { return widgetTypeInfoRepository.findWidgetTypeInfosByResourceLink(reference, PageRequest.of(0, limit)); } @Override public EntityType getEntityType() { return EntityType.WIDGET_TYPE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\widget\JpaWidgetTypeDao.java
1
请在Spring Boot框架中完成以下Java代码
public class PosilkaSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN") .and() .withUser("hamdamboy").password(passwordEncoder().encode("dam123")).roles("USER"); } /** * This is Http security, consists of all incoming requests. * **/ @Override protected void configure(HttpSecurity http) throws Exception { /* http .formLogin() .loginPage("/login.html").loginProcessingUrl("/login").permitAll(); http .logout() .logoutUrl("/logout"); http .csrf().disable(); http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .and()
.httpBasic(); */ http .authorizeRequests() .antMatchers("/index").permitAll() .antMatchers("/admin/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\9.PosilkaAdmin\src\main\java\posilka\admin\security\PosilkaSecurity.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> delete(@RequestParam(name = "id", required = true) String id) { sysGatewayRouteService.deleteById(id); return Result.ok("删除路由成功"); } /** * 查询被删除的列表 * @return */ @RequestMapping(value = "/deleteList", method = RequestMethod.GET) public Result<List<SysGatewayRoute>> deleteList(HttpServletRequest request) { Result<List<SysGatewayRoute>> result = new Result<>(); List<SysGatewayRoute> list = sysGatewayRouteService.getDeletelist(); result.setSuccess(true); result.setResult(list); return result; } /** * 还原被逻辑删除的路由 * * @param jsonObject * @return */ @RequiresPermissions("system:gateway:putRecycleBin") @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT) public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) { try { String ids = jsonObject.getString("ids"); if (StringUtils.isNotBlank(ids)) { sysGatewayRouteService.revertLogicDeleted(Arrays.asList(ids.split(","))); return Result.ok("操作成功!"); } } catch (Exception e) { e.printStackTrace(); return Result.error("操作失败!"); } return Result.ok("还原成功"); } /** * 彻底删除路由 * * @param ids 被删除的路由ID,多个id用半角逗号分割 * @return */ @RequiresPermissions("system:gateway:deleteRecycleBin") @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE) public Result deleteRecycleBin(@RequestParam("ids") String ids) { try { if (StringUtils.isNotBlank(ids)) { sysGatewayRouteService.deleteLogicDeleted(Arrays.asList(ids.split(",")));
} return Result.ok("删除成功!"); } catch (Exception e) { e.printStackTrace(); return Result.error("删除失败!"); } } /** * 复制路由 * * @param id 路由id * @return */ @RequiresPermissions("system:gateway:copyRoute") @RequestMapping(value = "/copyRoute", method = RequestMethod.GET) public Result<SysGatewayRoute> copyRoute(@RequestParam(name = "id", required = true) String id, HttpServletRequest req) { Result<SysGatewayRoute> result = new Result<>(); SysGatewayRoute sysGatewayRoute= sysGatewayRouteService.copyRoute(id); result.setResult(sysGatewayRoute); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysGatewayRouteController.java
2
请完成以下Java代码
public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } /** * Gets the value of the uri property. * * @return * possible object is * {@link String } * */ public String getURI() { return uri;
} /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setURI(String value) { this.uri = 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\ReferenceType.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultWidgetTypeService extends AbstractTbEntityService implements TbWidgetTypeService { private final WidgetTypeService widgetTypeService; private final TbResourceService tbResourceService; @Override public WidgetTypeDetails save(WidgetTypeDetails entity, SecurityUser user) throws Exception { return this.save(entity, false, user); } @Override public WidgetTypeDetails save(WidgetTypeDetails widgetTypeDetails, boolean updateExistingByFqn, SecurityUser user) throws Exception { TenantId tenantId = widgetTypeDetails.getTenantId(); if (widgetTypeDetails.getId() == null && StringUtils.isNotEmpty(widgetTypeDetails.getFqn()) && updateExistingByFqn) { WidgetType widgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(tenantId, widgetTypeDetails.getFqn()); if (widgetType != null) { widgetTypeDetails.setId(widgetType.getId()); } } if (CollectionUtils.isNotEmpty(widgetTypeDetails.getResources())) { tbResourceService.importResources(widgetTypeDetails.getResources(), user); } ActionType actionType = widgetTypeDetails.getId() == null ? ActionType.ADDED : ActionType.UPDATED; try { WidgetTypeDetails savedWidgetTypeDetails = checkNotNull(widgetTypeService.saveWidgetType(widgetTypeDetails)); autoCommit(user, savedWidgetTypeDetails.getId()); logEntityActionService.logEntityAction(tenantId, savedWidgetTypeDetails.getId(), savedWidgetTypeDetails, null, actionType, user); return savedWidgetTypeDetails; } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGET_TYPE), widgetTypeDetails, actionType, user, e); throw e; } }
@Override public void delete(WidgetTypeDetails widgetTypeDetails, User user) { ActionType actionType = ActionType.DELETED; TenantId tenantId = widgetTypeDetails.getTenantId(); try { widgetTypeService.deleteWidgetType(widgetTypeDetails.getTenantId(), widgetTypeDetails.getId()); logEntityActionService.logEntityAction(tenantId, widgetTypeDetails.getId(), widgetTypeDetails, null, actionType, user); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGET_TYPE), actionType, user, e, widgetTypeDetails.getId()); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\widgets\type\DefaultWidgetTypeService.java
2
请完成以下Java代码
public class InvoiceCandidatesStorage { @Getter private final GroupId groupId; private final boolean performDatabaseChanges; private final ImmutableMap<InvoiceCandidateId, I_C_Invoice_Candidate> invoiceCandidatesById; @Builder private InvoiceCandidatesStorage( @NonNull final GroupId groupId, @NonNull @Singular final List<I_C_Invoice_Candidate> invoiceCandidates, @NonNull final Boolean performDatabaseChanges) { this.groupId = groupId; this.performDatabaseChanges = performDatabaseChanges; invoiceCandidatesById = invoiceCandidates.stream() .peek(InvoiceCandidateCompensationGroupUtils::assertCompensationLine) .collect(GuavaCollectors.toImmutableMapByKey(record -> InvoiceCandidateId.ofRepoId(record.getC_Invoice_Candidate_ID()))); } public void save(final I_C_Invoice_Candidate compensationLinePO) { Check.assume(!compensationLinePO.isProcessed(), "Changing a processed line is not allowed: {}", compensationLinePO); // shall not happen setGroupNo(compensationLinePO); if (performDatabaseChanges) {
InterfaceWrapperHelper.save(compensationLinePO); } } private void setGroupNo(final I_C_Invoice_Candidate compensationLinePO) { if (compensationLinePO.getC_Order_CompensationGroup_ID() <= 0) { compensationLinePO.setC_Order_CompensationGroup_ID(groupId.getOrderCompensationGroupId()); } else if (compensationLinePO.getC_Order_CompensationGroup_ID() != groupId.getOrderCompensationGroupId()) { throw new AdempiereException("Invoice candidate has already another groupId set: " + compensationLinePO) .setParameter("expectedGroupId", groupId.getOrderCompensationGroupId()) .appendParametersToMessage(); } } public I_C_Invoice_Candidate getByIdIfPresent(final InvoiceCandidateId invoiceCandidateId) { return invoiceCandidatesById.get(invoiceCandidateId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidatesStorage.java
1
请完成以下Java代码
public void setModelToRecordId(int modelToRecordId) { this.modelToRecordId = modelToRecordId; } @Override public ISqlQueryFilter getFilter() { return filter; } @Override public void setFilter(ISqlQueryFilter filter) { this.filter = filter; } @Override public ISqlQueryFilter getModelFilter() { return modelFilter; } @Override public void setModelFilter(ISqlQueryFilter modelFilter) { this.modelFilter = modelFilter; } @Override public Access getRequiredAccess() { return requiredAccess; } @Override public void setRequiredAccess(final Access requiredAccess) { this.requiredAccess = requiredAccess; } @Override
public Integer getCopies() { return copies; } @Override public void setCopies(int copies) { this.copies = copies; } @Override public String getAggregationKey() { return aggregationKey; } @Override public void setAggregationKey(final String aggregationKey) { this.aggregationKey=aggregationKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java
1
请完成以下Java代码
public String getImplementationType() { return implementationType; } public void setImplementationType(String implementationType) { this.implementationType = implementationType; } public String getImplementation() { return implementation; } public void setImplementation(String implementation) { this.implementation = implementation; } public List<FieldExtension> getFieldExtensions() { return fieldExtensions; } public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public String getOnTransaction() { return onTransaction; } public void setOnTransaction(String onTransaction) { this.onTransaction = onTransaction; } public String getCustomPropertiesResolverImplementationType() { return customPropertiesResolverImplementationType; } public void setCustomPropertiesResolverImplementationType(String customPropertiesResolverImplementationType) { this.customPropertiesResolverImplementationType = customPropertiesResolverImplementationType; } public String getCustomPropertiesResolverImplementation() { return customPropertiesResolverImplementation; } public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } public ActivitiListener clone() { ActivitiListener clone = new ActivitiListener(); clone.setValues(this); return clone; } public void setValues(ActivitiListener otherListener) { setEvent(otherListener.getEvent()); setImplementation(otherListener.getImplementation()); setImplementationType(otherListener.getImplementationType()); fieldExtensions = new ArrayList<FieldExtension>(); if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherListener.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ActivitiListener.java
1
请完成以下Java代码
protected void onRecordCopied(final PO to, final PO from, final CopyTemplate template) {} private void fireOnRecordAndChildrenCopied(final PO to, final PO from, final CopyTemplate template) {onRecordAndChildrenCopied(to, from, template);} protected void onRecordAndChildrenCopied(final PO to, final PO from, final CopyTemplate template) {} private Iterator<Object> retrieveChildPOsForParent(final CopyTemplate childTemplate, final PO parentPO) { final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(childTemplate.getTableName()) .addEqualsFilter(childTemplate.getLinkColumnName(), parentPO.get_ID()); childTemplate.getOrderByColumnNames().forEach(queryBuilder::orderBy); return queryBuilder .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .create() .iterate(Object.class); } /** * @return true if the record shall be copied */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") protected boolean isCopyRecord(final PO fromPO) {return true;} protected boolean isCopyChildRecord(final CopyTemplate parentTemplate, final PO fromChildPO, final CopyTemplate childTemplate) {return true;} @Override public final GeneralCopyRecordSupport setParentLink(@NonNull final PO parentPO, @NonNull final String parentLinkColumnName) { this.parentPO = parentPO; this.parentLinkColumnName = parentLinkColumnName; return this; } @Override public final GeneralCopyRecordSupport setAdWindowId(final @Nullable AdWindowId adWindowId) { this.adWindowId = adWindowId; return this; } @SuppressWarnings("SameParameterValue")
@Nullable protected final <T> T getParentModel(final Class<T> modelType) { return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null; } private int getParentID() { return parentPO != null ? parentPO.get_ID() : -1; } /** * Allows other modules to install customer code to be executed each time a record was copied. */ @Override public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!recordCopiedListeners.contains(listener)) { recordCopiedListeners.add(listener); } return this; } @Override public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!childRecordCopiedListeners.contains(listener)) { childRecordCopiedListeners.add(listener); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeController { private final EmployeeService employeeService; @GetMapping(value = "/employee") public String showEmployeeForm(Model model) { model.addAttribute("employee", new Employee()); return "employee/createEmployeeForm"; } @PostMapping(path = "/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) public String saveEmployee(@ModelAttribute Employee employee) { employeeService.save(employee); return "employee/success"; }
@PostMapping(path = "/requestpart/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) public ResponseEntity<Object> saveEmployee(@RequestPart Employee employee, @RequestPart MultipartFile document) { employee.setDocument(document); employeeService.save(employee); return ResponseEntity.ok().build(); } @PostMapping(path = "/requestparam/employee", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) public ResponseEntity<Object> saveEmployee(@RequestParam String name, @RequestPart MultipartFile document) { Employee employee = new Employee(name, document); employeeService.save(employee); return ResponseEntity.ok().build(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\multipartupload\EmployeeController.java
2
请完成以下Java代码
public class HasNextVsHasNextLineDemo { private static final String LINE = "----------------------------"; private static final String END_LINE = "--------OUTPUT--END---------\n"; private static final String INPUT = new StringBuilder() .append("magic\tproject\n") .append(" database: oracle\n") .append("dependencies:\n") .append("spring:foo:bar\n") .append("\n").toString(); private static void hasNextBasic() { printHeader("hasNext() Basic"); Scanner scanner = new Scanner(INPUT); while (scanner.hasNext()) { log.info(scanner.next()); } log.info(END_LINE); scanner.close(); } private static void hasNextWithDelimiter() { printHeader("hasNext() with delimiter"); Scanner scanner = new Scanner(INPUT); while (scanner.hasNext()) { String token = scanner.next(); if ("dependencies:".equals(token)) { scanner.useDelimiter(":"); } log.info(token); } log.info(END_LINE); scanner.close(); } private static void hasNextWithDelimiterFixed() { printHeader("hasNext() with delimiter FIX"); Scanner scanner = new Scanner(INPUT); while (scanner.hasNext()) { String token = scanner.next(); if ("dependencies:".equals(token)) { scanner.useDelimiter(":|\\s+"); } log.info(token); } log.info(END_LINE); scanner.close(); } private static void addLineNumber() { printHeader("add line number by hasNextLine() "); Scanner scanner = new Scanner(INPUT); int i = 0; while (scanner.hasNextLine()) { log.info(String.format("%d|%s", ++i, scanner.nextLine()));
} log.info(END_LINE); scanner.close(); } private static void printHeader(String title) { log.info(LINE); log.info(title); log.info(LINE); } public static void main(String[] args) throws IOException { setLogger(); hasNextBasic(); hasNextWithDelimiter(); hasNextWithDelimiterFixed(); addLineNumber(); } //overwrite the logger config private static void setLogger() throws IOException { InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties"); Properties props = new Properties(); props.load(is); LogManager.resetConfiguration(); PropertyConfigurator.configure(props); } }
repos\tutorials-master\core-java-modules\core-java-scanner\src\main\java\com\baeldung\scanner\HasNextVsHasNextLineDemo.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public String getActivityId() { return activityId; } public String getType() { return type; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getDetailId() { return detailId; } public String[] getProcessInstanceIds() { return processInstanceIds; } public Date getOccurredBefore() {
return occurredBefore; } public Date getOccurredAfter() { return occurredAfter; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isInitial() { return initial; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } public boolean isDisableHistory() { return disableHistory; } public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory; } public DmnElement getDmnElement() { return dmnElement; } public void setDmnElement(DmnElement dmnElement) { this.dmnElement = dmnElement; } public DecisionExecutionAuditContainer getDecisionExecution() { return decisionExecution; } public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) { this.decisionExecution = decisionExecution; } }
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java
1
请完成以下Java代码
private String translateDictValue(String code, String text, String table, String key) { if(oConvertUtils.isEmpty(key)) { return null; } StringBuffer textValue=new StringBuffer(); String[] keys = key.split(","); for (String k : keys) { String tmpValue = null; log.debug(" 字典 key : "+ k); if (k.trim().length() == 0) { continue; //跳过循环 } // 代码逻辑说明: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题----- if (!StringUtils.isEmpty(table)){ log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code); String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim()); if (redisTemplate.hasKey(keyString)){ try { tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); } catch (Exception e) { log.warn(e.getMessage()); } }else { tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim()); } }else { String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim()); if (redisTemplate.hasKey(keyString)){ try { tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString)); } catch (Exception e) { log.warn(e.getMessage()); } }else { tmpValue = commonApi.translateDict(code, k.trim()); } } if (tmpValue != null) { if (!"".equals(textValue.toString())) { textValue.append(","); } textValue.append(tmpValue); }
} return textValue.toString(); } /** * 检测返回结果集中是否包含Dict注解 * @param records * @return */ private Boolean checkHasDict(List<Object> records){ if(oConvertUtils.isNotEmpty(records) && records.size()>0){ for (Field field : oConvertUtils.getAllFields(records.get(0))) { if (oConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) { return true; } } } return false; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\aspect\DictAspect.java
1
请在Spring Boot框架中完成以下Java代码
class ArticlesFinder { private final ArticleRepository articleRepository; private final UserRepository userRepository; private final ArticleMapper articleMapper; public Mono<MultipleArticlesView> findArticles(String tag, String author, String favoritedByUser, int offset, int limit, Optional<User> currentUser) { return createFindArticleRequest(tag, author, favoritedByUser, offset, limit) .flatMapMany(articleRepository::findNewestArticlesFilteredBy) .flatMap(article -> articleMapper.mapToArticleView(article, currentUser)) .collectList() .map(MultipleArticlesView::of); } private Mono<FindArticlesRequest> createFindArticleRequest(String tag, String author, String favoritedByUser, int offset, int limit) { var request = new FindArticlesRequest() .setOffset(offset) .setLimit(limit) .setTag(tag); return addToRequestAuthorId(author, request) .then(addToRequestFavoritedBy(favoritedByUser, request)) .thenReturn(request); } private Mono<User> addToRequestFavoritedBy(String favoritedByUser, FindArticlesRequest request) { return getFavoritedBy(favoritedByUser).doOnNext(request::setFavoritedBy); }
private Mono<String> addToRequestAuthorId(String author, FindArticlesRequest request) { return getAuthorId(author).doOnNext(request::setAuthorId); } private Mono<String> getAuthorId(String author) { if (author == null) { return Mono.empty(); } return userRepository.findByUsername(author).map(User::getId); } private Mono<User> getFavoritedBy(String favoritedBy) { if (favoritedBy == null) { return Mono.empty(); } return userRepository.findByUsername(favoritedBy); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\ArticlesFinder.java
2
请完成以下Java代码
public Long getLongValue() { return longValue; } @Override public void setLongValue(Long longValue) { this.longValue = longValue; } @Override public Double getDoubleValue() { return doubleValue; } @Override public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } @Override public String getTextValue() { return textValue; } @Override public void setTextValue(String textValue) { this.textValue = textValue; } @Override public String getTextValue2() { return textValue2; } @Override public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } @Override public Object getCachedValue() { return cachedValue; } @Override public void setCachedValue(Object cachedValue) { this.cachedValue = cachedValue; } // common methods /////////////////////////////////////////////////////////////// @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("HistoricDetailVariableInstanceUpdateEntity["); sb.append("id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null"); if (longValue != null) { sb.append(", longValue=").append(longValue); } if (doubleValue != null) { sb.append(", doubleValue=").append(doubleValue); } if (textValue != null) { sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40)); } if (textValue2 != null) { sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40)); } if (byteArrayRef != null && byteArrayRef.getId() != null) { sb.append(", byteArrayValueId=").append(byteArrayRef.getId()); } sb.append("]"); return sb.toString(); } @Override public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntityImpl.java
1
请完成以下Java代码
public boolean accept(final T model) { if(!InterfaceWrapperHelper.isInstanceOf(model, IPOReferenceAware.class)) { return false; } final IPOReferenceAware referencingModel = InterfaceWrapperHelper.create(model, IPOReferenceAware.class); final int tableId = Services.get(IADTableDAO.class).retrieveTableId(InterfaceWrapperHelper.getModelTableName(referencedModel)); return referencingModel.getAD_Table_ID() == tableId && referencingModel.getRecord_ID() == InterfaceWrapperHelper.getId(referencedModel); } @Override public String getSql() { buildSql(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx) { buildSql(); return sqlParams; }
private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null; private final void buildSql() { if (sqlBuilt) { return; } sqlWhereClause = "Record_ID = ? AND AD_Table_ID = ?"; sqlParams = new ArrayList<Object>(); sqlParams.add(InterfaceWrapperHelper.getId(referencedModel)); sqlParams.add(MTable.getTable_ID(InterfaceWrapperHelper.getModelTableName(referencedModel))); sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ReferencingPOFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentId implements RepoIdAware { @JsonCreator public static PaymentId ofRepoId(final int repoId) {return new PaymentId(repoId);} @Nullable public static PaymentId ofRepoIdOrNull(final int repoId) {return repoId > 0 ? new PaymentId(repoId) : null;} public static Optional<PaymentId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static int toRepoId(final PaymentId id) { return id != null ? id.getRepoId() : -1; } public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<PaymentId> ids) { if (ids.isEmpty()) { return ImmutableSet.of();
} return ids.stream().map(PaymentId::getRepoId).collect(ImmutableSet.toImmutableSet()); } int repoId; private PaymentId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Payment_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable PaymentId id1, @Nullable PaymentId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\payment\PaymentId.java
2
请完成以下Java代码
protected String doIt() throws Exception { final IPaymentStringDataProvider dataProvider = getDataProvider(); final I_C_BP_BankAccount bpBankAccount; if (willCreateANewBandAccountParam) { bpBankAccount = dataProvider.createNewC_BP_BankAccount(this, bPartnerParam.getC_BPartner_ID()); } else { Check.assumeNotNull(bankAccountParam, "bankAccountParam not null"); bpBankAccount = bankAccountParam; } final PaymentString paymentString = dataProvider.getPaymentString(); final I_C_Payment_Request paymentRequestTemplate = paymentStringProcessService.createPaymentRequestTemplate(bpBankAccount, amountParam, paymentString); paymentStringProcessService.createPaymentRequestFromTemplate(getActualInvoice(), paymentRequestTemplate); return MSG_OK; } @Override public void onParameterChanged(final String parameterName) { if (!PARAM_fullPaymentString.equals(parameterName) && !PARAM_C_BPartner_ID.equals(parameterName)) { // only update on magic payment string or bpartner return; } if (Check.isEmpty(fullPaymentStringParam, true)) { // do nothing if it's empty return; } final IPaymentStringDataProvider dataProvider; try { dataProvider = getDataProvider(); } catch (final PaymentStringParseException pspe) { throw pspe.setParameter("fullPaymentStringParam", fullPaymentStringParam).appendParametersToMessage(); } final PaymentString paymentString = dataProvider.getPaymentString(); final I_C_Invoice actualInvoice = getActualInvoice(); final I_C_BP_BankAccount bpBankAccountExisting = paymentStringProcessService.getAndVerifyBPartnerAccountOrNull(dataProvider, actualInvoice.getC_BPartner_ID()); if (bpBankAccountExisting != null) { bPartnerParam = bPartnerDAO.getById(bpBankAccountExisting.getC_BPartner_ID()); bankAccountParam = bpBankAccountExisting; } else { /* * If the C_BPartner is set from the field (manually by the user), * C_BP_BankAccount will be created by this process when the user presses "Start". * * If the C_BPartner is NOT set, show error and ask the user to set the partner before adding the magic payment string.
* */ if (bPartnerParam == null) { throw new AdempiereException(MSG_CouldNotFindOrCreateBPBankAccount, paymentString.getPostAccountNo()); } else { bankAccountNumberParam = paymentString.getPostAccountNo(); willCreateANewBandAccountParam = true; } } amountParam = paymentString.getAmount(); } private IPaymentStringDataProvider getDataProvider() { return paymentStringProcessService.parseQRPaymentString(fullPaymentStringParam); } private I_C_Invoice getActualInvoice() { return invoiceDAO.getByIdInTrx(InvoiceId.ofRepoId(getRecord_ID())); } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { return paymentStringProcessService.checkPreconditionsApplicable(context); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\banking\payment\process\WEBUI_Import_Payment_Request_For_Purchase_Invoice_QRCode.java
1
请在Spring Boot框架中完成以下Java代码
public class Service<S> extends ParametrizationAware<S> { private final JpaRepository<S, Long> repository; public Service(JpaRepository<S, Long> repository) { this.repository = repository; } public JpaRepository<S, Long> getRepository() { return repository; } public int countNumberOfRequestsWithFunction(ToIntFunction<List<S>> function) { return function.applyAsInt(repository.findAll()); } public Optional<S> getUserById(Long id) { return repository.findById(id); } public void deleteAll() { repository.deleteAll(); } public List<S> saveAll(Iterable<S> entities) {
return repository.saveAll(entities); } public List<S> findAll() { return repository.findAll(); } public Optional<S> getUserByIdWithPredicate(long id, Predicate<S> predicate) { Optional<S> user = repository.findById(id); user.ifPresent(predicate::test); return user; } public int getUserByIdWithFunction(Long id, ToIntFunction<S> function) { Optional<S> optionalUser = repository.findById(id); if (optionalUser.isPresent()) { return function.applyAsInt(optionalUser.get()); } else { return 0; } } public void save(S entity) { repository.save(entity); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\Service.java
2
请完成以下Java代码
static public MPrintTableFormat getDefault(final Properties ctx) { MPrintTableFormat tf = null; String sql = "SELECT * FROM AD_PrintTableFormat " + "WHERE AD_Client_ID IN (0,?) AND IsActive='Y' " + "ORDER BY IsDefault DESC, AD_Client_ID DESC"; int AD_Client_ID = Env.getAD_Client_ID(ctx); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, AD_Client_ID); rs = pstmt.executeQuery(); if (rs.next()) tf = new MPrintTableFormat(ctx, rs, null); } catch (Exception e) { s_log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return tf; } // get /** * Get the Image * * @return image */ public Image getImage() { if (m_image != null) { return m_image; } // if (isImageIsAttached()) { final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); final List<AttachmentEntry> entries = attachmentEntryService.getByReferencedRecord(TableRecordReference.of(Table_Name, getAD_PrintTableFormat_ID())); if (entries.isEmpty()) { log.warn("No Attachment entry - ID=" + get_ID()); return null; } final byte[] imageData = attachmentEntryService.retrieveData(entries.get(0).getId()); if (imageData != null) { m_image = Toolkit.getDefaultToolkit().createImage(imageData); } if (m_image != null) { log.debug(entries.get(0).getFilename() + " - Size=" + imageData.length); } else { log.warn(entries.get(0).getFilename() + " - not loaded (must be gif or jpg) - ID=" + get_ID()); } } else if (getImageURL() != null) { URL url;
try { url = new URL(getImageURL()); Toolkit tk = Toolkit.getDefaultToolkit(); m_image = tk.getImage(url); } catch (MalformedURLException e) { log.warn("Malformed URL - " + getImageURL(), e); } } return m_image; } // getImage /** * Get the Image * * @return image */ public Image getImageWaterMark() { if (m_image_water_mark != null) { return m_image_water_mark; } // if (getAD_Image_ID() > 0) { m_image_water_mark = MImage.get(getCtx(), getAD_Image_ID()).getImage(); } return m_image_water_mark; } // getImage } // MPrintTableFormat
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintTableFormat.java
1
请完成以下Java代码
public final class SpringSecurityCoreVersion { private static final String DISABLE_CHECKS = SpringSecurityCoreVersion.class.getName().concat(".DISABLE_CHECKS"); private static final Log logger = LogFactory.getLog(SpringSecurityCoreVersion.class); /** * Global Serialization value for Spring Security classes. * @deprecated Please have each class use its own serialization version * @see SpringSecurityCoreVersionSerializableTests */ @Deprecated(forRemoval = true) public static final long SERIAL_VERSION_UID = 620L; static final @Nullable String MIN_SPRING_VERSION = getSpringVersion(); static { performVersionChecks(); } private SpringSecurityCoreVersion() { } private static void performVersionChecks() { performVersionChecks(MIN_SPRING_VERSION); } /** * Perform version checks with specific min Spring Version * @param minSpringVersion */ private static void performVersionChecks(@Nullable String minSpringVersion) { if (minSpringVersion == null) { return; } // Check Spring Compatibility String springVersion = SpringVersion.getVersion(); String version = getVersion(); if (disableChecks(springVersion, version)) { return; } // should be disabled if springVersion is null Assert.notNull(springVersion, "springVersion cannot be null");
logger.info("You are running with Spring Security Core " + version); if (new ComparableVersion(springVersion).compareTo(new ComparableVersion(minSpringVersion)) < 0) { logger.warn("**** You are advised to use Spring " + minSpringVersion + " or later with this version. You are running: " + springVersion); } } public static @Nullable String getVersion() { Package pkg = SpringSecurityCoreVersion.class.getPackage(); return (pkg != null) ? pkg.getImplementationVersion() : null; } /** * Disable if springVersion and springSecurityVersion are the same to allow working * with Uber Jars. * @param springVersion * @param springSecurityVersion * @return */ private static boolean disableChecks(@Nullable String springVersion, @Nullable String springSecurityVersion) { if (springVersion == null || springVersion.equals(springSecurityVersion)) { return true; } return Boolean.getBoolean(DISABLE_CHECKS); } /** * Loads the spring version or null if it cannot be found. * @return */ private static @Nullable String getSpringVersion() { Properties properties = new Properties(); try (InputStream is = SpringSecurityCoreVersion.class.getClassLoader() .getResourceAsStream("META-INF/spring-security.versions")) { properties.load(is); } catch (IOException | NullPointerException ex) { return null; } return properties.getProperty("org.springframework:spring-core"); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\SpringSecurityCoreVersion.java
1
请完成以下Java代码
public class LoggingModuleInterceptor extends AbstractModuleInterceptor { private final static transient Logger logger = LogManager.getLogger(LoggingModuleInterceptor.class); public static final LoggingModuleInterceptor INSTANCE = new LoggingModuleInterceptor(); private LoggingModuleInterceptor() { } /** * Logs the output of {@link ILoggerCustomizer#dumpConfig()}. * * @task https://github.com/metasfresh/metasfresh/issues/288 */ @Override public void onUserLogin(final int AD_Org_ID_IGNORED, final int AD_Role_ID_IGNORED, final int AD_User_ID_IGNORED) { logCustomizerConfig(); } private void logCustomizerConfig() { final String customizerConfig = LogManager.dumpCustomizerConfig(); // try to get the current log level for this interceptor's logger final String logLevelBkp = LogManager.getLoggerLevelName(logger);
if (Check.isEmpty(logLevelBkp)) { System.err.println("Unable to log the customizer config to logger=" + logger); System.err.println("Writing the customizer config to std-err instead"); // there is a problem, but still try to output the information. System.err.println(customizerConfig); return; } // this is the normal case. Make sure that we are loglevel info, log the information and set the logger back to its former level. try { LogManager.setLoggerLevel(logger, Level.INFO); logger.info(customizerConfig); } finally { LogManager.setLoggerLevel(logger, logLevelBkp); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\model\interceptor\LoggingModuleInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
static class JaxbJackson2ObjectMapperCustomizerConfiguration { @Autowired void addJaxbAnnotationIntrospector(com.fasterxml.jackson.databind.ObjectMapper objectMapper) { com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector jaxbAnnotationIntrospector = new com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector( objectMapper.getTypeFactory()); objectMapper.setAnnotationIntrospectors( createPair(objectMapper.getSerializationConfig(), jaxbAnnotationIntrospector), createPair(objectMapper.getDeserializationConfig(), jaxbAnnotationIntrospector)); } private com.fasterxml.jackson.databind.AnnotationIntrospector createPair( com.fasterxml.jackson.databind.cfg.MapperConfig<?> config, com.fasterxml.jackson.module.jakarta.xmlbind.JakartaXmlBindAnnotationIntrospector jaxbAnnotationIntrospector) { return com.fasterxml.jackson.databind.AnnotationIntrospector.pair(config.getAnnotationIntrospector(), jaxbAnnotationIntrospector); } }
private static final class ObjectMapperContextResolver implements ContextResolver<com.fasterxml.jackson.databind.ObjectMapper> { private final com.fasterxml.jackson.databind.ObjectMapper objectMapper; private ObjectMapperContextResolver(com.fasterxml.jackson.databind.ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public com.fasterxml.jackson.databind.ObjectMapper getContext(Class<?> type) { return this.objectMapper; } } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\JerseyAutoConfiguration.java
2
请完成以下Java代码
public String getIdPrefix() { // The name of the property is also the id of the property // therefore the id prefix is not needed return ""; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public String getId() { return name;
} @Override public Object getPersistentState() { return value; } @Override public void setId(String id) { throw new FlowableException("only provided id generation allowed for properties"); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "PropertyEntity[name=" + name + ", value=" + value + "]"; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\PropertyEntityImpl.java
1
请完成以下Java代码
public final class LookupValueFilterPredicates { public static final LookupValueFilterPredicate of(final String filter) { final String adLanguage = null; // N/A return ofFilterAndLanguage(filter, adLanguage); } public static final LookupValueFilterPredicate ofFilterAndLanguage(final String filter, final String adLanguage) { if (filter == null) { return MATCH_ALL; } final String filterNorm = filter.trim(); if (filterNorm.isEmpty()) { return MATCH_ALL; } return new ContainsLookupValueFilterPredicate(filterNorm, adLanguage); } public static interface LookupValueFilterPredicate extends Predicate<LookupValue> { @Override boolean test(LookupValue lookupValue); boolean isMatchAll(); } public static final LookupValueFilterPredicate MATCH_ALL = new LookupValueFilterPredicate() { @Override public String toString() { return "MatchAll"; }; @Override public boolean test(final LookupValue lookupValue) { return true; } @Override public boolean isMatchAll() { return true; }; }; private static final class ContainsLookupValueFilterPredicate implements LookupValueFilterPredicate { private final String filterNormalized; private final String adLanguage; private ContainsLookupValueFilterPredicate(final String filter, final String adLanguage) { super(); filterNormalized = normalizeString(filter); this.adLanguage = Check.isEmpty(adLanguage, true) ? null : adLanguage; } @Override public String toString() { return MoreObjects.toStringHelper("ContainsIgnoreCase")
.omitNullValues() .addValue(filterNormalized) .add("adLanguage", adLanguage) .toString(); } private static final String normalizeString(final String str) { return str.toLowerCase(); } @Override public boolean test(final LookupValue lookupValue) { if (lookupValue == null) { return false; } final String displayName = adLanguage != null ? lookupValue.getDisplayName(adLanguage) : lookupValue.getDisplayName(); if (displayName == null) { return false; } final String displayNameNormalized = normalizeString(displayName); return displayNameNormalized.indexOf(filterNormalized) >= 0; } @Override public boolean isMatchAll() { return false; }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupValueFilterPredicates.java
1
请完成以下Java代码
public class TokenFilter extends GenericFilterBean { private static final Logger log = LoggerFactory.getLogger(TokenFilter.class); private final TokenProvider tokenProvider; private final SecurityProperties properties; private final OnlineUserService onlineUserService; /** * @param tokenProvider Token * @param properties JWT * @param onlineUserService 用户在线 */ public TokenFilter(TokenProvider tokenProvider, SecurityProperties properties, OnlineUserService onlineUserService) { this.properties = properties; this.onlineUserService = onlineUserService; this.tokenProvider = tokenProvider; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String token = resolveToken(httpServletRequest); // 对于 Token 为空的不需要去查 Redis if(StrUtil.isNotBlank(token)){ // 获取用户Token的Key String loginKey = tokenProvider.loginKey(token); OnlineUserDto onlineUserDto = onlineUserService.getOne(loginKey); // 判断用户在线信息是否为空 if (onlineUserDto != null) { // Token 续期判断 tokenProvider.checkRenewal(token); // 获取认证信息,设置上下文 Authentication authentication = tokenProvider.getAuthentication(token); SecurityContextHolder.getContext().setAuthentication(authentication); }
} filterChain.doFilter(servletRequest, servletResponse); } /** * 初步检测Token * * @param request / * @return / */ private String resolveToken(HttpServletRequest request) { String bearerToken = request.getHeader(properties.getHeader()); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) { // 去掉令牌前缀 return bearerToken.replace(properties.getTokenStartWith(), ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\security\TokenFilter.java
1
请完成以下Java代码
public class Processor { @Benchmark @BenchmarkMode(Mode.AverageTime) public void processSerially() throws InterruptedException { for (int i = 0; i < 100; i++) { Thread.sleep(10); } } @Benchmark @BenchmarkMode(Mode.AverageTime) public void processParallelyWithExecutorService() throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(10); List<CompletableFuture<Void>> futures = new ArrayList<>(); for (int i = 0; i < 100; i++) { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }, executorService); futures.add(future); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); executorService.shutdown(); }
@Benchmark @BenchmarkMode(Mode.AverageTime) public void processParallelyWithStream() { IntStream.range(0, 100) .parallel() .forEach(i -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); } @Benchmark @BenchmarkMode(Mode.AverageTime) public void processParallelyWithStreamSupport() { Iterable<Integer> iterable = () -> IntStream.range(0, 100).iterator(); Stream<Integer> stream = StreamSupport.stream(iterable.spliterator(), true); stream.forEach(i -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-2\src\main\java\com\baeldung\concurrent\parallel\Processor.java
1
请完成以下Java代码
public int hashCode() { // NOTE: we implemented this method only to get rid of "implemented equals() but not hashCode() warning" return super.hashCode(); } @Override public String toString() { if (!isAvailable()) { return DEBUG ? "<GARBAGED: " + valueStr + ">" : "<GARBAGED>"; } else { return String.valueOf(this.get());
} } } /** * Gets internal lock used by this weak list. * * NOTE: use it only if you know what are you doing. * * @return internal lock used by this weak list. */ public final ReentrantLock getReentrantLock() { return lock; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\WeakList.java
1
请完成以下Java代码
protected boolean hasCompensationHandler(ActivityExecution execution) { return execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID) != null; } protected void createCompensateEventSubscription(ActivityExecution execution) { String compensationHandlerId = (String) execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_COMPENSATION_HANDLER_ID); ExecutionEntity executionEntity = (ExecutionEntity) execution; ActivityImpl compensationHandler = executionEntity.getProcessDefinition().findActivity(compensationHandlerId); PvmScope scopeActivity = compensationHandler.getParent(); ExecutionEntity scopeExecution = ScopeUtil.findScopeExecutionForScope(executionEntity, scopeActivity); CompensateEventSubscriptionEntity compensateEventSubscriptionEntity = CompensateEventSubscriptionEntity.createAndInsert(scopeExecution); compensateEventSubscriptionEntity.setActivity(compensationHandler); } protected boolean hasLoopCharacteristics() { return hasMultiInstanceCharacteristics(); } protected boolean hasMultiInstanceCharacteristics() { return multiInstanceActivityBehavior != null; } public MultiInstanceActivityBehavior getMultiInstanceActivityBehavior() { return multiInstanceActivityBehavior; } public void setMultiInstanceActivityBehavior(MultiInstanceActivityBehavior multiInstanceActivityBehavior) { this.multiInstanceActivityBehavior = multiInstanceActivityBehavior; }
@Override public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception { if ("compensationDone".equals(signalName)) { signalCompensationDone(execution, signalData); } else { super.signal(execution, signalName, signalData); } } protected void signalCompensationDone(ActivityExecution execution, Object signalData) { // default behavior is to join compensating executions and propagate the signal if all executions // have compensated // join compensating executions if (execution.getExecutions().isEmpty()) { if (execution.getParent() != null) { ActivityExecution parent = execution.getParent(); ((InterpretableExecution) execution).remove(); ((InterpretableExecution) parent).signal("compensationDone", signalData); } } else { ((ExecutionEntity) execution).forceUpdate(); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractBpmnActivityBehavior.java
1
请完成以下Java代码
public Set<Map.Entry<Object, Object>> entrySet() { throw new FlowableException("unsupported operation on configuration beans"); } @Override public boolean isEmpty() { throw new FlowableException("unsupported operation on configuration beans"); } @Override public Object put(Object key, Object value) { throw new FlowableException("unsupported operation on configuration beans"); } @Override public void putAll(Map<? extends Object, ? extends Object> m) { throw new FlowableException("unsupported operation on configuration beans");
} @Override public Object remove(Object key) { throw new FlowableException("unsupported operation on configuration beans"); } @Override public int size() { throw new FlowableException("unsupported operation on configuration beans"); } @Override public Collection<Object> values() { throw new FlowableException("unsupported operation on configuration beans"); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\SpringBeanFactoryProxyMap.java
1