instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx protected String doIt() { StreamUtils.dice(streamDocumentsToRepost(), 1000) .forEach(this::enqueueChunk); return MSG_OK; } private void enqueueChunk(final Collection<DocumentToRepost> documentsToRepost) { FactAcctRepostCommand.builder() .documentsToRepost(documentsToRepost) .forcePosting(forcePosting) .onErrorNotifyUserId(getUserId()) .build() .execute(); } private Stream<DocumentToRepost> streamDocumentsToRepost() { return getView().streamByIds(getSelectedRowIds(), QueryLimit.NO_LIMIT) .map(this::extractDocumentToRepost); } private DocumentToRepost extractDocumentToRepost(@NonNull final IViewRow row) { final String tableName = getTableName(); if (I_Fact_Acct.Table_Name.equals(tableName) || FactAcctFilterDescriptorsProviderFactory.FACT_ACCT_TRANSACTIONS_VIEW.equals(tableName) || TABLENAME_RV_UnPosted.equals(tableName)) { return extractDocumentToRepostFromTableAndRecordIdRow(row); } else { return extractDocumentToRepostFromRegularRow(row); } } private DocumentToRepost extractDocumentToRepostFromTableAndRecordIdRow(final IViewRow row) { final int adTableId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Table_ID, -1); final int recordId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_Record_ID, -1); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId)
.recordId(recordId) .clientId(adClientId) .build(); } private DocumentToRepost extractDocumentToRepostFromRegularRow(final IViewRow row) { final int adTableId = adTablesRepo.retrieveTableId(getTableName()); final int recordId = row.getId().toInt(); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } @Override protected void postProcess(final boolean success) { getView().invalidateSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\WEBUI_Fact_Acct_Repost_ViewRows.java
1
请在Spring Boot框架中完成以下Java代码
public SuperStreamBuilder maxLength(long bytes) { return withArgument("max-length-bytes", bytes); } /** * Set the maximum size limit for segment file. * @param bytes the max segments size in bytes * @return the builder */ public SuperStreamBuilder maxSegmentSize(long bytes) { return withArgument("x-stream-max-segment-size-bytes", bytes); } /** * Set initial replication factor for each partition. * @param count number of nodes per partition * @return the builder */ public SuperStreamBuilder initialClusterSize(int count) { return withArgument("x-initial-cluster-size", count); } /** * Set extra argument which is not covered by builder's methods. * @param key argument name * @param value argument value * @return the builder */ public SuperStreamBuilder withArgument(String key, Object value) { if ("x-queue-type".equals(key) && !"stream".equals(value)) { throw new IllegalArgumentException("Changing x-queue-type argument is not permitted"); } this.arguments.put(key, value); return this; } /** * Set the stream name. * @param name the stream name. * @return the builder */ public SuperStreamBuilder name(String name) { this.name = name; return this; } /** * Set the partitions number. * @param partitions the partitions number
* @return the builder */ public SuperStreamBuilder partitions(int partitions) { this.partitions = partitions; return this; } /** * Set a strategy to determine routing keys to use for the * partitions. The first parameter is the queue name, the second the number of * partitions, the returned list must have a size equal to the partitions. * @param routingKeyStrategy the strategy * @return the builder */ public SuperStreamBuilder routingKeyStrategy(BiFunction<String, Integer, List<String>> routingKeyStrategy) { this.routingKeyStrategy = routingKeyStrategy; return this; } /** * Builds a final Super Stream. * @return the Super Stream instance */ public SuperStream build() { if (!StringUtils.hasText(this.name)) { throw new IllegalArgumentException("Stream name can't be empty"); } if (this.partitions <= 0) { throw new IllegalArgumentException( String.format("Partitions number should be great then zero. Current value; %d", this.partitions) ); } if (this.routingKeyStrategy == null) { return new SuperStream(this.name, this.partitions, this.arguments); } return new SuperStream(this.name, this.partitions, this.routingKeyStrategy, this.arguments); } }
repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\config\SuperStreamBuilder.java
2
请在Spring Boot框架中完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "2020-06-03T22:05:05.474+0000") public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } @ApiModelProperty(example = "completed") public String getStatus() {
return status; } public void setStatus(String status) { this.status = status; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResponse.java
2
请在Spring Boot框架中完成以下Java代码
public void setSUMUP_LastSync_Timestamp (final @Nullable java.sql.Timestamp SUMUP_LastSync_Timestamp) { set_Value (COLUMNNAME_SUMUP_LastSync_Timestamp, SUMUP_LastSync_Timestamp); } @Override public java.sql.Timestamp getSUMUP_LastSync_Timestamp() { return get_ValueAsTimestamp(COLUMNNAME_SUMUP_LastSync_Timestamp); } @Override public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code) { set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code); } @Override public java.lang.String getSUMUP_merchant_code() { return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code); } @Override public void setSUMUP_Transaction_ID (final int SUMUP_Transaction_ID) { if (SUMUP_Transaction_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, SUMUP_Transaction_ID); }
@Override public int getSUMUP_Transaction_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Transaction_ID); } @Override public void setTimestamp (final java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Transaction.java
2
请在Spring Boot框架中完成以下Java代码
public class PercentRefundConfigChangeHandler extends RefundConfigChangeHandler { public static PercentRefundConfigChangeHandler newInstance( @NonNull final MoneyService moneyService, @NonNull final RefundConfig currentRefundConfig) { return new PercentRefundConfigChangeHandler(moneyService, currentRefundConfig); } private final MoneyService moneyService; private PercentRefundConfigChangeHandler( @NonNull final MoneyService moneyService, @NonNull final RefundConfig currentRefundConfig) { super(Check.assumeNotNull(currentRefundConfig, "currentRefundConfig may not be null")); Check.errorUnless(RefundBase.PERCENTAGE.equals(currentRefundConfig.getRefundBase()), "The given currentRefundConfig needs to have refundBase = PERCENTAGE; currentRefundConfig={}", currentRefundConfig); this.moneyService = moneyService; } @Override public AssignmentToRefundCandidate createNewAssignment(@NonNull final AssignmentToRefundCandidate existingAssignment) { // note: currentRefundConfig can't be null final Percent percentToApply = getCurrentRefundConfig() .getPercent() .subtract(getFormerRefundConfig().getPercent()); final Money base = existingAssignment.getMoneyBase(); final Money moneyToAssign = moneyService.percentage(percentToApply, base);
return AssignmentToRefundCandidate.builder() .refundConfigId(getCurrentRefundConfig().getId()) .assignableInvoiceCandidateId(existingAssignment.getAssignableInvoiceCandidateId()) .refundInvoiceCandidate(existingAssignment.getRefundInvoiceCandidate()) .moneyBase(existingAssignment.getMoneyBase()) .moneyAssignedToRefundCandidate(moneyToAssign) .quantityAssigendToRefundCandidate(existingAssignment.getQuantityAssigendToRefundCandidate()) .useAssignedQtyInSum(getCurrentRefundConfig().isIncludeAssignmentsWithThisConfigInSum()) .build(); } @Override protected RefundBase getExpectedRefundBase() { return RefundBase.PERCENTAGE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\allqties\refundconfigchange\PercentRefundConfigChangeHandler.java
2
请完成以下Java代码
public long getSecondsToLive() { return secondsToLive; } public void setSecondsToLive(long secondsToLive) { this.secondsToLive = secondsToLive; } public int size() { return cache.size(); } public void put(String id, Object resource) { cache.put(id, new HalResourceCacheEntry(id, resource)); ensureCapacityLimit(); } public void remove(String id) { cache.remove(id); } public Object get(String id) { HalResourceCacheEntry cacheEntry = cache.get(id); if (cacheEntry != null) { if (expired(cacheEntry)) { remove(cacheEntry.getId()); return null; } else { return cacheEntry.getResource(); } } else { return null; } } public void destroy() { cache.clear(); } protected void ensureCapacityLimit() { if (size() > getCapacity()) { List<HalResourceCacheEntry> resources = new ArrayList<HalResourceCacheEntry>(cache.values()); NavigableSet<HalResourceCacheEntry> remainingResources = new TreeSet<HalResourceCacheEntry>(COMPARATOR); // remove expired resources
for (HalResourceCacheEntry resource : resources) { if (expired(resource)) { remove(resource.getId()); } else { remainingResources.add(resource); } if (size() <= getCapacity()) { // abort if capacity is reached return; } } // if still exceed capacity remove oldest while (remainingResources.size() > capacity) { HalResourceCacheEntry resourceToRemove = remainingResources.pollFirst(); if (resourceToRemove != null) { remove(resourceToRemove.getId()); } else { break; } } } } protected boolean expired(HalResourceCacheEntry entry) { return entry.getCreateTime() + secondsToLive * 1000 < ClockUtil.getCurrentTime().getTime(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\DefaultHalResourceCache.java
1
请完成以下Java代码
protected Optional<Set<IExternalSystemChildConfigId>> getAdditionalExternalSystemConfigIds(@NonNull final ExportHUCandidate exportHUCandidate) { if (exportHUCandidate.getLinkedSourceVHuId() == null) { return Optional.empty(); } final I_M_HU sourceTopLevel = handlingUnitsBL.getTopLevelParent(exportHUCandidate.getLinkedSourceVHuId()); final HuId sourceTopLevelId = HuId.ofRepoId(sourceTopLevel.getM_HU_ID()); final TableRecordReference sourceTopLevelHUTableRecordRef = TableRecordReference.of(I_M_HU.Table_Name, sourceTopLevelId); return Optional.of(getExternalSysConfigIdsFromExportAudit(sourceTopLevelHUTableRecordRef)); } @Override protected void runPreExportHook(final TableRecordReference recordReferenceToExport) { } private void exportIfAlreadyExportedOnce(@NonNull final I_M_HU_Trace huTrace) { final ExportHUCandidate exportHUCandidate = ExportHUCandidate.builder() .huId(HuId.ofRepoId(huTrace.getM_HU_ID())) .linkedSourceVHuId(HuId.ofRepoIdOrNull(huTrace.getVHU_Source_ID())) .build(); enqueueHUExport(exportHUCandidate); } private void directlyExportToAllMatchingConfigs(@NonNull final I_M_HU_Trace huTrace) { final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigRepo.getActiveByType(ExternalSystemType.GRSSignum); for (final ExternalSystemParentConfig config : configs) { final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig()); if (!shouldExportToExternalSystem(grsConfig, HUTraceType.ofCode(huTrace.getHUTraceType()))) { continue; } final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParent(HuId.ofRepoId(huTrace.getM_HU_ID())); final TableRecordReference topLevelHURecordRef = TableRecordReference.of(topLevelHU); exportToExternalSystem(grsConfig.getId(), topLevelHURecordRef, null); } } private boolean shouldExportDirectly(@NonNull final I_M_HU_Trace huTrace) {
final HUTraceType huTraceType = HUTraceType.ofCode(huTrace.getHUTraceType()); final boolean purchasedOrProduced = huTraceType.equals(MATERIAL_RECEIPT) || huTraceType.equals(PRODUCTION_RECEIPT); final boolean docCompleted = DocStatus.ofCodeOptional(huTrace.getDocStatus()) .map(DocStatus::isCompleted) .orElse(false); return purchasedOrProduced && docCompleted; } private boolean shouldExportIfAlreadyExportedOnce(@NonNull final HUTraceType huTraceType) { return huTraceType.equals(TRANSFORM_LOAD) || huTraceType.equals(TRANSFORM_PARENT); } private boolean shouldExportToExternalSystem(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig, @NonNull final HUTraceType huTraceType) { switch (huTraceType) { case MATERIAL_RECEIPT: return grsSignumConfig.isSyncHUsOnMaterialReceipt(); case PRODUCTION_RECEIPT: return grsSignumConfig.isSyncHUsOnProductionReceipt(); default: return false; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\ExportHUToGRSService.java
1
请在Spring Boot框架中完成以下Java代码
public void setTimeBetweenEvictionRunsMillis(Long timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public Long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public Boolean getTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(Boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public Boolean getTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(Boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public Boolean getTestOnReturn() { return testOnReturn; }
public void setTestOnReturn(Boolean testOnReturn) { this.testOnReturn = testOnReturn; } public Boolean getPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(Boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public Integer getMaxPoolPreparedStatementPerConnectionSize() { return maxPoolPreparedStatementPerConnectionSize; } public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) { this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } }
repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\config\DruidConfigPrimaryProperties.java
2
请在Spring Boot框架中完成以下Java代码
public ExternalWorkerJobEntity findJobByCorrelationId(String correlationId) { return dataManager.findJobByCorrelationId(correlationId); } @Override public List<ExternalWorkerJobEntity> findJobsByScopeIdAndSubScopeId(String scopeId, String subScopeId) { return dataManager.findJobsByScopeIdAndSubScopeId(scopeId, subScopeId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerId(String workerId) { return dataManager.findJobsByWorkerId(workerId); } @Override public List<ExternalWorkerJobEntity> findJobsByWorkerIdAndTenantId(String workerId, String tenantId) { return dataManager.findJobsByWorkerIdAndTenantId(workerId, tenantId); } @Override public List<ExternalWorkerJob> findJobsByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobsByQueryCriteria(jobQuery); }
@Override public long findJobCountByQueryCriteria(ExternalWorkerJobQueryImpl jobQuery) { return dataManager.findJobCountByQueryCriteria(jobQuery); } @Override public List<ExternalWorkerJobEntity> findExternalJobsToExecute(ExternalWorkerJobAcquireBuilderImpl builder, int numberOfJobs) { return dataManager.findExternalJobsToExecute(builder, numberOfJobs); } @Override public void delete(ExternalWorkerJobEntity entity, boolean fireDeleteEvent) { deleteByteArrayRef(entity.getExceptionByteArrayRef()); deleteByteArrayRef(entity.getCustomValuesByteArrayRef()); if (serviceConfiguration.getInternalJobManager() != null) { serviceConfiguration.getInternalJobManager().handleJobDelete(entity); } super.delete(entity, fireDeleteEvent); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\ExternalWorkerJobEntityManagerImpl.java
2
请完成以下Java代码
public class InsertService { /** 设置集合名称 */ private static final String COLLECTION_NAME = "users"; @Resource private MongoTemplate mongoTemplate; /** * 插入【一条】文档数据,如果文档信息已经【存在就抛出异常】 * * @return 插入的文档信息 */ public Object insert() { // 设置用户信息 User user = new User() .setId("10") .setAge(22) .setSex("男") .setRemake("无") .setSalary(1500) .setName("zhangsan") .setBirthday(new Date()) .setStatus(new Status().setHeight(180).setWeight(150)); // 插入一条用户数据,如果文档信息已经存在就抛出异常 User newUser = mongoTemplate.insert(user, COLLECTION_NAME); // 输出存储结果 log.info("存储的用户信息为:{}", newUser); return newUser; } /** * 插入【多条】文档数据,如果文档信息已经【存在就抛出异常】 * * @return 插入的多个文档信息 * */ public Object insertMany(){ // 设置两个用户信息 User user1 = new User() .setId("11")
.setAge(22) .setSex("男") .setRemake("无") .setSalary(1500) .setName("shiyi") .setBirthday(new Date()) .setStatus(new Status().setHeight(180).setWeight(150)); User user2 = new User() .setId("12") .setAge(22) .setSex("男") .setRemake("无") .setSalary(1500) .setName("shier") .setBirthday(new Date()) .setStatus(new Status().setHeight(180).setWeight(150)); // 使用户信息加入结合 List<User> userList = new ArrayList<>(); userList.add(user1); userList.add(user2); // 插入一条用户数据,如果某个文档信息已经存在就抛出异常 Collection<User> newUserList = mongoTemplate.insert(userList, COLLECTION_NAME); // 输出存储结果 for (User user : newUserList) { log.info("存储的用户信息为:{}", user); } return newUserList; } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\InsertService.java
1
请完成以下Java代码
public class Product { private int id; private String name; private double price; public Product() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() {
return name; } public void setName(String nom) { this.name = nom; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\jsonparams\model\Product.java
1
请完成以下Java代码
public String getProcessRef() { return processRef; } public void setProcessRef(String processRef) { this.processRef = processRef; } public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public void setFallbackToDefaultTenant(Boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; }
public Boolean getFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public boolean isSameDeployment() { return sameDeployment; } public void setSameDeployment(boolean sameDeployment) { this.sameDeployment = sameDeployment; } public String getProcessInstanceIdVariableName() { return processInstanceIdVariableName; } public void setProcessInstanceIdVariableName(String processInstanceIdVariableName) { this.processInstanceIdVariableName = processInstanceIdVariableName; } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ProcessTask.java
1
请在Spring Boot框架中完成以下Java代码
private void receiveMessage(@NonNull final RequestToProcurementWeb event) { auditService.logReceivedFromMetasfresh(Constants.QUEUE_NAME_MF_TO_PW, event); if (event instanceof PutBPartnersRequest) { handler.handlePutBPartnersRequest((PutBPartnersRequest)event); } else if (event instanceof PutProductsRequest) { handler.handlePutProductsRequest((PutProductsRequest)event); } else if (event instanceof PutRfQsRequest) { handler.handlePutRfQsRequest((PutRfQsRequest)event); } else if (event instanceof PutInfoMessageRequest) {
handler.handlePutInfoMessageRequest((PutInfoMessageRequest)event); } else if (event instanceof PutConfirmationToProcurementWebRequest) { handler.handlePutConfirmationToProcurementWebRequest((PutConfirmationToProcurementWebRequest)event); } else if (event instanceof PutRfQCloseEventsRequest) { handler.handlePutRfQCloseEventsRequest((PutRfQCloseEventsRequest)event); } else { throw new ReceiveSyncException(event, "Unsupported event type " + event.getClass().getName()); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\rabbitmq\ReceiverFromMetasfresh.java
2
请完成以下Java代码
protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { String name = para.getParameterName(); if (para.getParameter() == null) { continue; } else if (name.equals("AD_Table_ID")) { p_AD_Table_ID = para.getParameterAsInt(); } else if (name.equals("EntityType")) { p_EntityType = para.getParameterAsString(); } else if (name.equals("IsTest")) { p_IsTest = para.getParameterAsBoolean(); } } } @Override @RunOutOfTrx protected String doIt() { final CopyColumnsResult result = CopyColumnsProducer.newInstance() .setLogger(this) .setTargetTable(getTargetTable()) .setSourceColumns(getSourceColumns()) .setEntityType(p_EntityType)
.setDryRun(p_IsTest) .create(); // return "" + result; } protected I_AD_Table getTargetTable() { if (p_AD_Table_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_AD_Table_ID); } final I_AD_Table targetTable = InterfaceWrapperHelper.create(getCtx(), p_AD_Table_ID, I_AD_Table.class, get_TrxName()); return targetTable; } protected List<I_AD_Column> getSourceColumns() { final IQueryFilter<I_AD_Column> selectedColumnsFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<I_AD_Column> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_AD_Column.class, this) .filter(selectedColumnsFilter); queryBuilder.orderBy() .addColumn(I_AD_Column.COLUMNNAME_AD_Table_ID) .addColumn(I_AD_Column.COLUMNNAME_AD_Column_ID); return queryBuilder .create() .list(I_AD_Column.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_Column_CopySelectedToTable.java
1
请完成以下Java代码
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID)); } /** Get Standort. @return Identifiziert die (Liefer-) Adresse des Geschäftspartners */ @Override public int getC_BPartner_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set MSV3 Customer Config. @param MSV3_Customer_Config_ID MSV3 Customer Config */ @Override public void setMSV3_Customer_Config_ID (int MSV3_Customer_Config_ID) { if (MSV3_Customer_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Customer_Config_ID, Integer.valueOf(MSV3_Customer_Config_ID)); } /** Get MSV3 Customer Config. @return MSV3 Customer Config */ @Override public int getMSV3_Customer_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Customer_Config_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Nutzerkennung. @param UserID Nutzerkennung */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Customer_Config.java
1
请完成以下Java代码
public class CustomElementFactoryImpl implements ReplacedElementFactory { @Override public ReplacedElement createReplacedElement(LayoutContext lc, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) { Element e = box.getElement(); String nodeName = e.getNodeName(); if (nodeName.equals("img")) { String imagePath = e.getAttribute("src"); try { InputStream input = new FileInputStream("src/main/resources/" + imagePath); byte[] bytes = IOUtils.toByteArray(input); Image image = Image.getInstance(bytes); FSImage fsImage = new ITextFSImage(image); if (cssWidth != -1 || cssHeight != -1) { fsImage.scale(cssWidth, cssHeight); } else { fsImage.scale(2000, 1000); } return new ITextImageElement(fsImage); } catch (Exception e1) { e1.printStackTrace(); } }
return null; } @Override public void reset() { } @Override public void remove(Element e) { } @Override public void setFormSubmissionListener(FormSubmissionListener listener) { } }
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\openpdf\CustomElementFactoryImpl.java
1
请完成以下Java代码
public class CompositeConnectionAdapter implements ConnectionAdapter { private final List<ConnectionAdapter> adapters; public CompositeConnectionAdapter(List<ConnectionAdapter> adapters) { Assert.notEmpty(adapters, "ConnectionAdapter's are required"); this.adapters = adapters; } @Override public boolean supports(Class<?> containerType) { return (getAdapter(containerType) != null); } @Override public <T> Collection<T> getContent(Object container) { return getRequiredAdapter(container).getContent(container); } @Override public boolean hasPrevious(Object container) { return getRequiredAdapter(container).hasPrevious(container); } @Override public boolean hasNext(Object container) {
return getRequiredAdapter(container).hasNext(container); } @Override public String cursorAt(Object container, int index) { return getRequiredAdapter(container).cursorAt(container, index); } private ConnectionAdapter getRequiredAdapter(Object container) { ConnectionAdapter adapter = getAdapter(container.getClass()); Assert.notNull(adapter, "No ConnectionAdapter for: " + container.getClass().getName()); return adapter; } private @Nullable ConnectionAdapter getAdapter(Class<?> containerType) { for (ConnectionAdapter adapter : this.adapters) { if (adapter.supports(containerType)) { return adapter; } } return null; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\pagination\CompositeConnectionAdapter.java
1
请完成以下Java代码
public BigDecimal getCosts () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Costs); if (bd == null) return Env.ZERO; return bd; } /** 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 End Date. @param EndDate Last effective date (inclusive) */ public void setEndDate (Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get End Date. @return Last effective date (inclusive) */ public Timestamp getEndDate () { return (Timestamp)get_Value(COLUMNNAME_EndDate); } /** Set Summary Level. @param IsSummary This is a summary entity */ public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Summary Level. @return This is a summary entity */ public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair
*/ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign.java
1
请完成以下Java代码
public void beforeSave(final I_AD_PrinterHW record, final ModelChangeType timing) { if (timing.isNew()) { setHostKey(record); } HardwarePrinterRepository.validateOnBeforeSave(record); } private void setHostKey(final I_AD_PrinterHW printerHW) { if (Check.isNotBlank(printerHW.getHostKey())) { return; // HostKey was already set, nothing to do } if (!Objects.equals(OutputType.Queue, OutputType.ofNullableCode(printerHW.getOutputType()))) { return; // no hostkey needed } final Properties ctx = InterfaceWrapperHelper.getCtx(printerHW); final String hostKey = printClientsBL.getHostKeyOrNull(ctx); if (Check.isBlank(hostKey)) { logger.debug("HostKey not found in context"); return; } // Finally, update the bean printerHW.setHostKey(hostKey); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteAttachedLines(final I_AD_PrinterHW printerHW) { final HardwarePrinterId hardwarePrinterId = HardwarePrinterId.ofRepoId(printerHW.getAD_PrinterHW_ID());
hardwarePrinterRepository.deleteCalibrations(hardwarePrinterId); hardwarePrinterRepository.deleteMediaTrays(hardwarePrinterId); hardwarePrinterRepository.deleteMediaSizes(hardwarePrinterId); } /** * Needed because we want to order by ConfigHostKey and "unspecified" shall always be last. */ @ModelChange( timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Printer_Config.COLUMNNAME_ConfigHostKey) public void trimBlankHostKeyToNull(@NonNull final I_AD_PrinterHW printerHW) { try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(printerHW)) { final String normalizedString = StringUtils.trimBlankToNull(printerHW.getHostKey()); printerHW.setHostKey(normalizedString); } } /** * This interceptor shall only fire if the given {@code printerTrayHW} was created with replication. * If it was created via the REST endpoint, then the business logic is called directly. */ @ModelChange(timings = ModelValidator.TYPE_AFTER_NEW_REPLICATION) public void createPrinterConfigIfNoneExists(final I_AD_PrinterHW printerHW) { printerBL.createConfigAndDefaultPrinterMatching(printerHW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\AD_PrinterHW.java
1
请完成以下Spring Boot application配置
spring.main.banner-mode=console server.port=8081 rocketmq.producer.endpoints=rocketmq.qa.zg365.top:8081 rocketmq.producer.request-timeout=5 rocketmq.producer.topic=
test-topic rocketmq.push-consumer.endpoints=rocketmq.qa.zg365.top:8081
repos\spring-boot-student-master\spring-boot-student-rocketmq\src\main\resources\application.properties
2
请完成以下Java代码
public class BPartnerNameAndGreetingStrategyId { private static final Interner<BPartnerNameAndGreetingStrategyId> interner = Interners.newStrongInterner(); private final String stringRepresentation; @JsonCreator public static BPartnerNameAndGreetingStrategyId ofString(@NonNull final String stringRepresentation) { return interner.intern(new BPartnerNameAndGreetingStrategyId(stringRepresentation)); } private BPartnerNameAndGreetingStrategyId(@NonNull final String stringRepresentation) { this.stringRepresentation = StringUtils.trimBlankToNull(stringRepresentation); if (this.stringRepresentation == null) { throw new AdempiereException("Invalid BPartnerNameAndGreetingStrategyId: `" + stringRepresentation + "`"); }
} @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return stringRepresentation; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\BPartnerNameAndGreetingStrategyId.java
1
请完成以下Java代码
private ImmutableList<BusinessRuleAndTriggers> getRuleAndTriggers() { return rules.getByTriggerTableId(sourceModelRef.getAdTableId()); } private BooleanWithReason checkTriggerMatching(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger) { final BusinessRuleStopwatch stopwatch = logger.newStopwatch(); BooleanWithReason matching = BooleanWithReason.FALSE; try { if (!trigger.isChangeTypeMatching(timing)) { return BooleanWithReason.falseBecause("timing not matching"); } matching = checkConditionMatching(trigger.getCondition()); } catch (final Exception ex) { logger.debug("Failed evaluating trigger condition {}/{} for {}/{}", rule, trigger, sourceModel, timing, ex); matching = BooleanWithReason.falseBecause(ex); } finally { logger.debug(stopwatch, "Checked if trigger is matching source: {}", matching); } return matching; } private BooleanWithReason checkConditionMatching(@Nullable final Validation condition) { return condition == null || recordMatcher.isRecordMatching(sourceModelRef, condition)
? BooleanWithReason.TRUE : BooleanWithReason.FALSE; } private void enqueueToRecompute(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger) { eventRepository.create(BusinessRuleEventCreateRequest.builder() .clientAndOrgId(clientAndOrgId) .triggeringUserId(triggeringUserId) .recordRef(sourceModelRef) .businessRuleId(rule.getId()) .triggerId(trigger.getId()) .build()); logger.debug("Enqueued event for re-computation"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\BusinessRuleFireTriggersCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { @Bean public SecurityWebFilterChain accountAuthorization(ServerHttpSecurity http, @Qualifier("opaWebClient") WebClient opaWebClient) { return http.httpBasic(Customizer.withDefaults()) .authorizeExchange(exchanges -> exchanges.pathMatchers("/account/*") .access(opaAuthManager(opaWebClient))) .build(); } @Bean public ReactiveAuthorizationManager<AuthorizationContext> opaAuthManager(WebClient opaWebClient) { return (auth, context) -> opaWebClient.post() .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .body(toAuthorizationPayload(auth, context), Map.class) .exchangeToMono(this::toDecision); } private Mono<AuthorizationDecision> toDecision(ClientResponse response) { if (!response.statusCode() .is2xxSuccessful()) { return Mono.just(new AuthorizationDecision(false)); } return response.bodyToMono(ObjectNode.class) .map(node -> { boolean authorized = node.path("result") .path("authorized") .asBoolean(false); return new AuthorizationDecision(authorized); }); } private Publisher<Map<String, Object>> toAuthorizationPayload(Mono<Authentication> auth, AuthorizationContext context) { return auth.defaultIfEmpty( new AnonymousAuthenticationToken("**ANONYMOUS**", new Object(), Collections.singletonList(new SimpleGrantedAuthority("ANONYMOUS")))) .map(a -> { Map<String, String> headers = context.getExchange()
.getRequest() .getHeaders() .toSingleValueMap(); Map<String, Object> attributes = ImmutableMap.<String, Object> builder() .put("principal", a.getName()) .put("authorities", a.getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toList())) .put("uri", context.getExchange() .getRequest() .getURI() .getPath()) .put("headers", headers) .build(); return ImmutableMap.<String, Object> builder() .put("input", attributes) .build(); }); } }
repos\tutorials-master\spring-security-modules\spring-security-opa\src\main\java\com\baeldung\security\opa\config\SecurityConfiguration.java
2
请完成以下Java代码
public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine() { return iciol; } @Override public List<Object> getLineAggregationKeyElements() { return aggregationKeyElements; } @Override public Set<IInvoiceLineAttribute> getAttributesFromInoutLines() { return attributesFromInoutLines; } @Override public boolean isAllocateRemainingQty() { return this.allocateRemainingQty; } /** * {@link InvoiceLineAggregationRequest} builder. */ public static class Builder { private I_C_Invoice_Candidate invoiceCandidate; private I_C_InvoiceCandidate_InOutLine iciol; private final List<Object> aggregationKeyElements = new ArrayList<>(); private final Set<IInvoiceLineAttribute> attributesFromInoutLines = new LinkedHashSet<>(); @Setter private boolean allocateRemainingQty = false; /* package */ InvoiceLineAggregationRequest build() { return new InvoiceLineAggregationRequest(this); } private Builder() { } @Override
public String toString() { return ObjectUtils.toString(this); } public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate) { this.invoiceCandidate = invoiceCandidate; return this; } public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol) { this.iciol = iciol; return this; } /** * Adds an additional element to be considered part of the line aggregation key. * <p> * NOTE: basically this shall be always empty because everything which is related to line aggregation * shall be configured from aggregation definition, * but we are also leaving this door open in case we need to implement some quick/hot fixes. * * @deprecated This method will be removed because we shall go entirely with standard aggregation definition. */ @Deprecated public Builder addLineAggregationKeyElement(@NonNull final Object aggregationKeyElement) { aggregationKeyElements.add(aggregationKeyElement); return this; } public void addInvoiceLineAttributes(@NonNull final Collection<IInvoiceLineAttribute> invoiceLineAttributes) { this.attributesFromInoutLines.addAll(invoiceLineAttributes); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAggregationRequest.java
1
请完成以下Spring Boot application配置
mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml mybatis.type-aliases-package=com.neo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3
306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = root
repos\spring-boot-leaning-master\1.x\第07课:Spring Boot 集成 MyBatis\spring-boot-mybatis-xml\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public CommonResult updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updatePasswordParam) { int status = adminService.updatePassword(updatePasswordParam); if (status > 0) { return CommonResult.success(status); } else if (status == -1) { return CommonResult.failed("提交参数不合法"); } else if (status == -2) { return CommonResult.failed("找不到该用户"); } else if (status == -3) { return CommonResult.failed("旧密码错误"); } else { return CommonResult.failed(); } } @ApiOperation("删除指定用户信息") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = adminService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改帐号状态") @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) { UmsAdmin umsAdmin = new UmsAdmin(); umsAdmin.setStatus(status); int count = adminService.update(id,umsAdmin); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("给用户分配角色")
@RequestMapping(value = "/role/update", method = RequestMethod.POST) @ResponseBody public CommonResult updateRole(@RequestParam("adminId") Long adminId, @RequestParam("roleIds") List<Long> roleIds) { int count = adminService.updateRole(adminId, roleIds); if (count >= 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取指定用户的角色") @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) { List<UmsRole> roleList = adminService.getRoleList(adminId); return CommonResult.success(roleList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsAdminController.java
2
请完成以下Java代码
private ReportPrintingInfo extractReportPrintingInfo(@NonNull final ProcessInfo pi) { final ReportPrintingInfo.ReportPrintingInfoBuilder info = ReportPrintingInfo .builder() .processInfo(pi) .printPreview(pi.isPrintPreview()) .archiveReportData(pi.isArchiveReportData()) .forceSync(!pi.isAsync()); // gh #1160 if the process info says "sync", then sync it is // // Determine the ReportingSystem type based on report template file extension // TODO: make it more general and centralized with the other reporting code final String reportFileExtension = pi .getReportTemplate() .map(reportTemplate -> Files.getFileExtension(reportTemplate).toLowerCase()) .orElse(null); if ("jasper".equalsIgnoreCase(reportFileExtension) || "jrxml".equalsIgnoreCase(reportFileExtension)) { info.reportingSystemType(ReportingSystemType.Jasper); } else if ("xls".equalsIgnoreCase(reportFileExtension)) { info.reportingSystemType(ReportingSystemType.Excel); info.printPreview(true); // TODO: atm only print preview is supported } else { info.reportingSystemType(ReportingSystemType.Other); } return info.build(); } private void startProcess0(final ReportPrintingInfo reportPrintingInfo) { try { logger.info("Doing direct print without preview: {}", reportPrintingInfo); startProcessDirectPrint(reportPrintingInfo); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e); } } private enum ReportingSystemType { Jasper, Excel, /**
* May be used when no invocation to the jasper service is done */ Other } @Value @Builder private static class ReportPrintingInfo { ProcessInfo processInfo; ReportingSystemType reportingSystemType; boolean printPreview; boolean archiveReportData; /** * Even if {@link #isPrintPreview()} is {@code false}, we do <b>not</b> print in a background thread, if this is false. */ @Default boolean forceSync = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ReportStarter.java
1
请完成以下Java代码
public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", title=").append(title); sb.append(", startDate=").append(startDate); sb.append(", endDate=").append(endDate); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotion.java
1
请完成以下Java代码
static @Nullable PemContent load(@Nullable String content, ResourceLoader resourceLoader) throws IOException { if (!StringUtils.hasLength(content)) { return null; } if (isPresentInText(content)) { return new PemContent(content); } try (InputStream in = resourceLoader.getResource(content).getInputStream()) { return load(in); } catch (IOException | UncheckedIOException ex) { throw new IOException("Error reading certificate or key from file '%s'".formatted(content), ex); } } /** * Load {@link PemContent} from the given {@link Path}. * @param path a path to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(Path path) throws IOException { Assert.notNull(path, "'path' must not be null"); try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { return load(in); } } /** * Load {@link PemContent} from the given {@link InputStream}. * @param in an input stream to load the content from * @return the loaded PEM content * @throws IOException on IO error */ public static PemContent load(InputStream in) throws IOException { return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8)); }
/** * Return a new {@link PemContent} instance containing the given text. * @param text the text containing PEM encoded content * @return a new {@link PemContent} instance */ @Contract("!null -> !null") public static @Nullable PemContent of(@Nullable String text) { return (text != null) ? new PemContent(text) : null; } /** * Return if PEM content is present in the given text. * @param text the text to check * @return if the text includes PEM encoded content. */ public static boolean isPresentInText(@Nullable String text) { return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java
1
请完成以下Java代码
public String getExecutionId() { throw new UnsupportedOperationException("Not supported to get execution id"); } @Override public String getScopeId() { throw new UnsupportedOperationException("Not supported to get scope id"); } @Override public String getSubScopeId() { throw new UnsupportedOperationException("Not supported to get sub scope id"); } @Override public String getScopeType() { throw new UnsupportedOperationException("Not supported to scope type"); } @Override public String getTaskId() { throw new UnsupportedOperationException("Not supported to get task id"); } @Override public String getTextValue() { return node.path("textValue").stringValue(null); } @Override public void setTextValue(String textValue) { throw new UnsupportedOperationException("Not supported to set text value"); } @Override public String getTextValue2() { return node.path("textValues").stringValue(null); } @Override public void setTextValue2(String textValue2) { throw new UnsupportedOperationException("Not supported to set text value2"); } @Override public Long getLongValue() { JsonNode longNode = node.path("longValue"); if (longNode.isNumber()) { return longNode.longValue(); }
return null; } @Override public void setLongValue(Long longValue) { throw new UnsupportedOperationException("Not supported to set long value"); } @Override public Double getDoubleValue() { JsonNode doubleNode = node.path("doubleValue"); if (doubleNode.isNumber()) { return doubleNode.doubleValue(); } return null; } @Override public void setDoubleValue(Double doubleValue) { throw new UnsupportedOperationException("Not supported to set double value"); } @Override public byte[] getBytes() { throw new UnsupportedOperationException("Not supported to get bytes"); } @Override public void setBytes(byte[] bytes) { throw new UnsupportedOperationException("Not supported to set bytes"); } @Override public Object getCachedValue() { throw new UnsupportedOperationException("Not supported to set get cached value"); } @Override public void setCachedValue(Object cachedValue) { throw new UnsupportedOperationException("Not supported to set cached value"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java
1
请完成以下Java代码
public final Optional<ProductBarcodeFilterData> createData(@NonNull final String barcode) { // // Pick the first matcher for (final ProductBarcodeFilterDataFactory factory : productDataFactories) { final Optional<ProductBarcodeFilterData> data = factory.createData(services, barcode, ClientId.METASFRESH); if (data.isPresent()) { return data; } } return Optional.empty(); } private ImmutableList<ProductBarcodeFilterDataFactory> getProductBarcodeFilterDataFactories() { return ImmutableList.of( // Check if given barcode is a product UPC or M_Product.Value new UPCProductBarcodeFilterDataFactory(), // Check if given barcode is a SSCC18 of an existing HU new SSCC18ProductBarcodeFilterDataFactory(), // Check if given barcode is an HU internal barcode
new HUBarcodeFilterDataFactory()); } public static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final DocumentFilter filter) { if (!ProductBarcode_FilterId.equals(filter.getFilterId())) { throw new AdempiereException("Invalid filterId " + filter.getFilterId() + ". Expected: " + ProductBarcode_FilterId); } return Optional.ofNullable(filter.getParameterValueAs(PARAM_Data)); } public static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final IView view) { return view.getFilters() .stream() .filter(filter -> ProductBarcode_FilterId.equals(filter.getFilterId())) .findFirst() .flatMap(PackageableFilterDescriptorProvider::extractProductBarcodeFilterData); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\PackageableFilterDescriptorProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class AddressController { private final AddressRepository repository; AddressController(AddressRepository repository) { this.repository = repository; } @GetMapping("/addresses") List<Address> getAllAddresses() { return repository.findAll(); } @GetMapping("/addresses/{id}") Optional<Address> getAddressesById(@PathVariable Long id) { return repository.findById(id); } @PostMapping("/addresses") Address createNewAddress(@RequestBody Address newAddress) { return repository.save(newAddress); }
@PutMapping("/addresses/{id}") Address replaceEmployee(@RequestBody Address newAddress, @PathVariable Long id) { return repository.findById(id) .map(address -> { address.setCity(newAddress.getCity()); address.setPostalCode(newAddress.getPostalCode()); return repository.save(address); }) .orElseGet(() -> { return repository.save(newAddress); }); } @DeleteMapping("/addresses/{id}") void deleteEmployee(@PathVariable Long id) { repository.deleteById(id); } }
repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\putvspost\AddressController.java
2
请完成以下Java代码
public List<OAuth2ClientInfo> findOAuth2ClientInfosByIds(TenantId tenantId, List<OAuth2ClientId> oAuth2ClientIds) { log.trace("Executing findQueueStatsByIds, tenantId [{}], oAuth2ClientIds [{}]", tenantId, oAuth2ClientIds); return oauth2ClientDao.findByIds(tenantId.getId(), oAuth2ClientIds) .stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); } @Override public boolean isPropagateOAuth2ClientToEdge(TenantId tenantId, OAuth2ClientId oAuth2ClientId) { log.trace("Executing isPropagateOAuth2ClientToEdge, tenantId [{}], oAuth2ClientId [{}]", tenantId, oAuth2ClientId); return oauth2ClientDao.isPropagateToEdge(tenantId, oAuth2ClientId.getId()); } @Override public void deleteByTenantId(TenantId tenantId) { deleteOauth2ClientsByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findOAuth2ClientById(tenantId, new OAuth2ClientId(entityId.getId())));
} @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(oauth2ClientDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteOAuth2ClientById(tenantId, (OAuth2ClientId) id); } @Override public EntityType getEntityType() { return EntityType.OAUTH2_CLIENT; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\oauth2\OAuth2ClientServiceImpl.java
1
请完成以下Java代码
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public CaseFileItem getContext() { return contextRefAttribute.getReferenceTargetElement(this); } public void setContext(CaseFileItem context) { contextRefAttribute.setReferenceTargetElement(this, context); } public ConditionExpression getCondition() { return conditionChild.getChild(this); } public void setCondition(ConditionExpression expression) { conditionChild.setChild(this, expression); } public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ApplicabilityRule.class, CMMN_ELEMENT_APPLICABILITY_RULE) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<ApplicabilityRule>() { public ApplicabilityRule newInstance(ModelTypeInstanceContext instanceContext) { return new ApplicabilityRuleImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF) .idAttributeReference(CaseFileItem.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ApplicabilityRuleImpl.java
1
请完成以下Java代码
public PublicKeyCredentialBuilder authenticatorAttachment(AuthenticatorAttachment authenticatorAttachment) { this.authenticatorAttachment = authenticatorAttachment; return this; } /** * Sets the {@link #getClientExtensionResults()} property. * @param clientExtensionResults the client extension results * @return the PublicKeyCredentialBuilder */ public PublicKeyCredentialBuilder clientExtensionResults( AuthenticationExtensionsClientOutputs clientExtensionResults) { this.clientExtensionResults = clientExtensionResults; return this; }
/** * Creates a new {@link PublicKeyCredential} * @return a new {@link PublicKeyCredential} */ public PublicKeyCredential<R> build() { Assert.notNull(this.id, "id cannot be null"); Assert.notNull(this.rawId, "rawId cannot be null"); Assert.notNull(this.response, "response cannot be null"); return new PublicKeyCredential(this.id, this.type, this.rawId, this.response, this.authenticatorAttachment, this.clientExtensionResults); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredential.java
1
请在Spring Boot框架中完成以下Java代码
public void update(String index, List<Person> list) { list.forEach(person -> { updateRequest(index, String.valueOf(person.getId()), person); }); } @Override public void delete(String index, Person person) { if (ObjectUtils.isEmpty(person)) { // 如果person 对象为空,则删除全量 searchList(index).forEach(p -> { deleteRequest(index, String.valueOf(p.getId())); }); } deleteRequest(index, String.valueOf(person.getId()));
} @Override public List<Person> searchList(String index) { SearchResponse searchResponse = search(index); SearchHit[] hits = searchResponse.getHits().getHits(); List<Person> personList = new ArrayList<>(); Arrays.stream(hits).forEach(hit -> { Map<String, Object> sourceAsMap = hit.getSourceAsMap(); Person person = BeanUtil.mapToBean(sourceAsMap, Person.class, true); personList.add(person); }); return personList; } }
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\service\impl\PersonServiceImpl.java
2
请完成以下Java代码
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); }
@Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Snapshot.java
1
请完成以下Java代码
protected ImportLifecycle resolveImportLifecycle() { return resolvedImportLifecycle.updateAndGet(currentValue -> currentValue != null ? currentValue : getEnvironment() .map(env -> env.getProperty(CACHE_DATA_IMPORT_LIFECYCLE_PROPERTY_NAME, String.class, ImportLifecycle.getDefault().name())) .map(ImportLifecycle::from) .orElseGet(ImportLifecycle::getDefault)); } /** * Resolves the configured {@link SmartLifecycleSupport#getPhase() SmartLifecycle Phase} in which the cache data * import will be performed. * * @return the configured {@link SmartLifecycleSupport#getPhase() SmartLifecycle Phase}. * @see #getPhase() */ protected int resolveImportPhase() { return resolvedImportPhase.updateAndGet(currentValue -> currentValue != null ? currentValue : getEnvironment() .map(env -> env.getProperty(CACHE_DATA_IMPORT_PHASE_PROPERTY_NAME, Integer.class, DEFAULT_IMPORT_PHASE)) .orElse(DEFAULT_IMPORT_PHASE)); } /** * Performs the cache data import for each of the targeted {@link Region Regions}. * * @see #getCacheDataImporterExporter() * @see #getRegionsForImport() */ @Override public void start() { // Technically, the resolveImportLifecycle().isLazy() check is not strictly required since if the cache data // import is "eager", then the regionsForImport Set will be empty anyway. if (resolveImportLifecycle().isLazy()) { getRegionsForImport().forEach(getCacheDataImporterExporter()::importInto); } } /** * An {@link Enum Enumeration} defining the different modes for the cache data import lifecycle. */ public enum ImportLifecycle { EAGER("Imports cache data during Region bean post processing, after initialization"), LAZY("Imports cache data during the appropriate phase on Lifecycle start");
private final String description; ImportLifecycle(@NonNull String description) { Assert.hasText(description, "The enumerated value must have a description"); this.description = description; } public static @NonNull ImportLifecycle getDefault() { return LAZY; } public static @Nullable ImportLifecycle from(String name) { for (ImportLifecycle importCycle : values()) { if (importCycle.name().equalsIgnoreCase(name)) { return importCycle; } } return null; } public boolean isEager() { return EAGER.equals(this); } public boolean isLazy() { return LAZY.equals(this); } @Override public String toString() { return this.description; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\support\LifecycleAwareCacheDataImporterExporter.java
1
请在Spring Boot框架中完成以下Java代码
public final class RequestMatcherFactoryBean implements FactoryBean<RequestMatcher>, ApplicationContextAware { private PathPatternRequestMatcher.Builder builder; private final HttpMethod method; private final String path; public RequestMatcherFactoryBean(String path) { this(path, null); } public RequestMatcherFactoryBean(String path, HttpMethod method) { this.method = method; this.path = path; }
@Override public RequestMatcher getObject() throws Exception { return this.builder.matcher(this.method, this.path); } @Override public Class<?> getObjectType() { return null; } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.builder = context.getBean(PathPatternRequestMatcher.Builder.class); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\RequestMatcherFactoryBean.java
2
请完成以下Java代码
public class SetExternalTaskRetriesJobHandler extends AbstractBatchJobHandler<SetRetriesBatchConfiguration> { public static final BatchJobDeclaration JOB_DECLARATION = new BatchJobDeclaration(Batch.TYPE_SET_EXTERNAL_TASK_RETRIES); @Override public String getType() { return Batch.TYPE_SET_EXTERNAL_TASK_RETRIES; } @Override public void executeHandler(SetRetriesBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { commandContext.executeWithOperationLogPrevented( new SetExternalTasksRetriesCmd( new UpdateExternalTaskRetriesBuilderImpl( batchConfiguration.getIds(), batchConfiguration.getRetries()))); }
@Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } @Override protected SetRetriesBatchConfiguration createJobConfiguration(SetRetriesBatchConfiguration configuration, List<String> processIdsForJob) { return new SetRetriesBatchConfiguration(processIdsForJob, configuration.getRetries()); } @Override protected SetExternalTaskRetriesBatchConfigurationJsonConverter getJsonConverterInstance() { return SetExternalTaskRetriesBatchConfigurationJsonConverter.INSTANCE; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\externaltask\SetExternalTaskRetriesJobHandler.java
1
请完成以下Java代码
public String getPostingType () { return (String)get_Value(COLUMNNAME_PostingType); } /** RatioElementType AD_Reference_ID=372 */ public static final int RATIOELEMENTTYPE_AD_Reference_ID=372; /** Ratio = R */ public static final String RATIOELEMENTTYPE_Ratio = "R"; /** Constant = C */ public static final String RATIOELEMENTTYPE_Constant = "C"; /** Calculation = X */ public static final String RATIOELEMENTTYPE_Calculation = "X"; /** Account Value = A */ public static final String RATIOELEMENTTYPE_AccountValue = "A"; /** Set Element Type. @param RatioElementType Ratio Element Type */ public void setRatioElementType (String RatioElementType) { set_Value (COLUMNNAME_RatioElementType, RatioElementType); } /** Get Element Type. @return Ratio Element Type */ public String getRatioElementType () { return (String)get_Value(COLUMNNAME_RatioElementType); } /** RatioOperand AD_Reference_ID=373 */ public static final int RATIOOPERAND_AD_Reference_ID=373; /** Plus = P */ public static final String RATIOOPERAND_Plus = "P"; /** Minus = N */ public static final String RATIOOPERAND_Minus = "N"; /** Multiply = M */ public static final String RATIOOPERAND_Multiply = "M"; /** Divide = D */ public static final String RATIOOPERAND_Divide = "D"; /** Set Operand. @param RatioOperand Ratio Operand */ public void setRatioOperand (String RatioOperand) { set_Value (COLUMNNAME_RatioOperand, RatioOperand); } /** Get Operand. @return Ratio Operand */ public String getRatioOperand () { return (String)get_Value(COLUMNNAME_RatioOperand); } /** Set Sequence.
@param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_RatioElement.java
1
请完成以下Java代码
public boolean isProvidedForVendor(final int vendorRepoId) { final BPartnerId vendorId = BPartnerId.ofRepoId(vendorRepoId); return configRepo.hasConfigForVendor(vendorId); } @Override public AvailabilityResponse retrieveAvailability(@NonNull final AvailabilityRequest request) { final BPartnerId vendorId = BPartnerId.ofRepoId(request.getVendorId()); final MSV3ClientConfig config = configRepo.getByVendorId(vendorId); final MSV3AvailiabilityClient client = getClientFactory(config.getVersion()) .newAvailabilityClient(config); return client.retrieveAvailability(request); } @Override public RemotePurchaseOrderCreated placePurchaseOrder(@NonNull final PurchaseOrderRequest request) { final BPartnerId vendorId = BPartnerId.ofRepoId(request.getVendorId()); final MSV3ClientConfig config = configRepo.getByVendorId(vendorId); final MSV3PurchaseOrderClient client = getClientFactory(config.getVersion()) .newPurchaseOrderClient(config); return client.prepare(request).placeOrder(); } @Override public void associateLocalWithRemotePurchaseOrderId(
@NonNull final LocalPurchaseOrderForRemoteOrderCreated localPurchaseOrderForRemoteOrderCreated) { final RemotePurchaseOrderCreatedItem item = localPurchaseOrderForRemoteOrderCreated.getRemotePurchaseOrderCreatedItem(); final I_MSV3_BestellungAnteil anteilRecord = Services.get(IQueryBL.class).createQueryBuilder(I_MSV3_BestellungAnteil.class) .addEqualsFilter(I_MSV3_BestellungAnteil.COLUMN_MSV3_BestellungAnteil_ID, item.getInternalItemId()) .create() .firstOnlyNotNull(I_MSV3_BestellungAnteil.class); anteilRecord.setC_OrderLinePO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderLineId()); save(anteilRecord); final I_MSV3_BestellungAntwortAuftrag bestellungAntwortAuftrag = anteilRecord .getMSV3_BestellungAntwortPosition() .getMSV3_BestellungAntwortAuftrag(); bestellungAntwortAuftrag.setC_OrderPO_ID(localPurchaseOrderForRemoteOrderCreated.getPurchaseOrderId()); save(bestellungAntwortAuftrag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3VendorGatewayService.java
1
请在Spring Boot框架中完成以下Java代码
private ReturnResponse<Object> deleteFileCheck(HttpServletRequest request, String fileName, String password) { if (ObjectUtils.isEmpty(fileName)) { return ReturnResponse.failure("文件名为空,删除失败!"); } try { fileName = WebUtils.decodeUrl(fileName); } catch (Exception ex) { String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, fileName); return ReturnResponse.failure(errorMsg + "删除失败!"); } assert fileName != null; if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf("/") + 1); } if (KkFileUtils.isIllegalFileName(fileName)) { return ReturnResponse.failure("非法文件名,删除失败!"); } if (ObjectUtils.isEmpty(password)) { return ReturnResponse.failure("密码 or 验证码为空,删除失败!"); } String expectedPassword = ConfigConstants.getDeleteCaptcha() ? WebUtils.getSessionAttr(request, CAPTCHA_CODE) : ConfigConstants.getPassword(); if (!password.equalsIgnoreCase(expectedPassword)) { logger.error("删除文件【{}】失败,密码错误!", fileName); return ReturnResponse.failure("删除文件失败,密码错误!"); } return ReturnResponse.success(fileName); } @GetMapping("/directory") public Object directory(String urls) { String fileUrl;
try { fileUrl = WebUtils.decodeUrl(urls); } catch (Exception ex) { String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url"); return ReturnResponse.failure(errorMsg); } fileUrl = fileUrl.replaceAll("http://", ""); if (KkFileUtils.isIllegalFileName(fileUrl)) { return ReturnResponse.failure("不允许访问的路径:"); } return RarUtils.getTree(fileUrl); } private boolean existsFile(String fileName) { File file = new File(fileDir + demoPath + fileName); return file.exists(); } }
repos\kkFileView-master\server\src\main\java\cn\keking\web\controller\FileController.java
2
请完成以下Java代码
private static boolean acceptMatch(ServerRequest request, List<MediaType> expected) { if (CorsUtils.isPreFlightRequest(request.exchange().getRequest())) { return true; } ServerRequest.Headers headers = request.headers(); List<MediaType> acceptedMediaTypes; try { acceptedMediaTypes = acceptedMediaTypes(headers); } catch (InvalidMediaTypeException ex) { throw new NotAcceptableStatusException("Could not parse " + "Accept header [" + headers.firstHeader(HttpHeaders.ACCEPT) + "]: " + ex.getMessage()); } boolean match = false; outer: for (MediaType acceptedMediaType : acceptedMediaTypes) { for (MediaType mediaType : expected) { if (acceptedMediaType.isCompatibleWith(mediaType)) { match = true; break outer; } } } traceMatch("Accept", expected, acceptedMediaTypes, match); return match; } private static List<MediaType> acceptedMediaTypes(ServerRequest.Headers headers) { List<MediaType> acceptedMediaTypes = headers.accept(); if (acceptedMediaTypes.isEmpty()) { acceptedMediaTypes = Collections.singletonList(MediaType.ALL); } else { MimeTypeUtils.sortBySpecificity(acceptedMediaTypes); } return acceptedMediaTypes; }
private static boolean pathMatch(ServerRequest request, PathPattern pattern) { PathContainer pathContainer = request.requestPath().pathWithinApplication(); boolean pathMatch = pattern.matches(pathContainer); traceMatch("Pattern", pattern.getPatternString(), request.path(), pathMatch); if (pathMatch) { request.attributes().put(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE, pattern); } return pathMatch; } private static void traceMatch(String prefix, Object desired, @Nullable Object actual, boolean match) { if (logger.isTraceEnabled()) { logger.trace(String.format("%s \"%s\" %s against value \"%s\"", prefix, desired, match ? "matches" : "does not match", actual)); } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\GraphQlRequestPredicates.java
1
请完成以下Java代码
private ResolveHUResponse resolveByHUQRCode(@NonNull final HUQRCode huQRCode) { final HuId huId = huService.getHuIdByQRCode(huQRCode); final I_M_HU hu = huCache.getHUById(huId); final InventoryLine matchingLine = findFirstMatchingLine(line -> isLineMatchingHU(line, hu)); final InventoryLineHU matchingLineHU = matchingLine.getInventoryLineHUByHUId(huId).orElse(null); final AttributeSetInstanceId lineAsiId = (matchingLineHU != null ? matchingLineHU.getAsiId() : AttributeSetInstanceId.NONE) .orElseIfNone(matchingLine.getAsiId()); final boolean isCounted = matchingLineHU != null && matchingLineHU.isCounted(); final Quantity qtyCount = isCounted ? matchingLineHU.getQtyCount() : null; final Attributes lineAttributes = asiCache.getById(lineAsiId); final Attributes huAttributes = huCache.getAttributes(hu); return newResponse() .lineId(matchingLine.getIdNonNull()) .locatorId(huCache.getLocatorId(hu)) .huId(huId) .productId(matchingLine.getProductId()) .qtyBooked(huCache.getQty(hu, matchingLine.getProductId())) .isCounted(isCounted) .qtyCount(qtyCount) .attributes(lineAttributes.retainOnly(ATTRIBUTE_CODES, huAttributes)) .build(); } private ResolveHUResponse.ResolveHUResponseBuilder newResponse() { return ResolveHUResponse.builder() .scannedCode(scannedCode); } private ResolveHUResponse resolveByEAN13(@NonNull final EAN13 ean13) { for (final InventoryLine line : lines) { final ProductId lineProductId = line.getProductId(); if (!productService.isValidEAN13Product(ean13, lineProductId)) { continue; } return newResponse() .lineId(line.getIdNonNull()) .locatorId(line.getLocatorId()) .huId(null) .productId(lineProductId) .qtyBooked(Quantitys.zero(lineProductId))
.attributes(getDefaultAttributes()) .build(); } throw new AdempiereException("No line found for the given HU QR code"); } private Attributes getDefaultAttributes() { return Attributes.ofList( ATTRIBUTE_CODES.stream() .map(this::getDefaultAttribute) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()) ); } @Nullable private Attribute getDefaultAttribute(@NonNull AttributeCode attributeCode) { return Attribute.of(productService.getAttribute(attributeCode)); } @NonNull private InventoryLine findFirstMatchingLine(final Predicate<InventoryLine> predicate) { return lines.stream() .filter(predicate) .findFirst() .orElseThrow(() -> new AdempiereException("No line found for the given HU QR code")); } private boolean isLineMatchingHU(final InventoryLine line, final I_M_HU hu) { return !line.isCounted() && LocatorId.equals(line.getLocatorId(), huCache.getLocatorId(hu)) && huCache.getProductIds(hu).contains(line.getProductId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\job\qrcode\ResolveHUCommand.java
1
请完成以下Java代码
public static class OAuth2IdentityProviderProperties { /** * Enable {@link OAuth2IdentityProvider}. Default {@code true}. */ private boolean enabled = true; /** * Name of the attribute (claim) that holds the groups. */ private String groupNameAttribute; /** * Group name attribute delimiter. Only used if the {@link #groupNameAttribute} is a {@link String}. */ private String groupNameDelimiter = ","; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getGroupNameAttribute() { return groupNameAttribute; } public void setGroupNameAttribute(String groupNameAttribute) {
this.groupNameAttribute = groupNameAttribute; } public String getGroupNameDelimiter() { return groupNameDelimiter; } public void setGroupNameDelimiter(String groupNameDelimiter) { this.groupNameDelimiter = groupNameDelimiter; } } public OAuth2SSOLogoutProperties getSsoLogout() { return ssoLogout; } public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) { this.ssoLogout = ssoLogout; } public OAuth2IdentityProviderProperties getIdentityProvider() { return identityProvider; } public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) { this.identityProvider = identityProvider; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
1
请在Spring Boot框架中完成以下Java代码
static SubscribableChannel orders(@Value("${db.url}") String url,@Value("${db.username}") String username, @Value("${db.password}")String password) { // Connection supplier SingleConnectionDataSource ds = new SingleConnectionDataSource(url, username, password, true); Supplier<Connection> connectionSupplier = () -> { try { return ds.getConnection(); } catch(SQLException ex) { throw new RuntimeException(ex); } }; // DataSource PGSimpleDataSource pgds = new PGSimpleDataSource(); pgds.setUrl(url); pgds.setUser(username); pgds.setPassword(password); return new PostgresSubscribableChannel("orders", connectionSupplier, pgds, new ObjectMapper()); } @Transformer(inputChannel = "orders" , outputChannel = "orderProcessor" ) 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
2
请完成以下Java代码
private String inline0(@NonNull final String sql, @Nullable final List<Object> params) { final int paramsCount = params != null ? params.size() : 0; final int sqlLength = sql.length(); final StringBuilder sqlFinal = new StringBuilder(sqlLength); boolean insideQuotes = false; int nextParamIndex = 0; for (int i = 0; i < sqlLength; i++) { final char ch = sql.charAt(i); if (ch == '?') { if (insideQuotes) { sqlFinal.append(ch); } else { if (params != null && nextParamIndex < paramsCount) { sqlFinal.append(DB.TO_SQL(params.get(nextParamIndex))); } else { // error: parameter index is invalid appendMissingParam(sqlFinal, nextParamIndex); } nextParamIndex++; } } else if (ch == '\'') { sqlFinal.append(ch); insideQuotes = !insideQuotes; } else { sqlFinal.append(ch); } } if (params != null && nextParamIndex < paramsCount) { appendExceedingParams(sqlFinal, nextParamIndex, paramsCount, params); } return sqlFinal.toString(); } private void appendMissingParam( final StringBuilder sql, final int missingParamIndexZeroBased) { final int missingParamIndexOneBased = missingParamIndexZeroBased + 1; if (failOnError) { throw new AdempiereException("Missing SQL parameter with index=" + missingParamIndexOneBased);
} sql.append("?missing").append(missingParamIndexOneBased).append("?"); } private void appendExceedingParams( final StringBuilder sql, final int firstExceedingParamIndex, final int paramsCount, final List<Object> allParams) { if (failOnError) { throw new AdempiereException("Got more SQL params than needed: " + allParams.subList(firstExceedingParamIndex, allParams.size())); } sql.append(" -- Exceeding params: "); boolean firstExceedingParam = true; for (int i = firstExceedingParamIndex; i < paramsCount; i++) { if (firstExceedingParam) { firstExceedingParam = false; } else { sql.append(", "); } sql.append(DB.TO_SQL(allParams.get(i))); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\sql\SqlParamsInliner.java
1
请在Spring Boot框架中完成以下Java代码
public User userFromId(Long id) { if (id == null) { return null; } User user = new User(); user.setId(id); return user; } @Named("id") @BeanMapping(ignoreByDefault = true) @Mapping(target = "id", source = "id") public UserDTO toDtoId(User user) { if (user == null) { return null; } UserDTO userDto = new UserDTO(); userDto.setId(user.getId()); return userDto; } @Named("idSet") @BeanMapping(ignoreByDefault = true) @Mapping(target = "id", source = "id") public Set<UserDTO> toDtoIdSet(Set<User> users) { if (users == null) { return Collections.emptySet(); } Set<UserDTO> userSet = new HashSet<>(); for (User userEntity : users) { userSet.add(this.toDtoId(userEntity)); } return userSet; }
@Named("login") @BeanMapping(ignoreByDefault = true) @Mapping(target = "id", source = "id") @Mapping(target = "login", source = "login") public UserDTO toDtoLogin(User user) { if (user == null) { return null; } UserDTO userDto = new UserDTO(); userDto.setId(user.getId()); userDto.setLogin(user.getLogin()); return userDto; } @Named("loginSet") @BeanMapping(ignoreByDefault = true) @Mapping(target = "id", source = "id") @Mapping(target = "login", source = "login") public Set<UserDTO> toDtoLoginSet(Set<User> users) { if (users == null) { return Collections.emptySet(); } Set<UserDTO> userSet = new HashSet<>(); for (User userEntity : users) { userSet.add(this.toDtoLogin(userEntity)); } return userSet; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\mapper\UserMapper.java
2
请在Spring Boot框架中完成以下Java代码
public PageData<Customer> getCustomers( @Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @Parameter(description = CUSTOMER_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @Parameter(description = SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"createdTime", "title", "email", "country", "city"})) @RequestParam(required = false) String sortProperty, @Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"})) @RequestParam(required = false) String sortOrder) throws ThingsboardException { PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); TenantId tenantId = getCurrentUser().getTenantId(); return checkNotNull(customerService.findCustomersByTenantId(tenantId, pageLink)); } @ApiOperation(value = "Get Tenant Customer by Customer title (getTenantCustomer)", notes = "Get the Customer using Customer Title. " + TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @RequestMapping(value = "/tenant/customers", params = {"customerTitle"}, method = RequestMethod.GET) @ResponseBody public Customer getTenantCustomer( @Parameter(description = "A string value representing the Customer title.")
@RequestParam String customerTitle) throws ThingsboardException { TenantId tenantId = getCurrentUser().getTenantId(); return checkNotNull(customerService.findCustomerByTenantIdAndTitle(tenantId, customerTitle), "Customer with title [" + customerTitle + "] is not found"); } @ApiOperation(value = "Get customers by Customer Ids (getCustomersByIds)", notes = "Returns a list of Customer objects based on the provided ids." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')") @GetMapping(value = "/customers", params = {"customerIds"}) public List<Customer> getCustomersByIds( @Parameter(description = "A list of customer ids, separated by comma ','", array = @ArraySchema(schema = @Schema(type = "string")), required = true) @RequestParam("customerIds") Set<UUID> customerUUIDs) throws ThingsboardException { TenantId tenantId = getCurrentUser().getTenantId(); List<CustomerId> customerIds = new ArrayList<>(); for (UUID customerUUID : customerUUIDs) { customerIds.add(new CustomerId(customerUUID)); } return customerService.findCustomersByTenantIdAndIds(tenantId, customerIds); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\CustomerController.java
2
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @NotNull @Column(columnDefinition = "VARCHAR", length = 100) private String title; @NotNull @Column(columnDefinition = "VARCHAR", length = 100) private String author; @Column(columnDefinition = "VARCHAR", length = 1000) private String blurb; private int pages; public Book() { } public Book(@NotNull String title, @NotNull String author, String blurb, int pages) { this.title = title; this.author = author; this.blurb = blurb; this.pages = pages; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getBlurb() { return blurb; } public void setBlurb(String blurb) { this.blurb = blurb; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", blurb='" + blurb + '\'' + ", pages=" + pages + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-rest-2\src\main\java\com\baeldung\halbrowser\model\Book.java
2
请完成以下Java代码
public <T> T executeCommand(CommandConfig config, Command<T> command) { if (config == null) { throw new ActivitiIllegalArgumentException("The config is null"); } if (command == null) { throw new ActivitiIllegalArgumentException("The command is null"); } return commandExecutor.execute(config, command); } @Override public <MapperType, ResultType> ResultType executeCustomSql( CustomSqlExecution<MapperType, ResultType> customSqlExecution ) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute( new ExecuteCustomSqlCmd<MapperType, ResultType>(mapperClass, customSqlExecution) ); }
@Override public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) { return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize)); } @Override public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) { return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId)); } @Override public void deleteEventLogEntry(long logNr) { commandExecutor.execute(new DeleteEventLogEntry(logNr)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java
1
请完成以下Java代码
public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID */ @Override public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID /** * Get Document Approval Amount * @return amount */ @Override public BigDecimal getApprovalAmt() { return getAmt();
} // getApprovalAmt /** * Document Status is Complete or Closed * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MRMA
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMA.java
1
请完成以下Java代码
public void onAfterQuery(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onAfterQuery(calloutRecord); } } public static final class Builder { private final List<ITabCallout> tabCalloutsAll = new ArrayList<>(); private Builder() { super(); } public ITabCallout build() { if (tabCalloutsAll.isEmpty()) { return ITabCallout.NULL; } else if (tabCalloutsAll.size() == 1) { return tabCalloutsAll.get(0); }
else { return new CompositeTabCallout(tabCalloutsAll); } } public Builder addTabCallout(final ITabCallout tabCallout) { Check.assumeNotNull(tabCallout, "tabCallout not null"); if (tabCalloutsAll.contains(tabCallout)) { return this; } tabCalloutsAll.add(tabCallout); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\impl\CompositeTabCallout.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isValidUsername3(String username) { return userRoleRepository.isValidUsername(username); } @PreAuthorize("#username == authentication.principal.username") public String getMyRoles(String username) { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } @PostAuthorize("#username == authentication.principal.username") public String getMyRoles2(String username) { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } @PostAuthorize("returnObject.username == authentication.principal.nickName") public CustomUser loadUserDetail(String username) { return userRoleRepository.loadUserByUserName(username); } @PreFilter("filterObject != authentication.principal.username") public String joinUsernames(List<String> usernames) { return usernames.stream().collect(Collectors.joining(";")); }
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames") public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) { return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";")); } @PostFilter("filterObject != authentication.principal.username") public List<String> getAllUsernamesExceptCurrent() { return userRoleRepository.getAllUsernames(); } @IsViewer public String getUsername4() { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getName(); } @PreAuthorize("#username == authentication.principal.username") @PostAuthorize("returnObject.username == authentication.principal.nickName") public CustomUser securedLoadUserDetail(String username) { return userRoleRepository.loadUserByUserName(username); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java
2
请在Spring Boot框架中完成以下Java代码
public class CustomerImportService extends BaseEntityImportService<CustomerId, Customer, EntityExportData<Customer>> { private final CustomerService customerService; private final CustomerDao customerDao; @Override protected void setOwner(TenantId tenantId, Customer customer, IdProvider idProvider) { customer.setTenantId(tenantId); } @Override protected Customer prepare(EntitiesImportCtx ctx, Customer customer, Customer old, EntityExportData<Customer> exportData, IdProvider idProvider) { if (customer.isPublic()) { Customer publicCustomer = customerService.findOrCreatePublicCustomer(ctx.getTenantId()); publicCustomer.setExternalId(customer.getExternalId()); return publicCustomer; } else { return customer; } } @Override
protected Customer saveOrUpdate(EntitiesImportCtx ctx, Customer customer, EntityExportData<Customer> exportData, IdProvider idProvider, CompareResult compareResult) { if (!customer.isPublic()) { return customerService.saveCustomer(customer); } else { return customerDao.save(ctx.getTenantId(), customer); } } @Override protected Customer deepCopy(Customer customer) { return new Customer(customer); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\CustomerImportService.java
2
请完成以下Java代码
public void setContentType(@Nullable String contentType) { this.contentType = contentType; } /** * Set the {@link Marshaller} to be used by this message converter. * * @param marshaller The marshaller. */ public void setMarshaller(Marshaller marshaller) { Assert.notNull(marshaller, "marshaller must not be null"); this.marshaller = marshaller; } /** * Set the {@link Unmarshaller} to be used by this message converter. * * @param unmarshaller The unmarshaller. */ public void setUnmarshaller(Unmarshaller unmarshaller) { Assert.notNull(unmarshaller, "unmarshaller must not be null"); this.unmarshaller = unmarshaller; } @Override public void afterPropertiesSet() { Assert.notNull(this.marshaller, "Property 'marshaller' is required"); Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required"); } /** * Marshals the given object to a {@link Message}. */ @Override protected Message createMessage(Object object, MessageProperties messageProperties) throws MessageConversionException { try { if (this.contentType != null) { messageProperties.setContentType(this.contentType); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(bos); this.marshaller.marshal(object, streamResult); return new Message(bos.toByteArray(), messageProperties); } catch (XmlMappingException ex) { throw new MessageConversionException("Could not marshal [" + object + "]", ex);
} catch (IOException ex) { throw new MessageConversionException("Could not marshal [" + object + "]", ex); } } /** * Unmarshals the given {@link Message} into an object. */ @Override public Object fromMessage(Message message) throws MessageConversionException { try { ByteArrayInputStream bis = new ByteArrayInputStream(message.getBody()); StreamSource source = new StreamSource(bis); return this.unmarshaller.unmarshal(source); } catch (IOException ex) { throw new MessageConversionException("Could not access message content: " + message, ex); } catch (XmlMappingException ex) { throw new MessageConversionException("Could not unmarshal message: " + message, ex); } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\MarshallingMessageConverter.java
1
请完成以下Java代码
public List<Rating> findAllRatings() { return ratingRepository.findAll(); } public List<Rating> findAllCachedRatings(Exception exception) { return cacheRepository.findAllCachedRatings(); } @CircuitBreaker(name = "ratingsByIdFromDB", fallbackMethod = "findCachedRatingById") public Rating findRatingById(Long ratingId) { return ratingRepository.findById(ratingId) .orElseThrow(() -> new RatingNotFoundException("Rating not found. ID: " + ratingId)); } public Rating findCachedRatingById(Long ratingId, Exception exception) { return cacheRepository.findCachedRatingById(ratingId); } @Transactional(propagation = Propagation.REQUIRED) public Rating createRating(Rating rating) { Rating newRating = new Rating(); newRating.setBookId(rating.getBookId()); newRating.setStars(rating.getStars()); Rating persisted = ratingRepository.save(newRating); cacheRepository.createRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public void deleteRating(Long ratingId) { ratingRepository.deleteById(ratingId); cacheRepository.deleteRating(ratingId); }
@Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Map<String, String> updates, Long ratingId) { final Rating rating = findRatingById(ratingId); updates.keySet() .forEach(key -> { switch (key) { case "stars": rating.setStars(Integer.parseInt(updates.get(key))); break; } }); Rating persisted = ratingRepository.save(rating); cacheRepository.updateRating(persisted); return persisted; } @Transactional(propagation = Propagation.REQUIRED) public Rating updateRating(Rating rating, Long ratingId) { Preconditions.checkNotNull(rating); Preconditions.checkState(rating.getId() == ratingId); Preconditions.checkNotNull(ratingRepository.findById(ratingId)); return ratingRepository.save(rating); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingService.java
1
请完成以下Java代码
public class LargestPowerOf2 { public long findLargestPowerOf2LessThanTheGivenNumber(long input) { Assert.isTrue(input > 1, "Invalid input"); long firstPowerOf2 = 1; long nextPowerOf2 = 2; while (nextPowerOf2 < input) { firstPowerOf2 = nextPowerOf2; nextPowerOf2 = nextPowerOf2 * 2; } return firstPowerOf2; } public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) { Assert.isTrue(input > 1, "Invalid input"); long temp = input; if (input % 2 == 0) { temp = input - 1; } // Find log base 2 of a given number long power = (long) (Math.log(temp) / Math.log(2)); long result = (long) Math.pow(2, power); return result; } public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) { Assert.isTrue(input > 1, "Invalid input"); long result = 1; for (long i = input - 1; i > 1; i--) { if ((i & (i - 1)) == 0) {
result = i; break; } } return result; } public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) { Assert.isTrue(input > 1, "Invalid input"); long result = 1; long powerOf2; for (long i = 0; i < Long.BYTES * 8; i++) { powerOf2 = 1 << i; if (powerOf2 >= input) { break; } result = powerOf2; } return result; } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\largestpowerof2\LargestPowerOf2.java
1
请完成以下Java代码
public class X_ExternalSystem extends org.compiere.model.PO implements I_ExternalSystem, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1865891126L; /** Standard Constructor */ public X_ExternalSystem (final Properties ctx, final int ExternalSystem_ID, @Nullable final String trxName) { super (ctx, ExternalSystem_ID, trxName); } /** Load Constructor */ public X_ExternalSystem (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); }
@Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem.java
1
请完成以下Spring Boot application配置
server: port: 8081 security: oauth2: resource: token-info-uri: http://localhost:8080/oauth/check_token jwt: key-alias: oauth2 # 如果没有此项会去请求授权服务器获取 key-value: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkF9SyMHeGAsLMwbPsKj/ xpEtS0iCe8vTSBnIGBDZKmB3ma20Ry0Uzn3m+f40RwCXlxnUcvTw7ipoz0tMQERQ b3X4DkYCJXPK6pAD+R9/J5odEwrO2eysByWfcbMjsZw2u5pH5hleMS0YqkrGQOxJ pzlEcKxMePU5KYTbKUJkhOYPY+gQr61g6lF97WggSPtuQn1srT+Ptvfw6yRC4bdI 0zV5emfXjmoLUwaQTRoGYhOFrm97vpoKiltSNIDFW01J1Lr+l77ddDFC6cdiAC0H 5/eENWBBBTFWya8RlBTzHuikfFS1gP49PZ6MYJIVRs8p9YnnKTy7TVcGKY3XZMCA mwIDAQAB
-----END PUBLIC KEY----- key-uri: http://localhost:8080/oauth/token_key id: oauth2 client: client-id: oauth2 client-secret: oauth2 access-token-uri: http://localhost:8080/oauth/token scope: READ logging: level: org.springframework.security: debug
repos\spring-boot-demo-master\demo-oauth\oauth-resource-server\src\main\resources\application.yml
2
请完成以下Java代码
public void onDocValidate(final Object model, final DocTimingType timing) throws Exception { for (final IModelInterceptor interceptor : interceptors) { interceptor.onDocValidate(model, timing); } } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // NOTE: we use "interceptors" instead of userLoginListeners because the "onUserLogin" it's implemented on IModelInterceptor level for (final IModelInterceptor interceptor : interceptors) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); } } @Override public void beforeLogout(final MFSession session)
{ for (final IUserLoginListener listener : userLoginListeners) { listener.beforeLogout(session); } } @Override public void afterLogout(final MFSession session) { for (final IUserLoginListener listener : userLoginListeners) { listener.afterLogout(session); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\CompositeModelInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, List<Map<String, Object>>> getMetricsHistory() { return REDIS_METRICS; } /** * 记录近一小时redis监控数据 <br/> * 60s一次,,记录存储keysize和内存 * @throws RedisConnectException * @author chenrui * @date 2024/5/14 14:09 */ @Scheduled(fixedRate = 60000) public void recordCustomMetric() throws RedisConnectException { List<Map<String, Object>> list= new ArrayList<>(); if(REDIS_METRICS.containsKey("dbSize")){ list = REDIS_METRICS.get("dbSize"); }else{ REDIS_METRICS.put("dbSize",list);
} if(list.size()>60){ list.remove(0); } list.add(getKeysSize()); list= new ArrayList<>(); if(REDIS_METRICS.containsKey("memory")){ list = REDIS_METRICS.get("memory"); }else{ REDIS_METRICS.put("memory",list); } if(list.size()>60){ list.remove(0); } list.add(getMemoryInfo()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\monitor\service\impl\RedisServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder()); authenticationProvider.setHideUserNotFoundExceptions(false); return authenticationProvider; } @Override protected void configure(HttpSecurity http) throws Exception {
http .requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**") .and() .authorizeRequests() .antMatchers("/oauth/**").authenticated() .and() .formLogin().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } }
repos\Spring-Boot-In-Action-master\springbt_sso_jwt\codesheep-server\src\main\java\cn\codesheep\config\SpringSecurityConfig.java
2
请完成以下Java代码
public String getValue() { return value; } public void setValue(String value) { this.value = value; } public TemplateType getType() { return type; } public void setType(TemplateType type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TemplateDefinition that = (TemplateDefinition) o; return ( Objects.equals(from, that.from) && Objects.equals(subject, that.subject) && type == that.type && Objects.equals(value, that.value) ); } @Override
public int hashCode() { return Objects.hash(from, subject, type, value); } @Override public String toString() { return ( "TemplateDefinition{" + "from='" + from + '\'' + ", subject='" + subject + '\'' + ", type=" + type + ", value='" + value + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplateDefinition.java
1
请完成以下Java代码
public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } @Override public void setM_Pricelist_Version_Base_ID (final int M_Pricelist_Version_Base_ID) { if (M_Pricelist_Version_Base_ID < 1) set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, null); else set_Value (COLUMNNAME_M_Pricelist_Version_Base_ID, M_Pricelist_Version_Base_ID); } @Override public int getM_Pricelist_Version_Base_ID() { return get_ValueAsInt(COLUMNNAME_M_Pricelist_Version_Base_ID); } @Override public void setM_PriceList_Version_ID (final int M_PriceList_Version_ID) { if (M_PriceList_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PriceList_Version_ID, M_PriceList_Version_ID); } @Override public int getM_PriceList_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_Version_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcCreate (final @Nullable java.lang.String ProcCreate) { set_Value (COLUMNNAME_ProcCreate, ProcCreate); } @Override public java.lang.String getProcCreate()
{ return get_ValueAsString(COLUMNNAME_ProcCreate); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList_Version.java
1
请完成以下Java代码
protected void createTenantAsyncJobExecutor(String tenantId) { ((TenantAwareAsyncExecutor) asyncExecutor).addTenantAsyncExecutor(tenantId, isAsyncExecutorActivate() && booted); } @Override public CommandInterceptor createTransactionInterceptor() { return null; } @Override protected void postProcessEngineInitialisation() { // empty here. will be done in registerTenant } @Override public Runnable getProcessEngineCloseRunnable() { return new Runnable() { @Override public void run() { for (String tenantId : tenantInfoHolder.getAllTenants()) { tenantInfoHolder.setCurrentTenantId(tenantId); if (asyncExecutor != null) { commandExecutor.execute(new ClearProcessInstanceLockTimesCmd(asyncExecutor.getLockOwner())); } commandExecutor.execute(getProcessEngineCloseCommand()); tenantInfoHolder.clearCurrentTenantId();
} } }; } public Command<Void> getProcessEngineCloseCommand() { return new Command<>() { @Override public Void execute(CommandContext commandContext) { CommandContextUtil.getProcessEngineConfiguration(commandContext).getCommandExecutor().execute(new SchemaOperationProcessEngineClose()); return null; } }; } public TenantInfoHolder getTenantInfoHolder() { return tenantInfoHolder; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\multitenant\MultiSchemaMultiTenantProcessEngineConfiguration.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Dunning Date. @param DunningDate Date of Dunning */ public void setDunningDate (Timestamp DunningDate) { set_Value (COLUMNNAME_DunningDate, DunningDate); } /** Get Dunning Date. @return Date of Dunning */ public Timestamp getDunningDate () { return (Timestamp)get_Value(COLUMNNAME_DunningDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getDunningDate())); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) {
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send. @param SendIt Send */ public void setSendIt (String SendIt) { set_Value (COLUMNNAME_SendIt, SendIt); } /** Get Send. @return Send */ public String getSendIt () { return (String)get_Value(COLUMNNAME_SendIt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
1
请在Spring Boot框架中完成以下Java代码
public class IncidentRestServiceImpl extends AbstractRestProcessEngineAware implements IncidentRestService { public IncidentRestServiceImpl(String engineName, ObjectMapper objectMapper) { super(engineName, objectMapper); } @Override public List<IncidentDto> getIncidents(UriInfo uriInfo, Integer firstResult, Integer maxResults) { IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); IncidentQuery query = queryDto.toQuery(getProcessEngine()); List<Incident> queryResult = QueryUtil.list(query, firstResult, maxResults); List<IncidentDto> result = new ArrayList<>(); for (Incident incident : queryResult) { IncidentDto dto = IncidentDto.fromIncident(incident); result.add(dto); } return result; } @Override
public CountResultDto getIncidentsCount(UriInfo uriInfo) { IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); IncidentQuery query = queryDto.toQuery(getProcessEngine()); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } @Override public IncidentResource getIncident(String incidentId) { return new IncidentResourceImpl(getProcessEngine(), incidentId, getObjectMapper()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\IncidentRestServiceImpl.java
2
请完成以下Java代码
public void setDynPriorityStart (final int DynPriorityStart) { set_Value (COLUMNNAME_DynPriorityStart, DynPriorityStart); } @Override public int getDynPriorityStart() { return get_ValueAsInt(COLUMNNAME_DynPriorityStart); } @Override public void setEndWaitTime (final java.sql.Timestamp EndWaitTime) { set_Value (COLUMNNAME_EndWaitTime, EndWaitTime); } @Override public java.sql.Timestamp getEndWaitTime() { return get_ValueAsTimestamp(COLUMNNAME_EndWaitTime); } @Override public void setPriority (final int Priority) { set_Value (COLUMNNAME_Priority, Priority); } @Override public int getPriority() { return get_ValueAsInt(COLUMNNAME_Priority); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @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); }
@Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg); } /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Activity.java
1
请完成以下Java代码
public Quantity getQty() { return itemStorage.getQuantity(getProductId(), getC_UOM()); } @Override public final Quantity getQty(final I_C_UOM uom) { final ProductId productId = getProductId(); final Quantity qty = getQty(); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final UOMConversionContext conversionCtx= UOMConversionContext.of(productId); return uomConversionBL.convertQuantityTo(qty, conversionCtx, uom); } @Override public BigDecimal getQtyCapacity() { final Capacity capacityTotal = getTotalCapacity(); return capacityTotal.toBigDecimal(); } @Override public IAllocationRequest addQty(final IAllocationRequest request) { return itemStorage.requestQtyToAllocate(request); } @Override
public IAllocationRequest removeQty(final IAllocationRequest request) { return itemStorage.requestQtyToDeallocate(request); } @Override public void markStaled() { // nothing, so far, itemStorage is always database coupled, no in memory values } @Override public boolean isEmpty() { return itemStorage.isEmpty(getProductId()); } @Override public boolean isAllowNegativeStorage() { return itemStorage.isAllowNegativeStorage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemProductStorage.java
1
请完成以下Java代码
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { BoundaryEvent boundaryEvent = (BoundaryEvent) element; if (boundaryEvent.getAttachedToRef() != null) { writeDefaultAttribute(ATTRIBUTE_BOUNDARY_ATTACHEDTOREF, boundaryEvent.getAttachedToRef().getId(), xtw); } if (boundaryEvent.getEventDefinitions().size() == 1) { EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0); if (!(eventDef instanceof ErrorEventDefinition)) { writeDefaultAttribute(ATTRIBUTE_BOUNDARY_CANCELACTIVITY, String.valueOf(boundaryEvent.isCancelActivity()).toLowerCase(), xtw); } } else if (!boundaryEvent.getExtensionElements().isEmpty()) { List<ExtensionElement> eventTypeExtensionElements = boundaryEvent.getExtensionElements().get(BpmnXMLConstants.ELEMENT_EVENT_TYPE); if (eventTypeExtensionElements != null && !eventTypeExtensionElements.isEmpty()) { String eventTypeValue = eventTypeExtensionElements.get(0).getElementText(); if (StringUtils.isNotEmpty(eventTypeValue)) { writeDefaultAttribute(ATTRIBUTE_BOUNDARY_CANCELACTIVITY, String.valueOf(boundaryEvent.isCancelActivity()).toLowerCase(), xtw);
} } } } @Override protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception { BoundaryEvent boundaryEvent = (BoundaryEvent) element; didWriteExtensionStartElement = BpmnXMLUtil.writeIOParameters(ELEMENT_IN_PARAMETERS, boundaryEvent.getInParameters(), didWriteExtensionStartElement, xtw); didWriteExtensionStartElement = writeVariableListenerDefinition(boundaryEvent, didWriteExtensionStartElement, xtw); return didWriteExtensionStartElement; } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { BoundaryEvent boundaryEvent = (BoundaryEvent) element; writeEventDefinitions(boundaryEvent, boundaryEvent.getEventDefinitions(), model, xtw); } }
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\BoundaryEventXMLConverter.java
1
请完成以下Java代码
private boolean isQuantityWithinCurrentScale( @NonNull final RefundInvoiceCandidate candidateToUpdate, @NonNull final RefundConfig refundConfig, @NonNull final Quantity quantity) { final Quantity assignableQty = candidateToUpdate.computeAssignableQuantity(refundConfig); final boolean withinCurrentScale = assignableQty.compareTo(quantity) >= 0; return withinCurrentScale; } public boolean isRefundInvoiceCandidateRecord(@NonNull final I_C_Invoice_Candidate record) { if (record.getAD_Table_ID() != getTableId(I_C_Flatrate_Term.class)) { return false; } final I_C_Flatrate_Term term = loadOutOfTrx(record.getRecord_ID(), I_C_Flatrate_Term.class); final boolean recordIsARefundCandidate = X_C_Flatrate_Term.TYPE_CONDITIONS_Refund.equals(term.getType_Conditions());
return recordIsARefundCandidate; } public RefundInvoiceCandidate updateMoneyFromAssignments(@NonNull final RefundInvoiceCandidate refundCandidate) { final InvoiceCandidateId id = refundCandidate.getId(); final BigDecimal newMoneyAmount = assignmentAggregateService.retrieveMoneyAmount(id); final Money newMoney = Money.of( newMoneyAmount, refundCandidate.getMoney().getCurrencyId()); final RefundInvoiceCandidate candidateWithUpdatedMoney = refundCandidate .toBuilder() .money(newMoney) .build(); return refundInvoiceCandidateRepository.save(candidateWithUpdatedMoney); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundInvoiceCandidateService.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderedArticleLineDuration { @SerializedName("amount") private BigDecimal amount = null; @SerializedName("timePeriod") private BigDecimal timePeriod = null; public OrderedArticleLineDuration amount(BigDecimal amount) { this.amount = amount; return this; } /** * Anzahl der Tage, Wochen, Monate * @return amount **/ @Schema(example = "30", description = "Anzahl der Tage, Wochen, Monate") public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public OrderedArticleLineDuration timePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; return this; } /** * Zeitintervall (Unbekannt &#x3D; 0, Minute &#x3D; 1, Stunde &#x3D; 2, Tag &#x3D; 3, Woche &#x3D; 4, Monat &#x3D; 5, Quartal &#x3D; 6, Halbjahr &#x3D; 7, Jahr &#x3D; 8) * @return timePeriod **/ @Schema(example = "3", description = "Zeitintervall (Unbekannt = 0, Minute = 1, Stunde = 2, Tag = 3, Woche = 4, Monat = 5, Quartal = 6, Halbjahr = 7, Jahr = 8)") public BigDecimal getTimePeriod() { return timePeriod; } public void setTimePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderedArticleLineDuration orderedArticleLineDuration = (OrderedArticleLineDuration) o; return Objects.equals(this.amount, orderedArticleLineDuration.amount) && Objects.equals(this.timePeriod, orderedArticleLineDuration.timePeriod); } @Override
public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderedArticleLineDuration {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderedArticleLineDuration.java
2
请完成以下Java代码
public boolean isRoute() { return route; } public void setRoute(boolean route) { this.route = route; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public boolean getIsLeaf() { return isLeaf; } public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; }
public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal; } public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
public void add( final Properties ctx, final int M_Warehouse_ID, final int M_Locator_ID, final int M_Product_ID, final int M_AttributeSetInstance_ID, final int reservationAttributeSetInstance_ID, final BigDecimal diffQtyOnHand, final BigDecimal diffQtyReserved, final BigDecimal diffQtyOrdered, final String trxName) { if (isMStorageDisabled()) { return; } MStorage.add(ctx,
M_Warehouse_ID, M_Locator_ID, M_Product_ID, M_AttributeSetInstance_ID, reservationAttributeSetInstance_ID, diffQtyOnHand, diffQtyReserved, diffQtyOrdered, trxName); } private boolean isMStorageDisabled() { return Services.get(ISysConfigBL.class).getBooleanValue(CFG_M_STORAGE_DISABLED, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StorageBL.java
1
请完成以下Java代码
public static AvailableForSaleResultBuilder createEmptyWithPredefinedBuckets(@NonNull final AvailableForSalesMultiQuery multiQuery) { final ImmutableList.Builder<AvailableForSaleResultBucket> buckets = ImmutableList.builder(); final List<AvailableForSalesQuery> availableForSalesQueries = multiQuery.getAvailableForSalesQueries(); for (final AvailableForSalesQuery query : availableForSalesQueries) { final List<AttributesKeyMatcher> storageAttributesKeyMatchers = AttributesKeyPatternsUtil.extractAttributesKeyMatchers(Collections.singletonList(query.getStorageAttributesKeyPattern())); final ProductId productId = query.getProductId(); for (final AttributesKeyMatcher storageAttributesKeyMatcher : storageAttributesKeyMatchers) { final AvailableForSaleResultBucket bucket = AvailableForSaleResultBucket.builder() .product(ProductClassifier.specific(productId.getRepoId())) .storageAttributesKeyMatcher(storageAttributesKeyMatcher) .warehouse(WarehouseClassifier.specificOrAny(query.getWarehouseId())) .build(); bucket.addDefaultEmptyGroupIfPossible(); buckets.add(bucket); } } return new AvailableForSaleResultBuilder(buckets.build()); } private final ArrayList<AvailableForSaleResultBucket> buckets; @VisibleForTesting AvailableForSaleResultBuilder(final List<AvailableForSaleResultBucket> buckets) { this.buckets = new ArrayList<>(buckets); } public AvailableForSalesLookupResult build() {
final ImmutableList<AvailableForSalesLookupBucketResult> groups = buckets.stream() .flatMap(AvailableForSaleResultBucket::buildAndStreamGroups) .collect(ImmutableList.toImmutableList()); return AvailableForSalesLookupResult.builder().availableForSalesResults(groups).build(); } public void addQtyToAllMatchingGroups(@NonNull final AddToResultGroupRequest request) { // note that we might select more quantities than we actually wanted (bc of the way we match attributes in the query using LIKE) // for that reason, we need to be lenient in case not all quantities can be added to a bucked buckets.forEach(bucket -> bucket.addQtyToAllMatchingGroups(request)); } @VisibleForTesting ImmutableList<AvailableForSaleResultBucket> getBuckets() { return ImmutableList.copyOf(buckets); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AvailableForSaleResultBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public ReferenceType getBillOfLadingReference() { return billOfLadingReference; } /** * Sets the value of the billOfLadingReference property. * * @param value * allowed object is * {@link ReferenceType } * */ public void setBillOfLadingReference(ReferenceType value) { this.billOfLadingReference = value; } /** * Gets the value of the supplierOrderReference property. * * @return * possible object is * {@link ReferenceType } * */ public ReferenceType getSupplierOrderReference() { return supplierOrderReference; } /** * Sets the value of the supplierOrderReference property. * * @param value
* allowed object is * {@link ReferenceType } * */ public void setSupplierOrderReference(ReferenceType value) { this.supplierOrderReference = value; } /** * Reference to the consignment. * * @return * possible object is * {@link String } * */ public String getConsignmentReference() { return consignmentReference; } /** * Sets the value of the consignmentReference property. * * @param value * allowed object is * {@link String } * */ public void setConsignmentReference(String value) { this.consignmentReference = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DESADVExtensionType.java
2
请完成以下Java代码
public boolean getShowWarehouseFlag() { final ActionType currentActionType = getActionType(); if (currentActionType == null) { return false; } final boolean isMoveToWarehouseAllowed = _isMoveToDifferentWarehouseEnabled && statusBL.isStatusActive(getSelectedRow().getM_HU()); if (!isMoveToWarehouseAllowed) { return false; } final boolean showWarehouse;
switch (currentActionType) { case CU_To_NewCU: case CU_To_NewTUs: case TU_To_NewLUs: case TU_To_NewTUs: showWarehouse = true; break; default: showWarehouse = false; } return showWarehouse; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WebuiHUTransformParametersFiller.java
1
请完成以下Java代码
public void innerProductVectors() throws Exception { Vector v1 = new DenseVector(new double[]{1, 2, 3, 4, 5}); Vector v2 = new DenseVector(new double[]{5, 4, 3, 2, 1}); double inner = v1.innerProduct(v2); log.info("Vector inner product: {}", inner); } public void addingIncorrectVectors() throws Exception { Vector v1 = new DenseVector(new double[]{1, 2, 3}); Vector v2 = new DenseVector(new double[]{5, 4}); Vector v3 = v1.add(v2); log.info("Adding vectors: {}", v3); } public void addingMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4} }); Matrix m3 = m1.add(m2); log.info("Adding matrices: {}", m3); } public void multiplyMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {1, 4}, {2, 5}, {3, 6} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void multiplyIncorrectMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4}
}); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void inverseMatrix() { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2}, {3, 4} }); Inverse m2 = new Inverse(m1); log.info("Inverting a matrix: {}", m2); log.info("Verifying a matrix inverse: {}", m1.multiply(m2)); } public Polynomial createPolynomial() { return new Polynomial(new double[]{3, -5, 1}); } public void evaluatePolynomial(Polynomial p) { // Evaluate using a real number log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5)); // Evaluate using a complex number log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2))); } public void solvePolynomial() { Polynomial p = new Polynomial(new double[]{2, 2, -4}); PolyRootSolver solver = new PolyRoot(); List<? extends Number> roots = solver.solve(p); log.info("Finding polynomial roots: {}", roots); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\suanshu\SuanShuMath.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaMobileAppBundleDao extends JpaAbstractDao<MobileAppBundleEntity, MobileAppBundle> implements MobileAppBundleDao { private final MobileAppBundleRepository mobileAppBundleRepository; private final MobileAppBundleOauth2ClientRepository mobileOauth2ProviderRepository; @Override protected Class<MobileAppBundleEntity> getEntityClass() { return MobileAppBundleEntity.class; } @Override protected JpaRepository<MobileAppBundleEntity, UUID> getRepository() { return mobileAppBundleRepository; } @Override public PageData<MobileAppBundleInfo> findInfosByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(mobileAppBundleRepository.findInfoByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public MobileAppBundleInfo findInfoById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.getData(mobileAppBundleRepository.findInfoById(mobileAppBundleId.getId())); } @Override public List<MobileAppBundleOauth2Client> findOauth2ClientsByMobileAppBundleId(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { return DaoUtil.convertDataList(mobileOauth2ProviderRepository.findAllByMobileAppBundleId(mobileAppBundleId.getId())); } @Override public void addOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) { mobileOauth2ProviderRepository.save(new MobileAppBundleOauth2ClientEntity(mobileAppBundleOauth2Client)); } @Override public void removeOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) { mobileOauth2ProviderRepository.deleteById(new MobileAppOauth2ClientCompositeKey(mobileAppBundleOauth2Client.getMobileAppBundleId().getId(), mobileAppBundleOauth2Client.getOAuth2ClientId().getId())); }
@Override public MobileAppBundle findByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) { return DaoUtil.getData(mobileAppBundleRepository.findByPkgNameAndPlatformType(pkgName, platform)); } @Override public void deleteByTenantId(TenantId tenantId) { mobileAppBundleRepository.deleteByTenantId(tenantId.getId()); } @Override public EntityType getEntityType() { return EntityType.MOBILE_APP_BUNDLE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\mobile\JpaMobileAppBundleDao.java
2
请完成以下Java代码
public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } /** Set Nutzer 1. @param User1_ID User defined list element #1 */ @Override public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get Nutzer 1. @return User defined list element #1 */ @Override public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } /** Set Nutzer 2. @param User2_ID User defined list element #2 */ @Override public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get Nutzer 2. @return User defined list element #2 */ @Override public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Distribution.java
1
请完成以下Java代码
public class TriaFrequency extends PairFrequency { public String third; private TriaFrequency(String term, Integer frequency) { super(term, frequency); } private TriaFrequency(String term) { super(term); } /** * 构造一个三阶接续,正向 * * @param first * @param second * @param third * @param delimiter 一般使用RIGHT! * @return */ public static TriaFrequency create(String first, char delimiter, String second, String third) { TriaFrequency triaFrequency = new TriaFrequency(first + delimiter + second + Occurrence.RIGHT + third); triaFrequency.first = first; triaFrequency.second = second; triaFrequency.third = third; triaFrequency.delimiter = delimiter; return triaFrequency; } /** * 构造一个三阶接续,逆向 * @param second * @param third * @param delimiter 一般使用LEFT * @param first * @return */ public static TriaFrequency create(String second, String third, char delimiter, String first)
{ TriaFrequency triaFrequency = new TriaFrequency(second + Occurrence.RIGHT + third + delimiter + first); triaFrequency.first = first; triaFrequency.second = second; triaFrequency.third = third; triaFrequency.delimiter = delimiter; return triaFrequency; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(getKey().replace(Occurrence.LEFT, '←').replace(Occurrence.RIGHT, '→')); sb.append('='); sb.append(" tf="); sb.append(getValue()); sb.append(' '); sb.append("mi="); sb.append(mi); sb.append(" le="); sb.append(le); sb.append(" re="); sb.append(re); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\occurrence\TriaFrequency.java
1
请完成以下Java代码
private static Duration extractKeepAlive(@NonNull final I_C_Async_Batch_Type asyncBatchType) { final String keepAliveTimeHoursStr = StringUtils.trimBlankToNull(asyncBatchType.getKeepAliveTimeHours()); // if null or empty, keep alive forever if (keepAliveTimeHoursStr == null) { return Duration.ZERO; } final int keepAliveTimeHours = Integer.parseInt(keepAliveTimeHoursStr); return keepAliveTimeHours > 0 ? Duration.ofHours(keepAliveTimeHours) : Duration.ZERO; } private static Duration extractSkipTimeout(final I_C_Async_Batch_Type asyncBatchType) { final int skipTimeoutMillis = asyncBatchType.getSkipTimeoutMillis(); return skipTimeoutMillis > 0 ? Duration.ofMillis(skipTimeoutMillis) : Duration.ZERO; } private void updateProcessedFlag(@NonNull final I_C_Async_Batch asyncBatch) { final List<I_C_Queue_WorkPackage> workPackages = asyncBatchDAO.retrieveWorkPackages(asyncBatch, null); if (Check.isEmpty(workPackages)) { return; } final int workPackagesProcessedCount = (int)workPackages.stream() .filter(I_C_Queue_WorkPackage::isProcessed) .count(); final int workPackagesWithErrorCount = (int)workPackages.stream() .filter(I_C_Queue_WorkPackage::isError) .count(); final int workPackagesFinalized = workPackagesProcessedCount + workPackagesWithErrorCount; final boolean allWorkPackagesAreDone = workPackagesFinalized >= workPackages.size(); final boolean isProcessed = asyncBatch.getCountExpected() > 0 ? allWorkPackagesAreDone && workPackagesFinalized >= asyncBatch.getCountExpected() : allWorkPackagesAreDone; asyncBatch.setProcessed(isProcessed); asyncBatch.setIsProcessing(!allWorkPackagesAreDone); } private int getProcessedTimeOffsetMillis() { return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_PROCESSED_OFFSET_MILLIS, 1);
} private void save(final I_C_Async_Batch asyncBatch) { Services.get(IQueueDAO.class).save(asyncBatch); } private int setAsyncBatchCountEnqueued(@NonNull final I_C_Queue_WorkPackage workPackage, final int offset) { final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID()); if (asyncBatchId == null) { return 0; } lock.lock(); try { final I_C_Async_Batch asyncBatch = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(asyncBatchId); final Timestamp enqueued = SystemTime.asTimestamp(); if (asyncBatch.getFirstEnqueued() == null) { asyncBatch.setFirstEnqueued(enqueued); } asyncBatch.setLastEnqueued(enqueued); final int countEnqueued = asyncBatch.getCountEnqueued() + offset; asyncBatch.setCountEnqueued(countEnqueued); // we just enqueued something, so we are clearly not done yet asyncBatch.setIsProcessing(true); asyncBatch.setProcessed(false); save(asyncBatch); return countEnqueued; } finally { lock.unlock(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBL.java
1
请完成以下Java代码
private I_C_OLCand getOLCand(@NonNull final I_C_Invoice_Candidate ic) { return TableRecordCacheLocal.getReferencedValue(ic, I_C_OLCand.class); } /** * <ul> * <li>QtyDelivered := QtyOrdered * <li>DeliveryDate := DateOrdered * <li>M_InOut_ID: untouched * </ul> * * @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate) */ @Override public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic) { ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially ic.setQtyDeliveredInUOM(ic.getQtyEntered()); ic.setDeliveryDate(ic.getDateOrdered()); } @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic) { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(ic.getAD_Org_ID()));
final I_C_OLCand olc = getOLCand(ic); final IPricingResult pricingResult = Services.get(IOLCandBL.class).computePriceActual( olc, null, PricingSystemId.NULL, TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olc), timeZone)); return PriceAndTax.builder() .priceUOMId(pricingResult.getPriceUomId()) .priceActual(pricingResult.getPriceStd()) .taxIncluded(pricingResult.isTaxIncluded()) .invoicableQtyBasedOn(pricingResult.getInvoicableQtyBasedOn()) .build(); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_OLCand olc = getOLCand(ic); InvoiceCandidateLocationAdapterFactory .billLocationAdapter(ic) .setFrom(olCandEffectiveValuesBL.getBuyerPartnerInfo(olc)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\invoicecandidate\spi\impl\C_OLCand_Handler.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Saml2X509Credential that = (Saml2X509Credential) o; return Objects.equals(this.privateKey, that.privateKey) && this.certificate.equals(that.certificate) && this.credentialTypes.equals(that.credentialTypes); } @Override public int hashCode() { return Objects.hash(this.privateKey, this.certificate, this.credentialTypes); } private void validateUsages(Saml2X509CredentialType[] usages, Saml2X509CredentialType... validUsages) { for (Saml2X509CredentialType usage : usages) { boolean valid = false; for (Saml2X509CredentialType validUsage : validUsages) { if (usage == validUsage) { valid = true; break; }
} Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } public enum Saml2X509CredentialType { VERIFICATION, ENCRYPTION, SIGNING, DECRYPTION, } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2X509Credential.java
2
请完成以下Java代码
public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); } // propertyChange /** * Return Editor value * @return value */ public Object getValue() { return String.valueOf(getPassword()); } // getValue /** * Return Display Value * @return value */ public String getDisplay() { return String.valueOf(getPassword()); } // getDisplay /************************************************************************** * Key Listener Interface * @param e event */ public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} /** * Key Listener. * @param e event */ public void keyReleased(KeyEvent e) { String newText = String.valueOf(getPassword()); m_setting = true; try { fireVetoableChange(m_columnName, m_oldText, newText); } catch (PropertyVetoException pve) {} m_setting = false; } // keyReleased /** * Data Binding to MTable (via GridController) - Enter pressed * @param e event */ public void actionPerformed(ActionEvent e) { String newText = String.valueOf(getPassword());
// Data Binding try { fireVetoableChange(m_columnName, m_oldText, newText); } catch (PropertyVetoException pve) {} } // actionPerformed /** * Set Field/WindowNo for ValuePreference * @param mField field */ public void setField (GridField mField) { m_mField = mField; } // setField @Override public GridField getField() { return m_mField; } // metas: Ticket#2011062310000013 public boolean isAutoCommit() { return false; } } // VPassword
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java
1
请完成以下Java代码
private static String firstExists(File... paths) { for (File path : paths) { if (path.exists()) { return path.getAbsolutePath(); } } return null; } public static String getUserDir() { String userDir = System.getProperty("user.dir"); String binFolder = getEnvOrDefault("KKFILEVIEW_BIN_FOLDER", userDir); File pluginPath = new File(binFolder); // 如果指定了 bin 或其父目录,则返回父目录 if (new File(pluginPath, "bin").exists()) { return pluginPath.getAbsolutePath(); } else if (pluginPath.exists() && pluginPath.getName().equals("bin")) { return pluginPath.getParentFile().getAbsolutePath(); } else { return firstExists(new File(pluginPath, MAIN_DIRECTORY_NAME), new File(pluginPath.getParentFile(), MAIN_DIRECTORY_NAME)); } } public static String getCustomizedConfigPath() {
String homePath = getHomePath(); String separator = java.io.File.separator; return homePath + separator + "config" + separator + "application.properties"; } public synchronized static void restorePropertiesFromEnvFormat(Properties properties) { Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Object, Object> entry = iterator.next(); String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (value.trim().startsWith("${") && value.trim().endsWith("}")) { int beginIndex = value.indexOf(":"); if (beginIndex < 0) { beginIndex = value.length() - 1; } int endIndex = value.length() - 1; String envKey = value.substring(2, beginIndex); String envValue = System.getenv(envKey); if (envValue == null || "".equals(envValue.trim())) { value = value.substring(beginIndex + 1, endIndex); } else { value = envValue; } properties.setProperty(key, value); } } } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\ConfigUtils.java
1
请完成以下Java代码
public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) { correlationParameterValues.put(parameterName, parameterValue); return this; } @Override public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValues(Map<String, Object> parameters) { correlationParameterValues.putAll(parameters); return this; } public String getProcessDefinitionId() { return processDefinitionId; } public String getTenantId() { return tenantId; } public boolean hasCorrelationParameterValues() { return correlationParameterValues.size() > 0;
} public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } @Override public void deleteSubscriptions() { checkValidInformation(); runtimeService.deleteProcessInstanceStartEventSubscriptions(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionId)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the exact id of the version the subscription was registered for."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionDeletionBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Customer getCustomerById(@PathVariable final String customerId) { return customerService.getCustomerDetail(customerId); } @GetMapping("/{customerId}/{orderId}") public Order getOrderById(@PathVariable final String customerId, @PathVariable final String orderId) { return orderService.getOrderByIdForCustomer(customerId, orderId); } @GetMapping(value = "/{customerId}/orders", produces = { "application/hal+json" }) public CollectionModel<Order> getOrdersForCustomer(@PathVariable final String customerId) { final List<Order> orders = orderService.getAllOrdersForCustomer(customerId); for (final Order order : orders) { final Link selfLink = linkTo( methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel(); order.add(selfLink); } Link link = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel(); CollectionModel<Order> result = CollectionModel.of(orders, link); return result; } @GetMapping(produces = { "application/hal+json" }) public CollectionModel<Customer> getAllCustomers() { final List<Customer> allCustomers = customerService.allCustomers();
for (final Customer customer : allCustomers) { String customerId = customer.getCustomerId(); Link selfLink = linkTo(CustomerController.class).slash(customerId) .withSelfRel(); customer.add(selfLink); if (orderService.getAllOrdersForCustomer(customerId) .size() > 0) { final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)) .withRel("allOrders"); customer.add(ordersLink); } } Link link = linkTo(CustomerController.class).withSelfRel(); CollectionModel<Customer> result = CollectionModel.of(allCustomers, link); return result; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\CustomerController.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricEntityLinksByScopeIdAndType(String scopeId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("scopeId", scopeId); parameters.put("scopeType", scopeType); getDbSqlSession().delete("deleteHistoricEntityLinksByScopeIdAndScopeType", parameters, HistoricEntityLinkEntityImpl.class); } @Override public void deleteHistoricEntityLinksByScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("scopeDefinitionId", scopeDefinitionId); parameters.put("scopeType", scopeType); getDbSqlSession().delete("deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType", parameters, HistoricEntityLinkEntityImpl.class); } @Override public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) { Map<String, Object> parameters = new HashMap<>(); parameters.put("scopeType", scopeType); parameters.put("scopeIds", createSafeInValuesList(scopeIds));
getDbSqlSession().delete("bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds", parameters, HistoricEntityLinkEntityImpl.class); } @Override public void deleteHistoricEntityLinksForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricProcessEntityLinks", null, HistoricEntityLinkEntityImpl.class); } @Override public void deleteHistoricEntityLinksForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricCaseEntityLinks", null, HistoricEntityLinkEntityImpl.class); } @Override protected IdGenerator getIdGenerator() { return entityLinkServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\data\impl\MybatisHistoricEntityLinkDataManager.java
2
请完成以下Java代码
public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(JasperRerportsSimpleConfig.class); ctx.refresh(); SimpleReportFiller simpleReportFiller = ctx.getBean(SimpleReportFiller.class); simpleReportFiller.setReportFileName("employeeEmailReport.jrxml"); simpleReportFiller.compileReport(); simpleReportFiller.setReportFileName("employeeReport.jrxml"); simpleReportFiller.compileReport(); Map<String, Object> parameters = new HashMap<>(); parameters.put("title", "Employee Report Example"); parameters.put("minSalary", 15000.0);
parameters.put("condition", " LAST_NAME ='Smith' ORDER BY FIRST_NAME"); simpleReportFiller.setParameters(parameters); simpleReportFiller.fillReport(); SimpleReportExporter simpleExporter = ctx.getBean(SimpleReportExporter.class); simpleExporter.setJasperPrint(simpleReportFiller.getJasperPrint()); simpleExporter.exportToPdf("employeeReport.pdf", "baeldung"); simpleExporter.exportToXlsx("employeeReport.xlsx", "Employee Data"); simpleExporter.exportToCsv("employeeReport.csv"); simpleExporter.exportToHtml("employeeReport.html"); } }
repos\tutorials-master\libraries-reporting\src\main\java\com\baeldung\jasperreports\Main.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessContainer[") .append(get_ID()).append("]"); return sb.toString(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Container getCM_Container() throws RuntimeException { return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name) .getPO(getCM_Container_ID(), get_TrxName()); }
/** Set Web Container. @param CM_Container_ID Web Container contains content like images, text etc. */ public void setCM_Container_ID (int CM_Container_ID) { if (CM_Container_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessContainer.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteTasksByExecutionId(String executionId) { DbSqlSession dbSqlSession = getDbSqlSession(); if (isEntityInserted(dbSqlSession, "execution", executionId)) { deleteCachedEntities(dbSqlSession, tasksByExecutionIdMatcher, executionId); } else { bulkDelete("deleteTasksByExecutionId", tasksByExecutionIdMatcher, executionId); } } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); } protected void setSafeInValueLists(TaskQueryImpl taskQuery) { if (taskQuery.getCandidateGroups() != null) { taskQuery.setSafeCandidateGroups(createSafeInValuesList(taskQuery.getCandidateGroups()));
} if (taskQuery.getInvolvedGroups() != null) { taskQuery.setSafeInvolvedGroups(createSafeInValuesList(taskQuery.getInvolvedGroups())); } if (taskQuery.getScopeIds() != null) { taskQuery.setSafeScopeIds(createSafeInValuesList(taskQuery.getScopeIds())); } if (taskQuery.getOrQueryObjects() != null && !taskQuery.getOrQueryObjects().isEmpty()) { for (TaskQueryImpl orTaskQuery : taskQuery.getOrQueryObjects()) { setSafeInValueLists(orTaskQuery); } } } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MybatisTaskDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public class App { public static void main(String[] args) { insertAndDeleteInsideTransaction(); crudOperations(); queryCustomers(); } @Transactional public static void insertAndDeleteInsideTransaction() { Customer c1 = getCustomer(); Database server = DB.getDefault(); server.save(c1); Customer foundC1 = server.find(Customer.class, c1.getId()); server.delete(foundC1); } public static void crudOperations() { Address a1 = new Address("5, Wide Street", null, "New York"); Customer c1 = new Customer("John Wide", a1); Database server = DB.getDefault(); server.save(c1); c1.setName("Jane Wide"); c1.setAddress(null); server.save(c1); Customer foundC1 = DB.find(Customer.class, c1.getId()); DB.delete(foundC1); } public static void queryCustomers() {
Address a1 = new Address("1, Big Street", null, "New York"); Customer c1 = new Customer("Big John", a1); Address a2 = new Address("2, Big Street", null, "New York"); Customer c2 = new Customer("Big John", a2); Address a3 = new Address("3, Big Street", null, "San Jose"); Customer c3 = new Customer("Big Bob", a3); DB.saveAll(Arrays.asList(c1, c2, c3)); Customer customer = DB.find(Customer.class) .select("name") .fetch("address", "city") .where() .eq("city", "San Jose") .findOne(); DB.deleteAll(Arrays.asList(c1, c2, c3)); } private static Customer getCustomer() { Address a1 = new Address("1, Big Street", null, "New York"); Customer c1 = new Customer("Big John", a1); return c1; } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ebean\app\App.java
2
请在Spring Boot框架中完成以下Java代码
public HistoricTaskLogEntryBuilder data(String data) { this.data = data; return this; } @Override public HistoricTaskLogEntryBuilder processInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } @Override public HistoricTaskLogEntryBuilder processDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } @Override public HistoricTaskLogEntryBuilder executionId(String executionId) { this.executionId = executionId; return this; } @Override public HistoricTaskLogEntryBuilder scopeId(String scopeId) { this.scopeId = scopeId; return this; } @Override public HistoricTaskLogEntryBuilder scopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; return this; } @Override public HistoricTaskLogEntryBuilder subScopeId(String subScopeId) { this.subScopeId = subScopeId; return this; } @Override public HistoricTaskLogEntryBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public HistoricTaskLogEntryBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public String getType() { return type; } @Override public String getTaskId() { return taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public String getUserId() { return userId; } @Override public String getData() { return data; }
@Override public String getExecutionId() { return executionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() { return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public void create() { // add is not supported by default throw new RuntimeException("Operation is not supported"); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseHistoricTaskLogEntryBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Result<?> deleteDocumentAll(HttpServletRequest request, @RequestParam(name = "knowId") String knowId) { //update-begin---author:chenrui ---date:20250606 for:[issues/8337]关于ai工作列表的数据权限问题 #8337------------ //如果是saas隔离的情况下,判断当前租户id是否是当前租户下的 if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) { AiragKnowledge know = airagKnowledgeService.getById(knowId); //获取当前租户 String currentTenantId = TokenUtils.getTenantIdByRequest(request); if (null == know || !know.getTenantId().equals(currentTenantId)) { return Result.error("删除AI知识库失败,不能删除其他租户的AI知识库!"); } } //update-end---author:chenrui ---date:20250606 for:[issues/8337]关于ai工作列表的数据权限问题 #8337------------ return airagKnowledgeDocService.deleteAllByKnowId(knowId); } /** * 命中测试 * * @param knowId 知识库id * @param queryText 查询内容 * @param topNumber 最多返回条数 * @param similarity 最小分数 * @return * @author chenrui * @date 2025/2/18 17:09 */ @GetMapping(value = "/embedding/hitTest/{knowId}") public Result<?> hitTest(@PathVariable("knowId") String knowId, @RequestParam(name = "queryText") String queryText, @RequestParam(name = "topNumber") Integer topNumber, @RequestParam(name = "similarity") Double similarity) { List<Map<String, Object>> searchResp = embeddingHandler.searchEmbedding(knowId, queryText, topNumber, similarity); return Result.ok(searchResp); } /**
* 向量查询 * * @param knowIds 知识库ids * @param queryText 查询内容 * @param topNumber 最多返回条数 * @param similarity 最小分数 * @return * @author chenrui * @date 2025/2/18 17:09 */ @GetMapping(value = "/embedding/search") public Result<?> embeddingSearch(@RequestParam("knowIds") List<String> knowIds, @RequestParam(name = "queryText") String queryText, @RequestParam(name = "topNumber", required = false) Integer topNumber, @RequestParam(name = "similarity", required = false) Double similarity) { KnowledgeSearchResult searchResp = embeddingHandler.embeddingSearch(knowIds, queryText, topNumber, similarity); return Result.ok(searchResp); } /** * 通过ids批量查询知识库 * * @param ids * @return * @author chenrui * @date 2025/2/27 16:44 */ @GetMapping(value = "/query/batch/byId") public Result<?> queryBatchByIds(@RequestParam(name = "ids", required = true) String ids) { List<String> idList = Arrays.asList(ids.split(",")); List<AiragKnowledge> airagKnowledges = airagKnowledgeService.listByIds(idList); return Result.OK(airagKnowledges); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\controller\AiragKnowledgeController.java
2
请完成以下Java代码
public ITrxConstraints setActive(boolean active) { return this; } @Override public boolean isActive() { return false; } @Override public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes) { return this; } @Override public boolean isOnlyAllowedTrxNamePrefixes() { return false; } @Override public ITrxConstraints addAllowedTrxNamePrefix(String trxNamePrefix) { return this; } @Override public ITrxConstraints removeAllowedTrxNamePrefix(String trxNamePrefix) { return this; } @Override public Set<String> getAllowedTrxNamePrefixes() { return Collections.emptySet(); } @Override public ITrxConstraints setTrxTimeoutSecs(int secs, boolean logOnly) { return this; } @Override public int getTrxTimeoutSecs() { return 0; } @Override public boolean isTrxTimeoutLogOnly() { return false; } @Override public ITrxConstraints setMaxTrx(int max) { return this; } @Override public ITrxConstraints incMaxTrx(int num)
{ return this; } @Override public int getMaxTrx() { return 0; } @Override public int getMaxSavepoints() { return 0; } @Override public ITrxConstraints setMaxSavepoints(int maxSavePoints) { return this; } @Override public boolean isAllowTrxAfterThreadEnd() { return false; } @Override public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow) { return this; } @Override public void reset() { } @Override public String toString() { return "TrxConstraints have been globally disabled. Add or change AD_SysConfig " + TrxConstraintsBL.SYSCONFIG_TRX_CONSTRAINTS_DISABLED + " to enable them"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraintsDisabled.java
1
请完成以下Java代码
public void setAD_SchedulerLog_ID (int AD_SchedulerLog_ID) { if (AD_SchedulerLog_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_SchedulerLog_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_SchedulerLog_ID, Integer.valueOf(AD_SchedulerLog_ID)); } /** Get Ablauf-Protokoll. @return Result of the execution of the Scheduler */ @Override public int getAD_SchedulerLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_SchedulerLog_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Binärwert. @param BinaryData Binary Data */ @Override public void setBinaryData (byte[] BinaryData) { set_Value (COLUMNNAME_BinaryData, BinaryData); } /** Get Binärwert. @return Binary Data */ @Override public byte[] getBinaryData () { return (byte[])get_Value(COLUMNNAME_BinaryData); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Fehler. @param IsError An Error occured in the execution */ @Override public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return An Error occured in the execution */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null)
{ if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenz. @param Reference Reference for this record */ @Override public void setReference (java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Referenz. @return Reference for this record */ @Override public java.lang.String getReference () { return (java.lang.String)get_Value(COLUMNNAME_Reference); } /** Set Zusammenfassung. @param Summary Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Zusammenfassung. @return Textual summary of this request */ @Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); } /** Set Mitteilung. @param TextMsg Text Message */ @Override public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message */ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java
1
请完成以下Java代码
public ImmutableList<Object> getMultipleValues() { if (multipleValues != null) { return multipleValues; } else { throw new AdempiereException("Not a multiple values instance: " + this); } } @Nullable public Integer getSingleValueAsInteger(@Nullable final Integer defaultValue) { final Object value = getSingleValueAsObject(); if (value == null) { return defaultValue; } else if (value instanceof Number) { return ((Number)value).intValue(); } else { final String valueStr = StringUtils.trimBlankToNull(value.toString()); if (valueStr == null) { return defaultValue; } else { return Integer.parseInt(valueStr); } } } @Nullable public String getSingleValueAsString() { final Object value = getSingleValueAsObject(); return value != null ? value.toString() : null; } public Stream<IdsToFilter> streamSingleValues() { if (noValue) { return Stream.empty(); } else if (singleValue != null) { return Stream.of(this); } else { Objects.requireNonNull(multipleValues); return multipleValues.stream().map(IdsToFilter::ofSingleValue); } }
public ImmutableList<Object> toImmutableList() { if (noValue) { return ImmutableList.of(); } else if (singleValue != null) { return ImmutableList.of(singleValue); } else { Objects.requireNonNull(multipleValues); return multipleValues; } } public IdsToFilter mergeWith(@NonNull final IdsToFilter other) { if (other.isNoValue()) { return this; } else if (isNoValue()) { return other; } else { final ImmutableSet<Object> multipleValues = Stream.concat(toImmutableList().stream(), other.toImmutableList().stream()) .distinct() .collect(ImmutableSet.toImmutableSet()); return ofMultipleValues(multipleValues); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\IdsToFilter.java
1