instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class RewindableReader extends Reader { private static final SpinCoreLogger LOG = SpinLogger.CORE_LOGGER; protected PushbackReader wrappedReader; protected char[] buffer; protected int pos; protected boolean rewindable; public RewindableReader(Reader input, int size) { this.wrappedReader = new PushbackReader(input, size); this.buffer = new char[size]; this.pos = 0; this.rewindable = true; } public int read(char[] cbuf, int off, int len) throws IOException { int charactersRead = wrappedReader.read(cbuf, off, len); if (charactersRead > 0) { if (rewindable && pos + charactersRead > buffer.length) { rewindable = false; } if (pos < buffer.length) { int freeBufferSpace = buffer.length - pos; int insertableCharacters = Math.min(charactersRead, freeBufferSpace); System.arraycopy(cbuf, off, buffer, pos, insertableCharacters); pos += insertableCharacters; } } return charactersRead; } public int read() throws IOException { int nextCharacter = wrappedReader.read(); if (nextCharacter != -1) { if (pos < buffer.length) { buffer[pos] = (char) nextCharacter; pos++; } else if (rewindable && pos >= buffer.length) { rewindable = false; } } return nextCharacter; } public void close() throws IOException { wrappedReader.close(); } public synchronized void mark(int readlimit) throws IOException {
wrappedReader.mark(readlimit); } public boolean markSupported() { return wrappedReader.markSupported(); } public synchronized void reset() throws IOException { wrappedReader.reset(); } public long skip(long n) throws IOException { return wrappedReader.skip(n); } /** * Rewinds the reader such that the initial characters are returned when invoking read(). * * Throws an exception if more than the buffering limit has already been read. * @throws IOException */ public void rewind() throws IOException { if (!rewindable) { throw LOG.unableToRewindReader(); } wrappedReader.unread(buffer, 0, pos); pos = 0; } public int getRewindBufferSize() { return buffer.length; } /** * * @return the number of characters that can still be read and rewound. */ public int getCurrentRewindableCapacity() { return buffer.length - pos; } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\RewindableReader.java
1
请完成以下Java代码
public void setIsDepreciated (boolean IsDepreciated) { set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated)); } /** Get Depreciate. @return The asset will be depreciated */ public boolean isDepreciated () { Object oo = get_Value(COLUMNNAME_IsDepreciated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set One Asset Per UOM. @param IsOneAssetPerUOM Create one asset per UOM */ public void setIsOneAssetPerUOM (boolean IsOneAssetPerUOM) { set_Value (COLUMNNAME_IsOneAssetPerUOM, Boolean.valueOf(IsOneAssetPerUOM)); } /** Get One Asset Per UOM. @return Create one asset per UOM */ public boolean isOneAssetPerUOM () { Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Owned. @param IsOwned The asset is owned by the organization */ public void setIsOwned (boolean IsOwned) { set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned)); } /** Get Owned. @return The asset is owned by the organization */ public boolean isOwned () { Object oo = get_Value(COLUMNNAME_IsOwned); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Track Issues. @param IsTrackIssues Enable tracking issues for this asset */ public void setIsTrackIssues (boolean IsTrackIssues) { set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues)); } /** Get Track Issues. @return Enable tracking issues for this asset */ public boolean isTrackIssues () { Object oo = get_Value(COLUMNNAME_IsTrackIssues); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(NAME_KEY); } @Override public GatewayFilter apply(Config config) { // AbstractChangeRequestUriGatewayFilterFactory.apply() returns // OrderedGatewayFilter OrderedGatewayFilter gatewayFilter = (OrderedGatewayFilter) super.apply(config); return new OrderedGatewayFilter(gatewayFilter, gatewayFilter.getOrder()) { @Override public String toString() { String template = Objects.requireNonNull(config.getTemplate(), "template must not be null"); return filterToStringCreator(SetRequestUriGatewayFilterFactory.this).append("template", template) .toString(); } }; } String getUri(ServerWebExchange exchange, Config config) { String template = Objects.requireNonNull(config.getTemplate(), "template must not be null"); if (template.indexOf('{') == -1) { return template; } Map<String, String> variables = getUriTemplateVariables(exchange); return UriComponentsBuilder.fromUriString(template).build().expand(variables).toUriString(); } @Override protected Optional<URI> determineRequestUri(ServerWebExchange exchange, Config config) { try { String url = getUri(exchange, config); URI uri = URI.create(url); if (!uri.isAbsolute()) {
log.info("Request url is invalid: url={}, error=URI is not absolute", url); return Optional.ofNullable(null); } return Optional.of(uri); } catch (IllegalArgumentException e) { log.info("Request url is invalid : url={}, error={}", config.getTemplate(), e.getMessage()); return Optional.ofNullable(null); } } public static class Config { private @Nullable String template; public @Nullable String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetRequestUriGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public DataResponse<HistoryJobResponse> getHistoryJobs(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) { HistoryJobQuery query = managementService.createHistoryJobQuery(); if (allRequestParams.containsKey("id")) { query.jobId(allRequestParams.get("id")); } if (allRequestParams.containsKey("scopeType")) { query.jobId(allRequestParams.get("scopeType")); } if (allRequestParams.containsKey("withException")) { if (Boolean.parseBoolean(allRequestParams.get("withException"))) { query.withException(); } } if (allRequestParams.containsKey("exceptionMessage")) { query.exceptionMessage(allRequestParams.get("exceptionMessage")); } if (allRequestParams.containsKey("lockOwner")) { query.lockOwner(allRequestParams.get("lockOwner")); } if (allRequestParams.containsKey("locked")) { if (Boolean.parseBoolean(allRequestParams.get("locked"))) { query.locked(); } } if (allRequestParams.containsKey("unlocked")) { if (Boolean.parseBoolean(allRequestParams.get("unlocked"))) { query.unlocked(); } } if (allRequestParams.containsKey("tenantId")) { query.jobTenantId(allRequestParams.get("tenantId")); }
if (allRequestParams.containsKey("tenantIdLike")) { query.jobTenantIdLike(allRequestParams.get("tenantIdLike")); } if (allRequestParams.containsKey("withoutTenantId")) { if (Boolean.parseBoolean(allRequestParams.get("withoutTenantId"))) { query.jobWithoutTenantId(); } } if (restApiInterceptor != null) { restApiInterceptor.accessHistoryJobInfoWithQuery(query); } return paginateList(allRequestParams, query, "id", HistoryJobQueryProperties.PROPERTIES, restResponseFactory::createHistoryJobResponseList); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobCollectionResource.java
2
请在Spring Boot框架中完成以下Java代码
public FlowableEventDispatcher getEventDispatcher() { return configuration.getEventDispatcher(); } public JobManager getJobManager() { return configuration.getJobManager(); } public JobEntityManager getJobEntityManager() { return configuration.getJobEntityManager(); } public DeadLetterJobEntityManager getDeadLetterJobEntityManager() { return configuration.getDeadLetterJobEntityManager(); } public SuspendedJobEntityManager getSuspendedJobEntityManager() { return configuration.getSuspendedJobEntityManager(); }
public ExternalWorkerJobEntityManager getExternalWorkerJobEntityManager() { return configuration.getExternalWorkerJobEntityManager(); } public TimerJobEntityManager getTimerJobEntityManager() { return configuration.getTimerJobEntityManager(); } public HistoryJobEntityManager getHistoryJobEntityManager() { return configuration.getHistoryJobEntityManager(); } public CommandExecutor getCommandExecutor() { return configuration.getCommandExecutor(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\ServiceImpl.java
2
请完成以下Java代码
public Catalina startServer() throws Exception { URL staticUrl = getClass().getClassLoader().getResource("static"); if (staticUrl == null) { throw new IllegalStateException("Static directory not found in classpath"); } Path staticDir = Paths.get(staticUrl.toURI()); Path baseDir = Paths.get("target/tomcat-base").toAbsolutePath(); Files.createDirectories(baseDir); String config; try (InputStream serverXmlStream = getClass().getClassLoader().getResourceAsStream("server.xml")) { if (serverXmlStream == null) { throw new IllegalStateException("server.xml not found in classpath"); } config = new String(serverXmlStream.readAllBytes()) .replace("STATIC_DIR_PLACEHOLDER", staticDir.toString()); } Path configFile = baseDir.resolve("server.xml");
Files.writeString(configFile, config); System.setProperty("catalina.base", baseDir.toString()); System.setProperty("catalina.home", baseDir.toString()); Catalina catalina = new Catalina(); catalina.load(new String[]{"-config", configFile.toString()}); catalina.start(); System.out.println("\nTomcat started with multiple connectors!"); System.out.println("http://localhost:8081"); System.out.println("http://localhost:7081"); return catalina; } }
repos\tutorials-master\server-modules\apache-tomcat-2\src\main\java\com\baeldung\tomcat\AppServerXML.java
1
请完成以下Java代码
public java.sql.Timestamp getReminderDate() { return get_ValueAsTimestamp(COLUMNNAME_ReminderDate); } /** * Source AD_Reference_ID=541284 * Reference name: PO Sources */ public static final int SOURCE_AD_Reference_ID=541284; /** Material Disposition = MD */ public static final String SOURCE_MaterialDisposition = "MD"; /** Sales Order = SO */ public static final String SOURCE_SalesOrder = "SO"; /** API = API */ public static final String SOURCE_API = "API"; @Override public void setSource (final @Nullable String Source) { set_ValueNoCheck (COLUMNNAME_Source, Source); } @Override public String getSource() { return get_ValueAsString(COLUMNNAME_Source); } @Override public void setUserElementString1 (final @Nullable String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); } @Override public void setUserElementString3 (final @Nullable String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); } @Override public void setUserElementString5 (final @Nullable String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5);
} @Override public void setUserElementString6 (final @Nullable String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVendor_ID (final int Vendor_ID) { if (Vendor_ID < 1) set_Value (COLUMNNAME_Vendor_ID, null); else set_Value (COLUMNNAME_Vendor_ID, Vendor_ID); } @Override public int getVendor_ID() { return get_ValueAsInt(COLUMNNAME_Vendor_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isGlobalAcquireLockEnabled() { return globalAcquireLockEnabled; } public void setGlobalAcquireLockEnabled(boolean globalAcquireLockEnabled) { this.globalAcquireLockEnabled = globalAcquireLockEnabled; } public String getGlobalAcquireLockPrefix() { return globalAcquireLockPrefix; } public void setGlobalAcquireLockPrefix(String globalAcquireLockPrefix) { this.globalAcquireLockPrefix = globalAcquireLockPrefix; } public Duration getAsyncJobsGlobalLockWaitTime() { return asyncJobsGlobalLockWaitTime; } public void setAsyncJobsGlobalLockWaitTime(Duration asyncJobsGlobalLockWaitTime) { this.asyncJobsGlobalLockWaitTime = asyncJobsGlobalLockWaitTime; } public Duration getAsyncJobsGlobalLockPollRate() { return asyncJobsGlobalLockPollRate; } public void setAsyncJobsGlobalLockPollRate(Duration asyncJobsGlobalLockPollRate) { this.asyncJobsGlobalLockPollRate = asyncJobsGlobalLockPollRate; } public Duration getAsyncJobsGlobalLockForceAcquireAfter() { return asyncJobsGlobalLockForceAcquireAfter; } public void setAsyncJobsGlobalLockForceAcquireAfter(Duration asyncJobsGlobalLockForceAcquireAfter) { this.asyncJobsGlobalLockForceAcquireAfter = asyncJobsGlobalLockForceAcquireAfter; } public Duration getTimerLockWaitTime() { return timerLockWaitTime; } public void setTimerLockWaitTime(Duration timerLockWaitTime) { this.timerLockWaitTime = timerLockWaitTime; } public Duration getTimerLockPollRate() { return timerLockPollRate; } public void setTimerLockPollRate(Duration timerLockPollRate) { this.timerLockPollRate = timerLockPollRate; }
public Duration getTimerLockForceAcquireAfter() { return timerLockForceAcquireAfter; } public void setTimerLockForceAcquireAfter(Duration timerLockForceAcquireAfter) { this.timerLockForceAcquireAfter = timerLockForceAcquireAfter; } public Duration getResetExpiredJobsInterval() { return resetExpiredJobsInterval; } public void setResetExpiredJobsInterval(Duration resetExpiredJobsInterval) { this.resetExpiredJobsInterval = resetExpiredJobsInterval; } public int getResetExpiredJobsPageSize() { return resetExpiredJobsPageSize; } public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { this.resetExpiredJobsPageSize = resetExpiredJobsPageSize; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobExecutorConfiguration.java
2
请完成以下Java代码
public List<GarbageCollectorInfo> getGarbageCollectors() { return this.garbageCollectors; } public static class MemoryUsageInfo { private final MemoryUsage memoryUsage; MemoryUsageInfo(MemoryUsage memoryUsage) { this.memoryUsage = memoryUsage; } public long getInit() { return this.memoryUsage.getInit(); } public long getUsed() { return this.memoryUsage.getUsed(); } public long getCommitted() { return this.memoryUsage.getCommitted(); } public long getMax() { return this.memoryUsage.getMax(); } }
/** * Garbage collection information. * * @since 3.5.0 */ public static class GarbageCollectorInfo { private final String name; private final long collectionCount; GarbageCollectorInfo(GarbageCollectorMXBean garbageCollectorMXBean) { this.name = garbageCollectorMXBean.getName(); this.collectionCount = garbageCollectorMXBean.getCollectionCount(); } public String getName() { return this.name; } public long getCollectionCount() { return this.collectionCount; } } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\ProcessInfo.java
1
请完成以下Java代码
protected ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) { ComponentDescription paComponentDescription = ProcessApplicationAttachments.getProcessApplicationComponent(deploymentUnit); return paComponentDescription; } @SuppressWarnings("unchecked") protected ProcessEngine getProcessEngineForArchive(ServiceName serviceName, ServiceRegistry serviceRegistry) { ServiceController<ProcessEngine> processEngineServiceController = (ServiceController<ProcessEngine>) serviceRegistry.getRequiredService(serviceName); return processEngineServiceController.getValue(); } protected ServiceName getProcessEngineServiceName(ProcessArchiveXml processArchive) { ServiceName serviceName = null; if(processArchive.getProcessEngineName() == null || processArchive.getProcessEngineName().length() == 0) { serviceName = ServiceNames.forDefaultProcessEngine(); } else { serviceName = ServiceNames.forManagedProcessEngine(processArchive.getProcessEngineName()); } return serviceName; } protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) { final Module module = deploymentUnit.getAttachment(MODULE); Map<String, byte[]> resources = new HashMap<String, byte[]>(); // first, add all resources listed in the processe.xml List<String> process = processArchive.getProcessResourceNames(); ModuleClassLoader classLoader = module.getClassLoader(); for (String resource : process) { InputStream inputStream = null; try { inputStream = classLoader.getResourceAsStream(resource); resources.put(resource, IoUtil.readInputStream(inputStream, resource)); } finally { IoUtil.closeSilently(inputStream); } }
// scan for process definitions if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) { //always use VFS scanner on JBoss final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner(); String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH); String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR); URL processesXmlUrl = vfsFileAsUrl(processesXmlFile); resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes)); } return resources; } protected URL vfsFileAsUrl(VirtualFile processesXmlFile) { try { return processesXmlFile.toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ProcessApplicationDeploymentProcessor.java
1
请完成以下Java代码
public class ComparePerformance { String strInitial = "springframework"; String strFinal = ""; String replacement = "java-"; @Benchmark public String benchmarkStringConcatenation() { strFinal = ""; strFinal += strInitial; return strFinal; } @Benchmark public StringBuffer benchmarkStringBufferConcatenation() { StringBuffer stringBuffer = new StringBuffer(strFinal); stringBuffer.append(strInitial); return stringBuffer; } @Benchmark public String benchmarkStringReplacement() {
strFinal = strInitial.replaceFirst("spring", replacement); return strFinal; } @Benchmark public StringBuffer benchmarkStringBufferReplacement() { StringBuffer stringBuffer = new StringBuffer(strInitial); stringBuffer.replace(0,6, replacement); return stringBuffer; } public static void main(String[] args) throws RunnerException { Options options = new OptionsBuilder() .include(ComparePerformance.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-strings\src\main\java\com\baeldung\stringbuffer\ComparePerformance.java
1
请完成以下Java代码
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return processEngineConfiguration.getEventSubscriptionEntityManager(); } public HistoryManager getHistoryManager() { return processEngineConfiguration.getHistoryManager(); } public JobManager getJobManager() { return processEngineConfiguration.getJobManager(); } // Involved executions //////////////////////////////////////////////////////// public void addInvolvedExecution(ExecutionEntity executionEntity) { if (executionEntity.getId() != null) { involvedExecutions.put(executionEntity.getId(), executionEntity); } } public boolean hasInvolvedExecutions() { return involvedExecutions.size() > 0; } public Collection<ExecutionEntity> getInvolvedExecutions() { return involvedExecutions.values(); } // getters and setters // ////////////////////////////////////////////////////// public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; }
public ActivitiEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } public ActivitiEngineAgenda getAgenda() { return agenda; } public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public boolean isReused() { return reused; } public void setReused(boolean reused) { this.reused = reused; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
protected boolean shouldFetchValue(HistoricDetailVariableInstanceUpdateEntity entity) { // do not fetch values for byte arrays eagerly (unless requested by the user) return isByteArrayFetchingEnabled || !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entity.getSerializer().getType().getName()); } // order by ///////////////////////////////////////////////////////////////// public HistoricDetailQuery orderByProcessInstanceId() { orderBy(HistoricDetailQueryProperty.PROCESS_INSTANCE_ID); return this; } public HistoricDetailQuery orderByTime() { orderBy(HistoricDetailQueryProperty.TIME); return this; } public HistoricDetailQuery orderByVariableName() { orderBy(HistoricDetailQueryProperty.VARIABLE_NAME); return this; } public HistoricDetailQuery orderByFormPropertyId() { orderBy(HistoricDetailQueryProperty.VARIABLE_NAME); return this; } public HistoricDetailQuery orderByVariableRevision() { orderBy(HistoricDetailQueryProperty.VARIABLE_REVISION); return this; } public HistoricDetailQuery orderByVariableType() { orderBy(HistoricDetailQueryProperty.VARIABLE_TYPE); return this; } public HistoricDetailQuery orderPartiallyByOccurrence() { orderBy(HistoricDetailQueryProperty.SEQUENCE_COUNTER); return this; } public HistoricDetailQuery orderByTenantId() { return orderBy(HistoricDetailQueryProperty.TENANT_ID); } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public String getExecutionId() { return executionId; } public String getCaseExecutionId() { return caseExecutionId; } public String getTaskId() { return taskId; } public String getActivityId() { return activityId;
} public String getType() { return type; } public boolean getExcludeTaskRelated() { return excludeTaskRelated; } public String getDetailId() { return detailId; } public String[] getProcessInstanceIds() { return processInstanceIds; } public Date getOccurredBefore() { return occurredBefore; } public Date getOccurredAfter() { return occurredAfter; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isInitial() { return initial; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class AdImageRepository { private final CCache<AdImageId, AdImage> cache = CCache.<AdImageId, AdImage>builder() .cacheMapType(CCache.CacheMapType.LRU) .initialCapacity(1000) .tableName(I_AD_Image.Table_Name) .build(); public AdImage getById(@NonNull final AdImageId adImageId) { return cache.getOrLoad(adImageId, this::retrieveById); } private AdImage retrieveById(@NonNull final AdImageId adImageId) { final I_AD_Image record = InterfaceWrapperHelper.load(adImageId, I_AD_Image.class); if (record == null) { throw new AdempiereException("No AD_Image found for " + adImageId); }
return fromRecord(record); } public static AdImage fromRecord(@NonNull I_AD_Image record) { final String filename = record.getName(); return AdImage.builder() .id(AdImageId.ofRepoId(record.getAD_Image_ID())) .lastModified(record.getUpdated().toInstant()) .filename(filename) .contentType(MimeType.getMimeType(filename)) .data(record.getBinaryData()) .clientAndOrgId(ClientAndOrgId.ofClientAndOrg(record.getAD_Client_ID(), record.getAD_Org_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\image\AdImageRepository.java
2
请完成以下Java代码
default Predicate<ServerWebExchange> apply(Consumer<C> consumer) { C config = newConfig(); consumer.accept(config); beforeApply(config); return apply(config); } default AsyncPredicate<ServerWebExchange> applyAsync(Consumer<C> consumer) { C config = newConfig(); consumer.accept(config); beforeApply(config); return applyAsync(config); } default Class<C> getConfigClass() { throw new UnsupportedOperationException("getConfigClass() not implemented"); }
@Override default C newConfig() { throw new UnsupportedOperationException("newConfig() not implemented"); } default void beforeApply(C config) { } Predicate<ServerWebExchange> apply(C config); default AsyncPredicate<ServerWebExchange> applyAsync(C config) { return toAsyncPredicate(apply(config)); } default String name() { return NameUtils.normalizeRoutePredicateName(getClass()); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\RoutePredicateFactory.java
1
请完成以下Java代码
public class WordNatureWeightModelMaker { public static boolean makeModel(String corpusLoadPath, String modelSavePath) { Set<String> posSet = new TreeSet<String>(); DictionaryMaker dictionaryMaker = new DictionaryMaker(); for (CoNLLSentence sentence : CoNLLLoader.loadSentenceList(corpusLoadPath)) { for (CoNLLWord word : sentence.word) { addPair(word.NAME, word.HEAD.NAME, word.DEPREL, dictionaryMaker); addPair(word.NAME, wrapTag(word.HEAD.POSTAG ), word.DEPREL, dictionaryMaker); addPair(wrapTag(word.POSTAG), word.HEAD.NAME, word.DEPREL, dictionaryMaker); addPair(wrapTag(word.POSTAG), wrapTag(word.HEAD.POSTAG), word.DEPREL, dictionaryMaker); posSet.add(word.POSTAG); } } for (CoNLLSentence sentence : CoNLLLoader.loadSentenceList(corpusLoadPath)) { for (CoNLLWord word : sentence.word) { addPair(word.NAME, word.HEAD.NAME, word.DEPREL, dictionaryMaker); addPair(word.NAME, wrapTag(word.HEAD.POSTAG ), word.DEPREL, dictionaryMaker); addPair(wrapTag(word.POSTAG), word.HEAD.NAME, word.DEPREL, dictionaryMaker); addPair(wrapTag(word.POSTAG), wrapTag(word.HEAD.POSTAG), word.DEPREL, dictionaryMaker); posSet.add(word.POSTAG); } } StringBuilder sb = new StringBuilder(); for (String pos : posSet) { sb.append("case \"" + pos + "\":\n"); }
IOUtil.saveTxt("data/model/dependency/pos-thu.txt", sb.toString()); return dictionaryMaker.saveTxtTo(modelSavePath); } private static void addPair(String from, String to, String label, DictionaryMaker dictionaryMaker) { dictionaryMaker.add(new Word(from + "@" + to, label)); dictionaryMaker.add(new Word(from + "@", "频次")); } /** * 用尖括号将标签包起来 * @param tag * @return */ public static String wrapTag(String tag) { return "<" + tag + ">"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\model\WordNatureWeightModelMaker.java
1
请完成以下Java代码
protected DbOperation performBatchCleanup() { return Context .getCommandContext() .getHistoricBatchManager() .deleteHistoricBatchesByRemovalTime(ClockUtil.getCurrentTime(), configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize()); } protected DbOperation performTaskMetricsCleanup() { return Context .getCommandContext() .getMeterLogManager() .deleteTaskMetricsByRemovalTime(ClockUtil.getCurrentTime(), getTaskMetricsTimeToLive(), configuration.getMinuteFrom(), configuration.getMinuteTo(), getBatchSize()); } protected Map<String, Long> reportMetrics() { Map<String, Long> reports = new HashMap<>(); DbOperation deleteOperationProcessInstance = deleteOperations.get(HistoricProcessInstanceEntity.class); if (deleteOperationProcessInstance != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_PROCESS_INSTANCES, (long) deleteOperationProcessInstance.getRowsAffected()); } DbOperation deleteOperationDecisionInstance = deleteOperations.get(HistoricDecisionInstanceEntity.class); if (deleteOperationDecisionInstance != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_DECISION_INSTANCES, (long) deleteOperationDecisionInstance.getRowsAffected()); } DbOperation deleteOperationBatch = deleteOperations.get(HistoricBatchEntity.class); if (deleteOperationBatch != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_BATCH_OPERATIONS, (long) deleteOperationBatch.getRowsAffected()); } DbOperation deleteOperationTaskMetric = deleteOperations.get(TaskMeterLogEntity.class); if (deleteOperationTaskMetric != null) { reports.put(Metrics.HISTORY_CLEANUP_REMOVED_TASK_METRICS, (long) deleteOperationTaskMetric.getRowsAffected()); } return reports; } protected boolean isDmnEnabled() {
return Context .getProcessEngineConfiguration() .isDmnEnabled(); } protected Integer getTaskMetricsTimeToLive() { return Context .getProcessEngineConfiguration() .getParsedTaskMetricsTimeToLive(); } protected boolean shouldRescheduleNow() { int batchSize = getBatchSize(); for (DbOperation deleteOperation : deleteOperations.values()) { if (deleteOperation.getRowsAffected() == batchSize) { return true; } } return false; } public int getBatchSize() { return Context .getProcessEngineConfiguration() .getHistoryCleanupBatchSize(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupRemovalTime.java
1
请在Spring Boot框架中完成以下Java代码
public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/"); } // @Bean // public FilterRegistrationBean xssFilterRegistration() { // FilterRegistrationBean registration = new FilterRegistrationBean(); // registration.setDispatcherTypes(DispatcherType.REQUEST); // registration.setFilter(new XssFilter()); // registration.addUrlPatterns("/*"); // registration.setName("xssFilter"); // registration.setOrder(Integer.MAX_VALUE); // return registration; // } // @Override // public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // converters.clear(); // //FastJsonHttpMessageConverter // FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // List<MediaType> fastMediaTypes = new ArrayList<>(); // fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); // fastConverter.setSupportedMediaTypes(fastMediaTypes); // FastJsonConfig fastJsonConfig = new FastJsonConfig(); // fastJsonConfig.setCharset(StandardCharsets.UTF_8); // fastConverter.setFastJsonConfig(fastJsonConfig); // //StringHttpMessageConverter // StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); // stringConverter.setDefaultCharset(StandardCharsets.UTF_8); // stringConverter.setSupportedMediaTypes(fastMediaTypes); // converters.add(stringConverter); // converters.add(fastConverter); // } /** * FASTJSON2升级 by https://zhengkai.blog.csdn.net/ * https://blog.csdn.net/moshowgame/article/details/138013669 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//自定义配置... FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd HH:mm:ss"); // 添加更多解析特性以提高容错性 config.setReaderFeatures( JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean, // JSONReader.Feature.IgnoreNoneFieldGetter, JSONReader.Feature.InitStringFieldAsEmpty ); config.setWriterFeatures( JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat ); converter.setFastJsonConfig(config); converter.setDefaultCharset(StandardCharsets.UTF_8); converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON)); converters.add(0, converter); } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\config\WebMvcConfig.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (!Objects.equals(context.getTableName(), I_Carrier_ShipmentOrder_Parcel.Table_Name)) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final DeliveryOrderParcelId parcelId = DeliveryOrderParcelId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (parcelId == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No parcel selected"); } final DeliveryOrderParcel parcel = orderRepository.getParcelById(parcelId); if (parcel == null || parcel.getLabelPdfBase64() == null) { return ProcessPreconditionsResolution.rejectWithInternalReason("No label available"); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() { final DeliveryOrderParcelId parcelId = DeliveryOrderParcelId.ofRepoIdOrNull(getRecord_ID()); if (parcelId == null) { return MSG_OK; } final DeliveryOrderParcel parcel = orderRepository.getParcelById(parcelId); if (parcel == null || parcel.getLabelPdfBase64() == null) { return MSG_OK; } getResult().setReportData(new ByteArrayResource(parcel.getLabelPdfBase64()), "Awb_" + parcel.getAwb(), MimeType.TYPE_PDF); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\Carrier_ShipmentOrder_Parcel_Label_Download.java
1
请完成以下Java代码
private float getTabPos (float xPos, float length) { float retValue = xPos + length; int iLength = (int)Math.ceil(length); int tabSpace = iLength % 30; retValue += (30 - tabSpace); return retValue; } // getTabPos /** * String Representation * @return info */ @Override public String toString() { StringBuffer sb = new StringBuffer("StringElement["); sb.append("Bounds=").append(getBounds()) .append(",Height=").append(p_height).append("(").append(p_maxHeight)
.append("),Width=").append(p_width).append("(").append(p_maxHeight) .append("),PageLocation=").append(p_pageLocation).append(" - "); for (int i = 0; i < m_string_paper.length; i++) { if (m_string_paper.length > 1) sb.append(Env.NL).append(i).append(":"); AttributedCharacterIterator iter = m_string_paper[i].getIterator(); for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) sb.append(c); } if (m_ID != null) sb.append(",ID=(").append(m_ID.toStringX()).append(")"); sb.append("]"); return sb.toString(); } // toString } // StringElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\StringElement.java
1
请完成以下Java代码
public class SaveService { /** 设置集合名称 */ private static final String COLLECTION_NAME = "users"; @Resource private MongoTemplate mongoTemplate; /** * 存储【一条】用户信息,如果文档信息已经【存在就执行更新】 * * @return 存储的文档信息 */ public Object save() { // 设置用户信息 User user = new User() .setId("13")
.setAge(22) .setSex("男") .setRemake("无") .setSalary(2800) .setName("kuiba") .setBirthday(new Date()) .setStatus(new Status().setHeight(169).setWeight(150)); // 存储用户信息,如果文档信息已经存在就执行更新 User newUser = mongoTemplate.save(user, COLLECTION_NAME); // 输出存储结果 log.info("存储的用户信息为:{}", newUser); return newUser; } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\SaveService.java
1
请在Spring Boot框架中完成以下Java代码
public class RatingService { @Autowired private RatingRepository ratingRepository; @Autowired private RatingCacheRepository cacheRepository; @CircuitBreaker(name = "ratingsByBookIdFromDB", fallbackMethod = "findCachedRatingsByBookId") public List<Rating> findRatingsByBookId(Long bookId) { return ratingRepository.findRatingsByBookId(bookId); } public List<Rating> findCachedRatingsByBookId(Long bookId, Exception exception) { return cacheRepository.findCachedRatingsByBookId(bookId); } @CircuitBreaker(name = "ratingsFromDB", fallbackMethod = "findAllCachedRatings") 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
2
请完成以下Java代码
public static Map<String, String> byBufferedReader(String filePath, DupKeyOption dupKeyOption) { HashMap<String, String> map = new HashMap<>(); String line; try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { while ((line = reader.readLine()) != null) { String[] keyValuePair = line.split(":", 2); if (keyValuePair.length > 1) { String key = keyValuePair[0]; String value = keyValuePair[1]; if (DupKeyOption.OVERWRITE == dupKeyOption) { map.put(key, value); } else if (DupKeyOption.DISCARD == dupKeyOption) { map.putIfAbsent(key, value); } } else { System.out.println("No Key:Value found in line, ignoring: " + line); } } } catch (IOException e) { e.printStackTrace(); } return map; } public static Map<String, String> byStream(String filePath, DupKeyOption dupKeyOption) { Map<String, String> map = new HashMap<>(); try (Stream<String> lines = Files.lines(Paths.get(filePath))) { lines.filter(line -> line.contains(":")) .forEach(line -> { String[] keyValuePair = line.split(":", 2); String key = keyValuePair[0]; String value = keyValuePair[1]; if (DupKeyOption.OVERWRITE == dupKeyOption) { map.put(key, value); } else if (DupKeyOption.DISCARD == dupKeyOption) { map.putIfAbsent(key, value); } }); } catch (IOException e) { e.printStackTrace(); } return map; }
public static Map<String, List<String>> aggregateByKeys(String filePath) { Map<String, List<String>> map = new HashMap<>(); try (Stream<String> lines = Files.lines(Paths.get(filePath))) { lines.filter(line -> line.contains(":")) .forEach(line -> { String[] keyValuePair = line.split(":", 2); String key = keyValuePair[0]; String value = keyValuePair[1]; if (map.containsKey(key)) { map.get(key).add(value); } else { map.put(key, Stream.of(value).collect(Collectors.toList())); } }); } catch (IOException e) { e.printStackTrace(); } return map; } }
repos\tutorials-master\core-java-modules\core-java-io-4\src\main\java\com\baeldung\filetomap\FileToHashMap.java
1
请在Spring Boot框架中完成以下Java代码
public static ProcessEnginePlugin spinProcessEnginePlugin() { return new SpringBootSpinProcessEnginePlugin(); } } @ConditionalOnClass(ConnectProcessEnginePlugin.class) @Configuration static class ConnectConfiguration { @Bean @ConditionalOnMissingBean(name = "connectProcessEnginePlugin") public static ProcessEnginePlugin connectProcessEnginePlugin() { return new ConnectProcessEnginePlugin(); } } /* Provide option to apply application context classloader switch when Spring Spring Developer tools are enabled
For more details: https://jira.camunda.com/browse/CAM-9043 */ @ConditionalOnInitializedRestarter @Configuration static class InitializedRestarterConfiguration { @Bean @ConditionalOnMissingBean(name = "applicationContextClassloaderSwitchPlugin") public ApplicationContextClassloaderSwitchPlugin applicationContextClassloaderSwitchPlugin() { return new ApplicationContextClassloaderSwitchPlugin(); } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmPluginConfiguration.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_CM_Template_Ad_Cat[") .append(get_ID()).append("]"); return sb.toString(); } public I_CM_Ad_Cat getCM_Ad_Cat() throws RuntimeException { return (I_CM_Ad_Cat)MTable.get(getCtx(), I_CM_Ad_Cat.Table_Name) .getPO(getCM_Ad_Cat_ID(), get_TrxName()); } /** Set Advertisement Category. @param CM_Ad_Cat_ID Advertisement Category like Banner Homepage */ public void setCM_Ad_Cat_ID (int CM_Ad_Cat_ID) { if (CM_Ad_Cat_ID < 1) set_Value (COLUMNNAME_CM_Ad_Cat_ID, null); else set_Value (COLUMNNAME_CM_Ad_Cat_ID, Integer.valueOf(CM_Ad_Cat_ID)); } /** Get Advertisement Category. @return Advertisement Category like Banner Homepage */ public int getCM_Ad_Cat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Ad_Cat_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Template getCM_Template() throws RuntimeException { return (I_CM_Template)MTable.get(getCtx(), I_CM_Template.Table_Name) .getPO(getCM_Template_ID(), get_TrxName()); } /** Set Template. @param CM_Template_ID Template defines how content is displayed */ public void setCM_Template_ID (int CM_Template_ID) { if (CM_Template_ID < 1) set_Value (COLUMNNAME_CM_Template_ID, null); else set_Value (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID)); } /** Get Template. @return Template defines how content is displayed */ public int getCM_Template_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); }
/** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template_Ad_Cat.java
1
请完成以下Java代码
public String getDescription() { return description; } @Override public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public int getVersion() { return version; } @Override public void setVersion(int version) { this.version = version; } @Override public String getResourceName() { return resourceName; } @Override public void setResourceName(String resourceName) { this.resourceName = resourceName; } @Override public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public boolean isGraphicalNotationDefined() { return hasGraphicalNotation(); } @Override public void setHasGraphicalNotation(boolean hasGraphicalNotation) { this.isGraphicalNotationDefined = hasGraphicalNotation; } @Override public String getDiagramResourceName() { return diagramResourceName; } @Override
public void setDiagramResourceName(String diagramResourceName) { this.diagramResourceName = diagramResourceName; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getDecisionType() { return decisionType; } @Override public void setDecisionType(String decisionType) { this.decisionType = decisionType; } @Override public String toString() { return "DecisionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DecisionEntityImpl.java
1
请完成以下Java代码
public boolean isLookup() { return gridField.isLookup(); } public Lookup getLookup() { return gridField.getLookup(); } public boolean isVirtualColumn() { return gridField.isVirtualColumn(); } /** * Creates the editor component * * @param tableEditor true if table editor * @return editor or null if editor could not be created */ public VEditor createEditor(final boolean tableEditor) { // Reset lookup state // background: the lookup implements MutableComboBoxModel which stores the selected item. // If this lookup was previously used somewhere, the selected item is retained from there and we will get unexpected results. final Lookup lookup = gridField.getLookup(); if (lookup != null) { lookup.setSelectedItem(null); } // // Create a new editor VEditor editor = swingEditorFactory.getEditor(gridField, tableEditor); if (editor == null && tableEditor) { editor = new VString(); } // // Configure the new editor if (editor != null) { editor.setMandatory(false); editor.setReadWrite(true); } return editor; } public CLabel createEditorLabel() { return swingEditorFactory.getLabel(gridField); } @Override public Object convertValueToFieldType(final Object valueObj) { return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName()); } @Override
public String getValueDisplay(final Object value) { String infoDisplay = value == null ? "" : value.toString(); if (isLookup()) { final Lookup lookup = getLookup(); if (lookup != null) { infoDisplay = lookup.getDisplay(value); } } else if (getDisplayType() == DisplayType.YesNo) { final IMsgBL msgBL = Services.get(IMsgBL.class); infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay); } return infoDisplay; } @Override public boolean matchesColumnName(final String columnName) { if (columnName == null || columnName.isEmpty()) { return false; } if (columnName.equals(getColumnName())) { return true; } if (gridField.isVirtualColumn()) { if (columnName.equals(gridField.getColumnSQL(false))) { return true; } if (columnName.equals(gridField.getColumnSQL(true))) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
1
请完成以下Java代码
public static DDOrderUserNotificationProducer newInstance() { return new DDOrderUserNotificationProducer(); } public DDOrderUserNotificationProducer notifyGenerated(final Collection<? extends I_DD_Order> orders) { if (orders == null || orders.isEmpty()) { return this; } postNotifications(orders.stream() .map(this::createUserNotification) .collect(ImmutableList.toImmutableList())); return this; } public final DDOrderUserNotificationProducer notifyGenerated(@NonNull final I_DD_Order order) { notifyGenerated(ImmutableList.of(order)); return this; } private UserNotificationRequest createUserNotification(@NonNull final I_DD_Order order) { final UserId recipientUserId = getNotificationRecipientUserId(order); final TableRecordReference orderRef = TableRecordReference.of(order); return newUserNotificationRequest() .recipientUserId(recipientUserId) .contentADMessage(MSG_Event_DDOrderGenerated)
.contentADMessageParam(orderRef) .targetAction(UserNotificationRequest.TargetRecordAction.of(orderRef)) .build(); } private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC); } private UserId getNotificationRecipientUserId(final I_DD_Order order) { return UserId.ofRepoId(order.getCreatedBy()); } private void postNotifications(final List<UserNotificationRequest> notifications) { notificationBL.sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\event\DDOrderUserNotificationProducer.java
1
请在Spring Boot框架中完成以下Java代码
public TaskService getTaskService() { return processEngine.getTaskService(); } @Bean(name = "historyService") @Override public HistoryService getHistoryService() { return processEngine.getHistoryService(); } @Bean(name = "identityService") @Override public IdentityService getIdentityService() { return processEngine.getIdentityService(); } @Bean(name = "managementService") @Override public ManagementService getManagementService() { return processEngine.getManagementService(); } @Bean(name = "authorizationService") @Override public AuthorizationService getAuthorizationService() { return processEngine.getAuthorizationService(); } @Bean(name = "caseService") @Override public CaseService getCaseService() {
return processEngine.getCaseService(); } @Bean(name = "filterService") @Override public FilterService getFilterService() { return processEngine.getFilterService(); } @Bean(name = "externalTaskService") @Override public ExternalTaskService getExternalTaskService() { return processEngine.getExternalTaskService(); } @Bean(name = "decisionService") @Override public DecisionService getDecisionService() { return processEngine.getDecisionService(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringProcessEngineServicesConfiguration.java
2
请完成以下Java代码
public String getName() { return name; } public QueryOperator getOperator() { if(operator != null) { return operator; } return QueryOperator.EQUALS; } public String getOperatorName() { return getOperator().toString(); } public Object getValue() { return value.getValue(); } public TypedValue getTypedValue() { return value; } public boolean isLocal() { return local; } public boolean isVariableNameIgnoreCase() { return variableNameIgnoreCase; }
public void setVariableNameIgnoreCase(boolean variableNameIgnoreCase) { this.variableNameIgnoreCase = variableNameIgnoreCase; } public boolean isVariableValueIgnoreCase() { return variableValueIgnoreCase; } public void setVariableValueIgnoreCase(boolean variableValueIgnoreCase) { this.variableValueIgnoreCase = variableValueIgnoreCase; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryVariableValue that = (QueryVariableValue) o; return local == that.local && variableNameIgnoreCase == that.variableNameIgnoreCase && variableValueIgnoreCase == that.variableValueIgnoreCase && name.equals(that.name) && value.equals(that.value) && operator == that.operator && Objects.equals(valueCondition, that.valueCondition); } @Override public int hashCode() { return Objects.hash(name, value, operator, local, valueCondition, variableNameIgnoreCase, variableValueIgnoreCase); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryVariableValue.java
1
请在Spring Boot框架中完成以下Java代码
public static class JsonHUIdentifier { @Nullable @JsonProperty("metasfreshId") JsonMetasfreshId metasfreshId; @Nullable @JsonProperty("qrCode") String qrCode; @Builder public JsonHUIdentifier( @JsonProperty("metasfreshId") @Nullable final JsonMetasfreshId metasfreshId, @JsonProperty("qrCode") @Nullable final String qrCode) {
Check.assume(qrCode == null || metasfreshId == null, "metasfreshId and qrCode cannot be set at the same time!"); Check.assume(qrCode != null || metasfreshId != null, "metasfreshId or qrCode must be set!"); this.metasfreshId = metasfreshId; this.qrCode = qrCode; } @NonNull public static JsonHUIdentifier ofJsonMetasfreshId(@NonNull final JsonMetasfreshId metasfreshId) { return JsonHUIdentifier.builder() .metasfreshId(metasfreshId) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonSetClearanceStatusRequest.java
2
请完成以下Java代码
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier) { return getHelperThatCanHandle(model).computeDynAttributeIfAbsent(model, attributeName, supplier); } @Override public <T extends PO> T getPO(final Object model, final boolean strict) { if (model == null) { return null; } // Short-circuit: model is already a PO instance if (model instanceof PO) { @SuppressWarnings("unchecked") final T po = (T)model; return po; } return getHelperThatCanHandle(model) .getPO(model, strict); } @Override public Evaluatee getEvaluatee(final Object model) { if (model == null) { return null; } else if (model instanceof Evaluatee) { final Evaluatee evaluatee = (Evaluatee)model;
return evaluatee; } return getHelperThatCanHandle(model) .getEvaluatee(model); } @Override public boolean isCopy(@NonNull final Object model) { return getHelperThatCanHandle(model).isCopy(model); } @Override public boolean isCopying(@NonNull final Object model) { return getHelperThatCanHandle(model).isCopying(model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\CompositeInterfaceWrapperHelper.java
1
请在Spring Boot框架中完成以下Java代码
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) srequest; String uri = request.getRequestURI(); sresponse.setCharacterEncoding("UTF-8");//设置响应编码格式 sresponse.setContentType("text/html;charset=UTF-8");//设置响应编码格式 if (uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".jpg") || uri.endsWith(".gif") || uri.endsWith(".png") || uri.endsWith(".ico")) { log.debug("security filter, pass, " + request.getRequestURI()); filterChain.doFilter(srequest, sresponse); return; } System.out.println("request uri is : "+uri); //不处理指定的action, jsp if (GreenUrlSet.contains(uri) || uri.contains("/verified/")) { log.debug("security filter, pass, " + request.getRequestURI()); filterChain.doFilter(srequest, sresponse); return; } String id=(String)request.getSession().getAttribute(WebConfiguration.LOGIN_KEY); if(StringUtils.isBlank(id)){ String html = "<script type=\"text/javascript\">window.location.href=\"/toLogin\"</script>"; sresponse.getWriter().write(html); }else { filterChain.doFilter(srequest, sresponse); } }
public void destroy() { } @Override public void init(FilterConfig filterconfig) throws ServletException { GreenUrlSet.add("/toRegister"); GreenUrlSet.add("/toLogin"); GreenUrlSet.add("/login"); GreenUrlSet.add("/loginOut"); GreenUrlSet.add("/register"); GreenUrlSet.add("/verified"); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\config\SessionFilter.java
2
请完成以下Java代码
public class SetExecutionVariablesCmd extends NeedsActiveExecutionCmd<Object> { private static final long serialVersionUID = 1L; protected Map<String, ? extends Object> variables; protected boolean isLocal; public SetExecutionVariablesCmd(String executionId, Map<String, ? extends Object> variables, boolean isLocal) { super(executionId); this.variables = variables; this.isLocal = isLocal; } protected Object execute(CommandContext commandContext, ExecutionEntity execution) { if (isLocal) { if (variables != null) { for (String variableName : variables.keySet()) { execution.setVariableLocal(variableName, variables.get(variableName), false); } } } else { if (variables != null) { for (String variableName : variables.keySet()) { execution.setVariable(variableName, variables.get(variableName), false);
} } } // ACT-1887: Force an update of the execution's revision to prevent // simultaneous inserts of the same // variable. If not, duplicate variables may occur since optimistic // locking doesn't work on inserts execution.forceUpdate(); return null; } @Override protected String getSuspendedExceptionMessage() { return "Cannot set variables because execution '" + executionId + "' is suspended"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetExecutionVariablesCmd.java
1
请完成以下Java代码
private Comparator<Info_Column> getColumnsOrderBy() { if (I_AD_Field.Table_Name.equalsIgnoreCase(getTableName())) { return FixedOrderByKeyComparator.of( "*", ImmutableList.of( I_AD_Field.COLUMNNAME_AD_Column_ID, I_AD_Field.COLUMNNAME_Name, I_AD_Field.COLUMNNAME_EntityType, "*", I_AD_Field.COLUMNNAME_AD_Tab_ID ), Info_Column::getColumnName) .thenComparing(Info_Column::getSeqNo); } else { return Comparator.comparing(Info_Column::getSeqNo); } } /************************************************************************** * Construct SQL Where Clause and define parameters. * (setParameters needs to set parameters) * Includes first AND * @return where clause */ @Override protected String getSQLWhere() { StringBuffer sql = new StringBuffer(); addSQLWhere(sql, 0, textField1.getText().toUpperCase()); addSQLWhere(sql, 1, textField2.getText().toUpperCase()); addSQLWhere(sql, 2, textField3.getText().toUpperCase()); addSQLWhere(sql, 3, textField4.getText().toUpperCase()); return sql.toString(); } // getSQLWhere /** * Add directly Query as Strings * * @param sql sql buffer * @param index index * @param value value */ private void addSQLWhere(StringBuffer sql, int index, String value) { if (!(value.isEmpty() || value.equals("%")) && index < filterByColumns.size()) { // Angelo Dabala' (genied) nectosoft: [2893220] avoid to append string parameters directly because of special chars like quote(s) sql.append(" AND UPPER(").append(filterByColumns.get(index).getColumnSql()).append(") LIKE ?"); } } // addSQLWhere /** * Get SQL WHERE parameter * * @param f field * @return sql part */ private static String getSQLText(CTextField f) {
String s = f.getText().toUpperCase(); if (!s.contains("%")) { if (!s.endsWith("%")) { s += "%"; } if (!s.startsWith("%")) { s = "%" + s; } } return s; } // getSQLText /** * Set Parameters for Query. * (as defined in getSQLWhere) * * @param pstmt statement * @param forCount for counting records */ @Override protected void setParameters(PreparedStatement pstmt, boolean forCount) throws SQLException { int index = 1; if (!textField1.getText().isEmpty()) pstmt.setString(index++, getSQLText(textField1)); if (!textField2.getText().isEmpty()) pstmt.setString(index++, getSQLText(textField2)); if (!textField3.getText().isEmpty()) pstmt.setString(index++, getSQLText(textField3)); if (!textField4.getText().isEmpty()) pstmt.setString(index++, getSQLText(textField4)); } // setParameters // // // @Value @Builder private static class FilterByColumn { @NotNull String columnName; @NotNull String columnSql; } } // InfoGeneral
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoGeneral.java
1
请在Spring Boot框架中完成以下Java代码
public class BankCodeCType { @XmlValue protected BigInteger value; @XmlAttribute(name = "BankCodeType", namespace = "http://erpel.at/schemas/1p0/documents", required = true) protected CountryCodeType bankCodeType; /** * Gets the value of the value property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigInteger } * */ public void setValue(BigInteger value) { this.value = value; } /** * Defines the type of bank code by providing the country from which the bank code is. In order to specify the country in this attribute, a code according to ISO 3166-1 must be used. * * @return * possible object is * {@link CountryCodeType }
* */ public CountryCodeType getBankCodeType() { return bankCodeType; } /** * Sets the value of the bankCodeType property. * * @param value * allowed object is * {@link CountryCodeType } * */ public void setBankCodeType(CountryCodeType value) { this.bankCodeType = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BankCodeCType.java
2
请完成以下Java代码
public int getAD_UI_ElementField_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_ElementField_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_UI_Element getAD_UI_Element() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_UI_Element_ID, org.compiere.model.I_AD_UI_Element.class); } @Override public void setAD_UI_Element(org.compiere.model.I_AD_UI_Element AD_UI_Element) { set_ValueFromPO(COLUMNNAME_AD_UI_Element_ID, org.compiere.model.I_AD_UI_Element.class, AD_UI_Element); } /** Set UI Element. @param AD_UI_Element_ID UI Element */ @Override public void setAD_UI_Element_ID (int AD_UI_Element_ID) { if (AD_UI_Element_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, Integer.valueOf(AD_UI_Element_ID)); } /** Get UI Element. @return UI Element */ @Override public int getAD_UI_Element_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Element_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * TooltipIconName AD_Reference_ID=540912 * Reference name: TooltipIcon */ public static final int TOOLTIPICONNAME_AD_Reference_ID=540912; /** text = text */ public static final String TOOLTIPICONNAME_Text = "text"; /** Set Tooltip Icon Name. @param TooltipIconName Tooltip Icon Name */ @Override public void setTooltipIconName (java.lang.String TooltipIconName) { set_Value (COLUMNNAME_TooltipIconName, TooltipIconName);
} /** Get Tooltip Icon Name. @return Tooltip Icon Name */ @Override public java.lang.String getTooltipIconName () { return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName); } /** * Type AD_Reference_ID=540910 * Reference name: Type_AD_UI_ElementField */ public static final int TYPE_AD_Reference_ID=540910; /** widget = widget */ public static final String TYPE_Widget = "widget"; /** tooltip = tooltip */ public static final String TYPE_Tooltip = "tooltip"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java
1
请完成以下Java代码
public String getArtifactId() { return this.artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getBootVersion() { return this.bootVersion; } public void setBootVersion(String bootVersion) { this.bootVersion = bootVersion; } public String getPackaging() { return this.packaging; } public void setPackaging(String packaging) { this.packaging = packaging; } public String getApplicationName() { return this.applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public String getLanguage() { return this.language; } public void setLanguage(String language) { this.language = language; } public String getConfigurationFileFormat() { return this.configurationFileFormat; }
public void setConfigurationFileFormat(String configurationFileFormat) { this.configurationFileFormat = configurationFileFormat; } public String getPackageName() { if (StringUtils.hasText(this.packageName)) { return this.packageName; } if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) { return getGroupId() + "." + getArtifactId(); } return null; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getJavaVersion() { return this.javaVersion; } public void setJavaVersion(String javaVersion) { this.javaVersion = javaVersion; } public String getBaseDir() { return this.baseDir; } public void setBaseDir(String baseDir) { this.baseDir = baseDir; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\ProjectRequest.java
1
请完成以下Java代码
public Stream<HuForInventoryLine> streamHus() { final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder() .setOnlyTopLevelHUs() .addHUStatusToInclude(X_M_HU.HUSTATUS_Active); if (onlyStockedProducts != null) { huQueryBuilder.setOnlyStockedProducts(onlyStockedProducts); } if (warehouseId != null) { huQueryBuilder.addOnlyInWarehouseId(warehouseId); } if (locatorId != null) { huQueryBuilder.addOnlyInLocatorId(locatorId); } if (!onlyProductIds.isEmpty()) { huQueryBuilder.addOnlyWithProductIds(onlyProductIds); } if (asiId.isRegular()) { appendAttributeFilters(huQueryBuilder); } return huQueryBuilder.createQueryBuilder() .clearOrderBys().orderBy(I_M_HU.COLUMNNAME_M_HU_ID) .create() .iterateAndStream()
.flatMap(huForInventoryLineFactory::ofHURecord); } private void appendAttributeFilters(final IHUQueryBuilder huQueryBuilder) { final ImmutableAttributeSet storageRelevantAttributes = asiBL.getImmutableAttributeSetById(asiId) .filterOnlyStorageRelevantAttributes(); if (storageRelevantAttributes.isEmpty()) { return; } for (final AttributeId attributeId : storageRelevantAttributes.getAttributeIds()) { final Object value = storageRelevantAttributes.getValue(attributeId); huQueryBuilder.addOnlyWithAttribute(attributeId, value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\LocatorAndProductStrategy.java
1
请完成以下Spring Boot application配置
spring: datasource: url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false username: root password: root druid: initial-size: 5 #连接池初始化大小 min-idle: 10 #最小空闲连接数 max-active: 20 #最大连接数 web-stat-filter: exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" #不统计这些请求数据 stat-view-servlet: #访问监控网页的登录用户名和密码 login-username: druid login-password: druid data:
elasticsearch: repositories: enabled: true elasticsearch: uris: localhost:9200 logging: level: root: info com.macro.mall: debug logstash: host: localhost enableInnerLog: false
repos\mall-master\mall-search\src\main\resources\application-dev.yml
2
请完成以下Java代码
public String getExtensionId() { return "my-reactive-tenant-extension"; } } /** * Actual extension providing access to the {@link Tenant} value object. */ @RequiredArgsConstructor static class TenantExtension implements EvaluationContextExtension { private final Tenant tenant; @Override public String getExtensionId() { return "my-tenant-extension"; } @Override
public Tenant getRootObject() { return tenant; } } /** * The root object. */ @Value public static class Tenant { String tenantId; } }
repos\spring-data-examples-main\cassandra\reactive\src\main\java\example\springdata\cassandra\spel\ApplicationConfiguration.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_C_CashBook[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Cash Book. @param C_CashBook_ID Cash Book for recording petty cash transactions */ public void setC_CashBook_ID (int C_CashBook_ID) { if (C_CashBook_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID)); } /** Get Cash Book. @return Cash Book for recording petty cash transactions */ public int getC_CashBook_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Currency getC_Currency() throws RuntimeException { return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name) .getPO(getC_Currency_ID(), get_TrxName()); } /** Set Currency. @param C_Currency_ID The Currency for this record */ public void setC_Currency_ID (int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID)); } /** Get Currency. @return The Currency for this record */ public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Default.
@param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook.java
1
请完成以下Java代码
public class DefaultESRLineHandler implements IESRLineHandler { final private ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final private IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); @Override public boolean matchBPartnerOfInvoice(final I_C_Invoice invoice, final I_ESR_ImportLine esrLine) { final Properties ctx = InterfaceWrapperHelper.getCtx(invoice); if (sysConfigBL.getBooleanValue(ESRConstants.SYSCONFIG_MATCH_ORG, true)) { final I_C_BPartner invoicePartner = bpartnerDAO.getById(invoice.getC_BPartner_ID()); if (invoicePartner.getAD_Org_ID() > 0 // task 09852: a partner that has no org at all does not mean an inconsistency and is therefore OK && invoicePartner.getAD_Org_ID() != esrLine.getAD_Org_ID()) { ESRDataLoaderUtil.addMatchErrorMsg(esrLine, Services.get(IMsgBL.class).getMsg(ctx, ESRDataLoaderUtil.ESR_UNFIT_BPARTNER_ORG)); return false; } } else { // check the org: should not match with invoices from other orgs if (invoice.getAD_Org_ID() != esrLine.getAD_Org_ID()) { ESRDataLoaderUtil.addMatchErrorMsg(esrLine, Services.get(IMsgBL.class).getMsg(ctx, ESRDataLoaderUtil.ESR_UNFIT_INVOICE_ORG)); return false; } } return true; }
@Override public boolean matchBPartner( @NonNull final I_C_BPartner bPartner, @NonNull final I_ESR_ImportLine esrLine) { if (sysConfigBL.getBooleanValue(ESRConstants.SYSCONFIG_MATCH_ORG, true)) { if (bPartner.getAD_Org_ID() > 0 // task 09852: a partner that has no org at all does not mean an inconsistency and is therefore OK && bPartner.getAD_Org_ID() != esrLine.getAD_Org_ID()) { final Properties ctx = InterfaceWrapperHelper.getCtx(esrLine); final IMsgBL msgBL = Services.get(IMsgBL.class); ESRDataLoaderUtil.addMatchErrorMsg(esrLine, msgBL.getMsg(ctx, ESRDataLoaderUtil.ESR_UNFIT_BPARTNER_ORG)); return false; } } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\spi\impl\DefaultESRLineHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String title; private String isbn; @ManyToOne @JoinColumn(name = "library_id") private Library library; @ManyToMany(mappedBy = "books", fetch = FetchType.EAGER) private List<Author> authors; public Book() { } public Book(String title) { super(); this.title = title; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getId() { return id;
} public void setId(long id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Library getLibrary() { return library; } public void setLibrary(Library library) { this.library = library; } public List<Author> getAuthors() { return authors; } public void setAuthors(List<Author> authors) { this.authors = authors; } }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\books\models\Book.java
2
请在Spring Boot框架中完成以下Java代码
public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize(DataSize.ofBytes(10000000L)); factory.setMaxRequestSize(DataSize.ofBytes(10000000L)); return factory.createMultipartConfig(); } @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); bean.setOrder(2); return bean; } /** Static resource locations including themes*/ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/", "/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } /** BEGIN theme configuration */ @Bean public ResourceBundleThemeSource themeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setDefaultEncoding("UTF-8"); themeSource.setBasenamePrefix("themes."); return themeSource; } @Bean public CookieThemeResolver themeResolver() {
CookieThemeResolver resolver = new CookieThemeResolver(); resolver.setDefaultThemeName("default"); resolver.setCookieName("example-theme-cookie"); return resolver; } @Bean public ThemeChangeInterceptor themeChangeInterceptor() { ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor(); interceptor.setParamName("theme"); return interceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(themeChangeInterceptor()); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return factory -> factory.setRegisterDefaultServlet(true); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
private List<?> readCurrencyAndAmount() { int decimalPointPosition = readDecimalPointPosition(); String currencyCode = readNumericDataField(3, 3); String digits = readDataField(1, 15); BigDecimal amount = new BigDecimal(digits).movePointLeft(decimalPointPosition); return Arrays.asList(currencyCode, amount); } private List<String> readCountryList() { String dataField = readNumericDataField(3, 15); if (dataField.length() % 3 != 0) { throw new IllegalArgumentException("invalid data field length"); } ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < dataField.length(); i += 3) { list.add(dataField.substring(i, i + 3)); } return list; } private String readNumericDataField(int minLength, int maxLength) { String dataField = readDataField(minLength, maxLength); if (!StringUtils.isNumber(dataField)) { throw new AdempiereException("data field must be numeric: " + dataField); } return dataField; } private String readDataField(int minLength, int maxLength) { int length = 0; int endIndex = position; while (length < maxLength && endIndex < sequence.length()) { if (sequence.charAt(endIndex) == SEPARATOR_CHAR) { break; } endIndex++; length++; } if (length < minLength && minLength == maxLength) { throw new IllegalArgumentException("data field must be exactly " + minLength + " characters long"); }
if (length < minLength) { throw new IllegalArgumentException("data field must be at least " + minLength + " characters long"); } String dataField = sequence.substring(position, endIndex); position = endIndex; return dataField; } private void skipSeparatorIfPresent() { if (position < sequence.length() && sequence.charAt(position) == SEPARATOR_CHAR) { position++; } } public int remainingLength() { return sequence.length() - position; } public boolean startsWith(String prefix) { return sequence.startsWith(prefix, position); } private char readChar() { return sequence.charAt(position++); } public String read(int length) { String s = peek(length); position += length; return s; } public String peek(int length) { return sequence.substring(position, position + length); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1SequenceReader.java
1
请完成以下Java代码
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { return postReceive(message, channel); } @Override public Message<?> postReceive(Message<?> message, MessageChannel channel) { setup(message); return message; } @Override public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, @Nullable Exception ex) { cleanup(); } private void setup(Message<?> message) { Authentication authentication = message.getHeaders().get(this.authenticationHeaderName, Authentication.class); SecurityContext currentContext = this.securityContextHolderStrategy.getContext(); Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null) { contextStack = new Stack<>(); originalContext.set(contextStack); } contextStack.push(currentContext); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authentication); this.securityContextHolderStrategy.setContext(context); }
private void cleanup() { Stack<SecurityContext> contextStack = originalContext.get(); if (contextStack == null || contextStack.isEmpty()) { this.securityContextHolderStrategy.clearContext(); originalContext.remove(); return; } SecurityContext context = contextStack.pop(); try { if (this.empty.equals(context)) { this.securityContextHolderStrategy.clearContext(); originalContext.remove(); } else { this.securityContextHolderStrategy.setContext(context); } } catch (Throwable ex) { this.securityContextHolderStrategy.clearContext(); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextPropagationChannelInterceptor.java
1
请完成以下Java代码
public <T extends Spin<?>> T createSpinFromReader(Reader parameter) { ensureNotNull("parameter", parameter); RewindableReader rewindableReader = new RewindableReader(parameter, READ_SIZE); DataFormat<T> matchingDataFormat = null; for (DataFormat<?> format : DataFormats.getAvailableDataFormats()) { if (format.getReader().canRead(rewindableReader, rewindableReader.getRewindBufferSize())) { matchingDataFormat = (DataFormat<T>) format; } try { rewindableReader.rewind(); } catch (IOException e) { throw LOG.unableToReadFromReader(e); } } if (matchingDataFormat == null) { throw LOG.unrecognizableDataFormatException(); } return createSpin(rewindableReader, matchingDataFormat); } /** * * @throws SpinDataFormatException in case the parameter cannot be read using this data format * @throws IllegalArgumentException in case the parameter is null or dd: */ public <T extends Spin<?>> T createSpinFromSpin(T parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); return parameter; } public <T extends Spin<?>> T createSpinFromString(String parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter);
Reader input = SpinIoUtil.stringAsReader(parameter); return createSpin(input, format); } public <T extends Spin<?>> T createSpinFromReader(Reader parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); DataFormatReader reader = format.getReader(); Object dataFormatInput = reader.readInput(parameter); return format.createWrapperInstance(dataFormatInput); } public <T extends Spin<?>> T createSpinFromObject(Object parameter, DataFormat<T> format) { ensureNotNull("parameter", parameter); DataFormatMapper mapper = format.getMapper(); Object dataFormatInput = mapper.mapJavaToInternal(parameter); return format.createWrapperInstance(dataFormatInput); } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\SpinFactoryImpl.java
1
请完成以下Java代码
public void setRedirectUriResolver(Converter<RedirectUriParameters, Mono<String>> redirectUriResolver) { Assert.notNull(redirectUriResolver, "redirectUriResolver cannot be null"); this.redirectUriResolver = redirectUriResolver; } /** * Set the {@link ServerRedirectStrategy} to use, default * {@link DefaultServerRedirectStrategy} * @param redirectStrategy {@link ServerRedirectStrategy} * @since 6.5 */ public void setRedirectStrategy(ServerRedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } /** * Parameters, required for redirect URI resolving. * * @author Max Batischev * @since 6.5 */ public static final class RedirectUriParameters { private final ServerWebExchange serverWebExchange; private final Authentication authentication; private final ClientRegistration clientRegistration; public RedirectUriParameters(ServerWebExchange serverWebExchange, Authentication authentication, ClientRegistration clientRegistration) { Assert.notNull(clientRegistration, "clientRegistration cannot be null"); Assert.notNull(serverWebExchange, "serverWebExchange cannot be null"); Assert.notNull(authentication, "authentication cannot be null"); this.serverWebExchange = serverWebExchange; this.authentication = authentication; this.clientRegistration = clientRegistration; }
public ServerWebExchange getServerWebExchange() { return this.serverWebExchange; } public Authentication getAuthentication() { return this.authentication; } public ClientRegistration getClientRegistration() { return this.clientRegistration; } } /** * Default {@link Converter} for redirect uri resolving. * * @since 6.5 */ private final class DefaultRedirectUriResolver implements Converter<RedirectUriParameters, Mono<String>> { @Override public Mono<String> convert(RedirectUriParameters redirectUriParameters) { // @formatter:off return Mono.just(redirectUriParameters.authentication) .flatMap((authentication) -> { URI endSessionEndpoint = endSessionEndpoint(redirectUriParameters.clientRegistration); if (endSessionEndpoint == null) { return Mono.empty(); } String idToken = idToken(authentication); String postLogoutRedirectUri = postLogoutRedirectUri( redirectUriParameters.serverWebExchange.getRequest(), redirectUriParameters.clientRegistration); return Mono.just(endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri)); }); // @formatter:on } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\web\server\logout\OidcClientInitiatedServerLogoutSuccessHandler.java
1
请完成以下Java代码
public void setProductValue (String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Product Key. @return Key of the Product */ public String getProductValue () { return (String)get_Value(COLUMNNAME_ProductValue); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set UOM Code. @param X12DE355
UOM EDI X12 Code */ public void setX12DE355 (String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } /** Get UOM Code. @return UOM EDI X12 Code */ public String getX12DE355 () { return (String)get_Value(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
1
请完成以下Java代码
public java.lang.String getExportStatus() { return get_ValueAsString(COLUMNNAME_ExportStatus); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit getM_ShipmentSchedule_ExportAudit() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit.class); } @Override public void setM_ShipmentSchedule_ExportAudit(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit M_ShipmentSchedule_ExportAudit) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit.class, M_ShipmentSchedule_ExportAudit); } @Override public void setM_ShipmentSchedule_ExportAudit_ID (final int M_ShipmentSchedule_ExportAudit_ID) { if (M_ShipmentSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, M_ShipmentSchedule_ExportAudit_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID); } @Override public void setM_ShipmentSchedule_ExportAudit_Item_ID (final int M_ShipmentSchedule_ExportAudit_Item_ID) { if (M_ShipmentSchedule_ExportAudit_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); }
@Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请完成以下Java代码
public class CollectionsSortTimeComplexityJMH { public static void main(String[] args) throws Exception { org.openjdk.jmh.Main.main(args); } @Benchmark public void measureCollectionsSortBestCase(BestCaseBenchmarkState state) { List<Integer> sortedList = new ArrayList<>(state.sortedList); Collections.sort(sortedList); } @Benchmark public void measureCollectionsSortAverageWorstCase(AverageWorstCaseBenchmarkState state) { List<Integer> unsortedList = new ArrayList<>(state.unsortedList); Collections.sort(unsortedList); } @State(Scope.Benchmark) public static class BestCaseBenchmarkState { List<Integer> sortedList; @Setup(Level.Trial)
public void setUp() { sortedList = new ArrayList<>(); for (int i = 1; i <= 1000000; i++) { sortedList.add(i); } } } @State(Scope.Benchmark) public static class AverageWorstCaseBenchmarkState { List<Integer> unsortedList; @Setup(Level.Trial) public void setUp() { unsortedList = new ArrayList<>(); for (int i = 1000000; i > 0; i--) { unsortedList.add(i); } } } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\collectionssortcomplexity\CollectionsSortTimeComplexityJMH.java
1
请在Spring Boot框架中完成以下Java代码
public List<Post> retrievePostsForUser(@PathVariable int id) { Optional<User> user = userRepository.findById(id); if(user.isEmpty()) throw new UserNotFoundException("id:"+id); return user.get().getPosts(); } @PostMapping("/jpa/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { User savedUser = userRepository.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } @PostMapping("/jpa/users/{id}/posts") public ResponseEntity<Object> createPostForUser(@PathVariable int id, @Valid @RequestBody Post post) { Optional<User> user = userRepository.findById(id); if(user.isEmpty())
throw new UserNotFoundException("id:"+id); post.setUser(user.get()); Post savedPost = postRepository.save(post); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedPost.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserJpaResource.java
2
请完成以下Java代码
public int getAD_WF_Block_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Block_ID); } @Override public void setAD_Workflow_ID (final int AD_Workflow_ID) { if (AD_Workflow_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, AD_Workflow_ID); } @Override public int getAD_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description);
} @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Block.java
1
请在Spring Boot框架中完成以下Java代码
class MetadataCollector { private final Predicate<ItemMetadata> mergeRequired; private final ConfigurationMetadata previousMetadata; private final Set<ItemMetadata> metadataItems = new LinkedHashSet<>(); private final Set<ItemHint> metadataHints = new LinkedHashSet<>(); /** * Creates a new {@code MetadataProcessor} instance. * @param mergeRequired specify whether an item can be merged * @param previousMetadata any previous metadata or {@code null} */ MetadataCollector(Predicate<ItemMetadata> mergeRequired, ConfigurationMetadata previousMetadata) { this.mergeRequired = mergeRequired; this.previousMetadata = previousMetadata; } void add(ItemMetadata metadata) { this.metadataItems.add(metadata); } void add(ItemMetadata metadata, Consumer<ItemMetadata> onConflict) { ItemMetadata existing = find(metadata.getName()); if (existing != null) { onConflict.accept(existing); return; } add(metadata); } boolean addIfAbsent(ItemMetadata metadata) { ItemMetadata existing = find(metadata.getName()); if (existing != null) { return false; } add(metadata); return true; } void add(ItemHint itemHint) { this.metadataHints.add(itemHint); } boolean hasSimilarGroup(ItemMetadata metadata) { if (!metadata.isOfItemType(ItemMetadata.ItemType.GROUP)) { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } } return false; }
ConfigurationMetadata getMetadata() { ConfigurationMetadata metadata = new ConfigurationMetadata(); for (ItemMetadata item : this.metadataItems) { metadata.add(item); } for (ItemHint metadataHint : this.metadataHints) { metadata.add(metadataHint); } if (this.previousMetadata != null) { List<ItemMetadata> items = this.previousMetadata.getItems(); for (ItemMetadata item : items) { if (this.mergeRequired.test(item)) { metadata.addIfMissing(item); } } } return metadata; } private ItemMetadata find(String name) { return this.metadataItems.stream() .filter((candidate) -> name.equals(candidate.getName())) .findFirst() .orElse(null); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\MetadataCollector.java
2
请完成以下Java代码
public class HelpCommand extends AbstractCommand { private final CommandRunner commandRunner; public HelpCommand(CommandRunner commandRunner) { super("help", "Get help on commands"); this.commandRunner = commandRunner; } @Override public String getUsageHelp() { return "command"; } @Override public @Nullable String getHelp() { return null; } @Override public Collection<OptionHelp> getOptionsHelp() { List<OptionHelp> help = new ArrayList<>(); for (Command command : this.commandRunner) { if (isHelpShown(command)) { help.add(new OptionHelp() { @Override public Set<String> getOptions() { return Collections.singleton(command.getName()); } @Override public String getUsageHelp() { return command.getDescription(); } }); } } return help; } private boolean isHelpShown(Command command) { return !(command instanceof HelpCommand) && !(command instanceof HintCommand); } @Override public ExitStatus run(String... args) throws Exception { if (args.length == 0) { throw new NoHelpCommandArgumentsException(); } String commandName = args[0];
for (Command command : this.commandRunner) { if (command.getName().equals(commandName)) { Log.info(this.commandRunner.getName() + command.getName() + " - " + command.getDescription()); Log.info(""); if (command.getUsageHelp() != null) { Log.info("usage: " + this.commandRunner.getName() + command.getName() + " " + command.getUsageHelp()); Log.info(""); } if (command.getHelp() != null) { Log.info(command.getHelp()); } Collection<HelpExample> examples = command.getExamples(); if (examples != null) { Log.info((examples.size() != 1) ? "examples:" : "example:"); Log.info(""); for (HelpExample example : examples) { Log.info(" " + example.getDescription() + ":"); Log.info(" $ " + example.getExample()); Log.info(""); } Log.info(""); } return ExitStatus.OK; } } throw new NoSuchCommandException(commandName); } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\core\HelpCommand.java
1
请完成以下Java代码
public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set SubLine ID. @param SubLine_ID
Transaction sub line ID (internal) */ @Override public void setSubLine_ID (int SubLine_ID) { if (SubLine_ID < 1) set_ValueNoCheck (COLUMNNAME_SubLine_ID, null); else set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID)); } /** Get SubLine ID. @return Transaction sub line ID (internal) */ @Override public int getSubLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest.java
1
请完成以下Java代码
protected CostDetailCreateResult createOutboundCostDefaultImpl(final CostDetailCreateRequest request) { final boolean isReturnTrx = request.getQty().signum() > 0; final CurrentCost currentCosts = utils.getCurrentCost(request); final CostDetailPreviousAmounts previousCosts = CostDetailPreviousAmounts.of(currentCosts); final CostDetailCreateResult result; if (isReturnTrx) { result = utils.createCostDetailRecordWithChangedCosts(request, previousCosts); currentCosts.addWeightedAverage(request.getAmt(), request.getQty(), utils.getQuantityUOMConverter()); } else { final CostPrice price = currentCosts.getCostPrice(); final Quantity qty = utils.convertToUOM(request.getQty(), price.getUomId(), request.getProductId()); final CostAmount amt = price.multiply(qty).roundToPrecisionIfNeeded(currentCosts.getPrecision()); final CostDetailCreateRequest requestEffective = request.withAmount(amt); result = utils.createCostDetailRecordWithChangedCosts(requestEffective, previousCosts); currentCosts.addToCurrentQtyAndCumulate(qty, amt); } utils.saveCurrentCost(currentCosts);
return result; } @Override public void voidCosts(final CostDetailVoidRequest request) { final CurrentCost currentCosts = utils.getCurrentCost(request.getCostSegmentAndElement()); currentCosts.addToCurrentQtyAndCumulate(request.getQty().negate(), request.getAmt().negate(), utils.getQuantityUOMConverter()); utils.saveCurrentCost(currentCosts); } @Override public MoveCostsResult createMovementCosts(@NonNull final MoveCostsRequest request) { // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\methods\AverageInvoiceCostingMethodHandler.java
1
请完成以下Java代码
public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } public int getHorsePower() { return horsePower; } public void setHorsePower(int horsePower) { this.horsePower = horsePower; } public int getYearOfProduction() { return yearOfProduction; } public void setYearOfProduction(int yearOfProduction) { this.yearOfProduction = yearOfProduction; } public boolean isBigEngine() { return isBigEngine; }
public void setBigEngine(boolean bigEngine) { isBigEngine = bigEngine; } public boolean isNewCar() { return isNewCar; } public void setNewCar(boolean newCar) { isNewCar = newCar; } @Override public String toString() { return "Car{" + "make='" + make + '\'' + ", model='" + model + '\'' + ", engine=" + engine + ", horsePower=" + horsePower + ", yearOfProduction=" + yearOfProduction + ", isBigEngine=" + isBigEngine + ", isNewCar=" + isNewCar + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\entity\Car.java
1
请完成以下Java代码
public Locale getLocale() { return this.locale; } @Override public void configureExecutionInput(BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer) { this.executionInputConfigurers.add(configurer); } @Override public ExecutionInput toExecutionInput() { ExecutionInput.Builder inputBuilder = ExecutionInput.newExecutionInput() .query(getDocument()) .operationName(getOperationName()) .variables(getVariables()) .extensions(getExtensions()) .locale(this.locale) .executionId((this.executionId != null) ? this.executionId : ExecutionId.from(this.id));
ExecutionInput executionInput = inputBuilder.build(); for (BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput> configurer : this.executionInputConfigurers) { ExecutionInput current = executionInput; executionInput = executionInput.transform((builder) -> configurer.apply(current, builder)); } return executionInput; } @Override public String toString() { return super.toString() + ", id=" + getId() + ", Locale=" + getLocale(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\support\DefaultExecutionGraphQlRequest.java
1
请完成以下Java代码
public class DeleteHistoricProcessInstanceBatchConfigurationJsonConverter extends AbstractBatchConfigurationObjectConverter<BatchConfiguration> { public static final DeleteHistoricProcessInstanceBatchConfigurationJsonConverter INSTANCE = new DeleteHistoricProcessInstanceBatchConfigurationJsonConverter(); public static final String HISTORIC_PROCESS_INSTANCE_IDS = "historicProcessInstanceIds"; public static final String HISTORIC_PROCESS_INSTANCE_ID_MAPPINGS = "historicProcessInstanceIdMappings"; public static final String FAIL_IF_NOT_EXISTS = "failIfNotExists"; @Override public JsonObject writeConfiguration(BatchConfiguration configuration) { JsonObject json = JsonUtil.createObject(); JsonUtil.addListField(json, HISTORIC_PROCESS_INSTANCE_ID_MAPPINGS, DeploymentMappingJsonConverter.INSTANCE, configuration.getIdMappings()); JsonUtil.addListField(json, HISTORIC_PROCESS_INSTANCE_IDS, configuration.getIds()); JsonUtil.addField(json, FAIL_IF_NOT_EXISTS, configuration.isFailIfNotExists()); return json; }
@Override public BatchConfiguration readConfiguration(JsonObject json) { BatchConfiguration configuration = new BatchConfiguration(readProcessInstanceIds(json), readIdMappings(json), JsonUtil.getBoolean(json, FAIL_IF_NOT_EXISTS)); return configuration; } protected List<String> readProcessInstanceIds(JsonObject jsonObject) { return JsonUtil.asStringList(JsonUtil.getArray(jsonObject, HISTORIC_PROCESS_INSTANCE_IDS)); } protected DeploymentMappings readIdMappings(JsonObject json) { return JsonUtil.asList(JsonUtil.getArray(json, HISTORIC_PROCESS_INSTANCE_ID_MAPPINGS), DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\deletion\DeleteHistoricProcessInstanceBatchConfigurationJsonConverter.java
1
请完成以下Java代码
public class MonitorableQueueProcessorStatistics implements IMutableQueueProcessorStatistics { private static final String METERNAME_QueueSize = "QueueSize"; private static final String METERNAME_All = "All"; private static final String METERNAME_Processed = "Processed"; private static final String METERNAME_Error = "Error"; private static final String METERNAME_Skipped = "Skipped"; private final String workpackageProcessorName; public MonitorableQueueProcessorStatistics(@NonNull final String workpackageProcessorName) { this.workpackageProcessorName = workpackageProcessorName; } private final IMeter getMeter(final String meterName) { final String moduleName = Async_Constants.ENTITY_TYPE; final String meterNameFQ = workpackageProcessorName + "_" + meterName; return Services.get(IMonitoringBL.class).createOrGet(moduleName, meterNameFQ); } /** * NOTE: there is nothing to clone, since this is just an accessor for {@link IMeter}s * * @return this */ @Override public MonitorableQueueProcessorStatistics clone() { return this; } @Override public long getCountAll() { return getMeter(METERNAME_All).getGauge(); } @Override public void incrementCountAll() { getMeter(METERNAME_All).plusOne(); } @Override public long getCountProcessed() { return getMeter(METERNAME_Processed).getGauge(); }
@Override public void incrementCountProcessed() { getMeter(METERNAME_Processed).plusOne(); } @Override public long getCountErrors() { return getMeter(METERNAME_Error).getGauge(); } @Override public void incrementCountErrors() { getMeter(METERNAME_Error).plusOne(); } @Override public long getQueueSize() { return getMeter(METERNAME_QueueSize).getGauge(); } @Override public void incrementQueueSize() { getMeter(METERNAME_QueueSize).plusOne(); } @Override public void decrementQueueSize() { getMeter(METERNAME_QueueSize).minusOne(); } @Override public long getCountSkipped() { return getMeter(METERNAME_Skipped).getGauge(); } @Override public void incrementCountSkipped() { getMeter(METERNAME_Skipped).plusOne(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\MonitorableQueueProcessorStatistics.java
1
请完成以下Java代码
public Void execute(CommandContext context) { ensureNotNull(BadUserRequestException.class, "caseDefinitionId", caseDefinitionId); if (historyTimeToLive != null) { ensureGreaterThanOrEqual(BadUserRequestException.class, "", "historyTimeToLive", historyTimeToLive, 0); } validate(historyTimeToLive, context); CaseDefinitionEntity caseDefinitionEntity = context.getCaseDefinitionManager().findLatestDefinitionById(caseDefinitionId); for (CommandChecker checker : context.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateCaseDefinition(caseDefinitionEntity); } logUserOperation(context, caseDefinitionEntity); caseDefinitionEntity.setHistoryTimeToLive(historyTimeToLive); return null; } protected void logUserOperation(CommandContext commandContext, CaseDefinitionEntity caseDefinitionEntity) {
List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("historyTimeToLive", caseDefinitionEntity.getHistoryTimeToLive(), historyTimeToLive)); propertyChanges.add(new PropertyChange("caseDefinitionKey", null, caseDefinitionEntity.getKey())); commandContext.getOperationLogManager() .logCaseDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_UPDATE_HISTORY_TIME_TO_LIVE, caseDefinitionId, caseDefinitionEntity.getTenantId(), propertyChanges); } protected void validate(Integer historyTimeToLive, CommandContext context) { HistoryTimeToLiveParser parser = HistoryTimeToLiveParser.create(context); parser.validate(historyTimeToLive); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\cmd\UpdateCaseDefinitionHistoryTimeToLiveCmd.java
1
请完成以下Java代码
private Map<String, DestinationTopicHolder> correlatePairSourceAndDestinationValues( List<DestinationTopic> destinationList) { return IntStream .range(0, destinationList.size()) .boxed() .collect(Collectors.toMap(index -> destinationList.get(index).getDestinationName(), index -> new DestinationTopicHolder(destinationList.get(index), getNextDestinationTopic(destinationList, index)))); } private DestinationTopic getNextDestinationTopic(List<DestinationTopic> destinationList, int index) { return index != destinationList.size() - 1 ? destinationList.get(index + 1) : new DestinationTopic(destinationList.get(index).getDestinationName() + NO_OPS_SUFFIX, destinationList.get(index), NO_OPS_SUFFIX, DestinationTopic.Type.NO_OPS); } @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (Objects.equals(event.getApplicationContext(), this.applicationContext)) { this.contextRefreshed = true; } } /** * Return true if the application context is refreshed. * @return true if refreshed. * @since 2.7.8 */ public boolean isContextRefreshed() { return this.contextRefreshed; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }
public static class DestinationTopicHolder { private final DestinationTopic sourceDestination; private final DestinationTopic nextDestination; DestinationTopicHolder(DestinationTopic sourceDestination, DestinationTopic nextDestination) { this.sourceDestination = sourceDestination; this.nextDestination = nextDestination; } protected DestinationTopic getNextDestination() { return this.nextDestination; } protected DestinationTopic getSourceDestination() { return this.sourceDestination; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DefaultDestinationTopicResolver.java
1
请完成以下Java代码
public boolean hasAccess(Access access) { return accesses.contains(access); } public boolean isReadOnly() { return hasAccess(Access.READ) && !hasAccess(Access.WRITE); } public boolean isReadWrite() { return hasAccess(Access.WRITE); } public ClientId getClientId() { return resource.getClientId(); } public OrgId getOrgId() { return resource.getOrgId(); } @Override public OrgResource getResource()
{ return resource; } @Override public Permission mergeWith(final Permission permissionFrom) { final OrgPermission orgPermissionFrom = checkCompatibleAndCast(permissionFrom); final ImmutableSet<Access> accesses = ImmutableSet.<Access> builder() .addAll(this.accesses) .addAll(orgPermissionFrom.accesses) .build(); return new OrgPermission(resource, accesses); } /** * Creates a copy of this permission but it will use the given resource. * * @return copy of this permission but having the given resource */ public OrgPermission copyWithResource(final OrgResource resource) { return new OrgPermission(resource, this.accesses); } } // OrgAccess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermission.java
1
请完成以下Java代码
public boolean fromXmlNode(I_AD_MigrationData data, Element element) { data.setColumnName(element.getAttribute(NODE_Column)); data.setAD_Column_ID(Integer.parseInt(element.getAttribute(NODE_AD_Column_ID))); data.setIsOldNull("true".equals(element.getAttribute(NODE_isOldNull))); data.setOldValue(element.getAttribute(NODE_oldValue)); data.setIsNewNull("true".equals(element.getAttribute(NODE_isNewNull))); data.setNewValue(getText(element)); InterfaceWrapperHelper.save(data); logger.info("Imported data: " + data); return true; } // thx to http://www.java2s.com/Code/Java/XML/DOMUtilgetElementText.htm private String getText(Element element) {
StringBuffer buf = new StringBuffer(); NodeList list = element.getChildNodes(); boolean found = false; for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); found = true; } } return found ? buf.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\impl\MigrationDataHandler.java
1
请完成以下Java代码
public class DelegatingByTopicDeserializer extends DelegatingByTopicSerialization<Deserializer<?>> implements Deserializer<Object> { /** * Construct an instance that will be configured in {@link #configure(Map, boolean)} * with consumer properties. */ public DelegatingByTopicDeserializer() { } /** * Construct an instance with the supplied mapping of topic name patterns to delegate * deserializers. * @param delegates the map of delegates. * @param defaultDelegate the default to use when no topic name match. */ public DelegatingByTopicDeserializer(Map<Pattern, Deserializer<?>> delegates, Deserializer<?> defaultDelegate) { super(delegates, defaultDelegate); } @Override public void configure(Map<String, ?> configs, boolean isKey) { super.configure(configs, isKey); } @Override
protected Deserializer<?> configureDelegate(Map<String, ?> configs, boolean isKey, Deserializer<?> delegate) { delegate.configure(configs, isKey); return delegate; } @Override protected boolean isInstance(Object delegate) { return delegate instanceof Deserializer; } @Override public Object deserialize(String topic, byte[] data) { throw new UnsupportedOperationException(); } @Override public @Nullable Object deserialize(String topic, Headers headers, byte[] data) { return findDelegate(topic).deserialize(topic, headers, data); } @Override public @Nullable Object deserialize(String topic, Headers headers, ByteBuffer data) { return findDelegate(topic).deserialize(topic, headers, data); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTopicDeserializer.java
1
请完成以下Java代码
public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<String, String>(); options.put("useKeyTab", "true"); options.put("keyTab", this.keyTabLocation); options.put("principal", this.servicePrincipalName); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); if (this.debug) { options.put("debug", "true"); } if (this.realmName != null) { options.put("realm", this.realmName); }
if (this.refreshKrb5Config) { options.put("refreshKrb5Config", "true"); } if (!this.multiTier) { options.put("isInitiator", "false"); } return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), }; } } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\SunJaasKerberosTicketValidator.java
1
请完成以下Java代码
public class C_AggregationItem_Builder { private final C_Aggregation_Builder parentBuilder; private final AdTableId adTableId; private I_C_Aggregation aggregation; private String type; private AdColumnId adColumnId; private I_C_Aggregation includedAggregation; private I_C_Aggregation_Attribute attribute; private String includeLogic; public C_AggregationItem_Builder( @NonNull final C_Aggregation_Builder parentBuilder, @NonNull final AdTableId adTableId) { this.parentBuilder = parentBuilder; this.adTableId = adTableId; } public I_C_AggregationItem build() { final I_C_Aggregation aggregation = getC_Aggregation(); final I_C_AggregationItem aggregationItem = InterfaceWrapperHelper.newInstance(I_C_AggregationItem.class, aggregation); aggregationItem.setC_Aggregation(aggregation); aggregationItem.setType(getType()); aggregationItem.setAD_Column_ID(AdColumnId.toRepoId(getAD_Column_ID())); aggregationItem.setIncluded_Aggregation(getIncluded_Aggregation()); aggregationItem.setC_Aggregation_Attribute(getC_Aggregation_Attribute()); aggregationItem.setIncludeLogic(getIncludeLogic()); InterfaceWrapperHelper.save(aggregationItem); return aggregationItem; } public C_Aggregation_Builder end() { return parentBuilder; } @Override public String toString() { return ObjectUtils.toString(this); } public C_AggregationItem_Builder setC_Aggregation(final I_C_Aggregation aggregation) { this.aggregation = aggregation; return this; } private I_C_Aggregation getC_Aggregation() { Check.assumeNotNull(aggregation, "aggregation not null"); return aggregation; } public C_AggregationItem_Builder setType(final String type) { this.type = type; return this; } private String getType()
{ Check.assumeNotEmpty(type, "type not empty"); return type; } public C_AggregationItem_Builder setAD_Column(@Nullable final String columnName) { if (isBlank(columnName)) { this.adColumnId = null; } else { this.adColumnId = Services.get(IADTableDAO.class).retrieveColumnId(adTableId, columnName); } return this; } private AdColumnId getAD_Column_ID() { return adColumnId; } public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation) { this.includedAggregation = includedAggregation; return this; } private I_C_Aggregation getIncluded_Aggregation() { return includedAggregation; } public C_AggregationItem_Builder setIncludeLogic(final String includeLogic) { this.includeLogic = includeLogic; return this; } private String getIncludeLogic() { return includeLogic; } public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute) { this.attribute = attribute; return this; } private I_C_Aggregation_Attribute getC_Aggregation_Attribute() { return this.attribute; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java
1
请完成以下Java代码
protected ObjectNode mapDependency(Dependency dependency) { if (dependency.getCompatibilityRange() == null) { // only map the dependency if no compatibilityRange is set return mapValue(dependency); } return null; } protected ObjectNode mapType(Type type) { ObjectNode result = mapValue(type); result.put("action", type.getAction()); ObjectNode tags = nodeFactory.objectNode(); type.getTags().forEach(tags::put); result.set("tags", tags); return result; } private ObjectNode mapVersionMetadata(MetadataElement value) { ObjectNode result = nodeFactory.objectNode(); result.put("id", formatVersion(value.getId())); result.put("name", value.getName()); return result; }
protected String formatVersion(String versionId) { Version version = VersionParser.DEFAULT.safeParse(versionId); return (version != null) ? version.format(Format.V1).toString() : versionId; } protected ObjectNode mapValue(MetadataElement value) { ObjectNode result = nodeFactory.objectNode(); result.put("id", value.getId()); result.put("name", value.getName()); if ((value instanceof Describable) && ((Describable) value).getDescription() != null) { result.put("description", ((Describable) value).getDescription()); } return result; } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\InitializrMetadataV2JsonMapper.java
1
请在Spring Boot框架中完成以下Java代码
public King findByName(String name) { King t = kingDao.findByName(name); return t; } /** * 获取当前节点下的所有king * * @param name * @return */ public List<King> getKings(String name) { return kingDao.getKings(name); }
/** * 保存父子关系 * * @param fatherName * @param sonName * @return */ public void saveRelation(String fatherName, String sonName) { King from = kingDao.findByName(fatherName); King to = kingDao.findByName(sonName); FatherAndSonRelation fatherAndSonRelation = new FatherAndSonRelation(); fatherAndSonRelation.setFrom(from); fatherAndSonRelation.setTo(to); from.addRelation(fatherAndSonRelation); kingDao.save(from); } }
repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\service\KingService.java
2
请完成以下Java代码
public String getId() { return id; } public String getBusinessKey() { return businessKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public Date getCreateTime() { return createTime; } public Date getCloseTime() { return closeTime; } public Long getDurationInMillis() { return durationInMillis; } public String getCreateUserId() { return createUserId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getTenantId() { return tenantId; } public Boolean getActive() { return active; }
public Boolean getCompleted() { return completed; } public Boolean getTerminated() { return terminated; } public Boolean getClosed() { return closed; } public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) { HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto(); dto.id = historicCaseInstance.getId(); dto.businessKey = historicCaseInstance.getBusinessKey(); dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId(); dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey(); dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName(); dto.createTime = historicCaseInstance.getCreateTime(); dto.closeTime = historicCaseInstance.getCloseTime(); dto.durationInMillis = historicCaseInstance.getDurationInMillis(); dto.createUserId = historicCaseInstance.getCreateUserId(); dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId(); dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId(); dto.tenantId = historicCaseInstance.getTenantId(); dto.active = historicCaseInstance.isActive(); dto.completed = historicCaseInstance.isCompleted(); dto.terminated = historicCaseInstance.isTerminated(); dto.closed = historicCaseInstance.isClosed(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseInstanceDto.java
1
请完成以下Java代码
public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setAmt(ActiveOrHistoricCurrencyAndAmount value) { this.amt = value; } /** * Gets the value of the ccyXchg property. * * @return
* possible object is * {@link CurrencyExchange5 } * */ public CurrencyExchange5 getCcyXchg() { return ccyXchg; } /** * Sets the value of the ccyXchg property. * * @param value * allowed object is * {@link CurrencyExchange5 } * */ public void setCcyXchg(CurrencyExchange5 value) { this.ccyXchg = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AmountAndCurrencyExchangeDetails4.java
1
请完成以下Java代码
private static String exceptionMessage(String errorCode, String message) { if (message == null) { return ""; } else { return message + " (errorCode='" + errorCode + "')"; } } protected void setErrorCode(String errorCode) { ensureNotEmpty("Error Code", errorCode); this.errorCode = errorCode; } public String getErrorCode() { return errorCode; }
@Override public String toString() { return super.toString() + " (errorCode='" + errorCode + "')"; } protected void setMessage(String errorMessage) { ensureNotEmpty("Error Message", errorMessage); this.errorMessage = errorMessage; } @Override public String getMessage() { return errorMessage; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\delegate\BpmnError.java
1
请完成以下Java代码
public static RSAPublicKey readX509PublicKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException { KeyFactory factory = KeyFactory.getInstance("RSA"); try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) { PemObject pemObject = pemReader.readPemObject(); byte[] content = pemObject.getContent(); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content); return (RSAPublicKey) factory.generatePublic(pubKeySpec); } } public static RSAPublicKey readX509PublicKeySecondApproach(File file) throws IOException { try (FileReader keyReader = new FileReader(file)) { PEMParser pemParser = new PEMParser(keyReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pemParser.readObject()); return (RSAPublicKey) converter.getPublicKey(publicKeyInfo); } } public static RSAPrivateKey readPKCS8PrivateKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException { KeyFactory factory = KeyFactory.getInstance("RSA"); try (FileReader keyReader = new FileReader(file); PemReader pemReader = new PemReader(keyReader)) {
PemObject pemObject = pemReader.readPemObject(); byte[] content = pemObject.getContent(); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content); return (RSAPrivateKey) factory.generatePrivate(privKeySpec); } } public static RSAPrivateKey readPKCS8PrivateKeySecondApproach(File file) throws IOException { try (FileReader keyReader = new FileReader(file)) { PEMParser pemParser = new PEMParser(keyReader); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(pemParser.readObject()); return (RSAPrivateKey) converter.getPrivateKey(privateKeyInfo); } } }
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\pem\BouncyCastlePemUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class AD_Menu { @Init public void init() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_AD_Tab.COLUMNNAME_AD_Element_ID) @CalloutMethod(columnNames = I_AD_Menu.COLUMNNAME_AD_Element_ID) public void onElementIDChanged(final I_AD_Menu menu) { final IADElementDAO adElementDAO = Services.get(IADElementDAO.class); if (!IElementTranslationBL.DYNATTR_AD_Menu_UpdateTranslations.getValue(menu, true)) { // do not copy translations from element to menu return; } final I_AD_Element menuElement = adElementDAO.getById(menu.getAD_Element_ID()); if (menuElement == null) { // nothing to do. It was not yet set return; } menu.setName(menuElement.getName()); menu.setDescription(menuElement.getDescription());
menu.setWEBUI_NameBrowse(menuElement.getWEBUI_NameBrowse()); menu.setWEBUI_NameNew(menuElement.getWEBUI_NameNew()); menu.setWEBUI_NameNewBreadcrumb(menuElement.getWEBUI_NameNewBreadcrumb()); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_AD_Menu.COLUMNNAME_AD_Element_ID) public void updateTranslationsForElement(final I_AD_Menu menu) { final AdElementId menuElementId = AdElementId.ofRepoIdOrNull(menu.getAD_Element_ID()); if (menuElementId == null) { // nothing to do. It was not yet set return; } Services.get(IElementTranslationBL.class).updateMenuTranslationsFromElement(menuElementId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\menu\model\interceptor\AD_Menu.java
2
请在Spring Boot框架中完成以下Java代码
public class DerKurierShipperConfig { String restApiBaseUrl; String customerNumber; ParcelNumberGenerator parcelNumberGenerator; Optional<MailboxId> deliveryOrderMailBoxId; EMailAddress deliveryOrderRecipientEmailOrNull; int parcelNumberAdSequenceId; String collectorCode; String customerCode; LocalTime desiredTimeFrom; LocalTime desiredTimeTo; @Builder private DerKurierShipperConfig( @NonNull final String restApiBaseUrl, @NonNull final String customerNumber, @Nullable final MailboxId deliveryOrderMailBoxId, @Nullable final EMailAddress deliveryOrderRecipientEmailOrNull, @NonNull String collectorCode, @NonNull String customerCode, final int parcelNumberAdSequenceId, @NonNull LocalTime desiredTimeFrom, @NonNull LocalTime desiredTimeTo) {
this.customerNumber = Check.assumeNotEmpty(customerNumber, "Parameter customerNumber is not empty"); this.restApiBaseUrl = Check.assumeNotEmpty(restApiBaseUrl, "Parameter restApiBaseUrl is not empty"); final boolean mailBoxIsSet = deliveryOrderMailBoxId != null; final boolean mailAddressIsSet = deliveryOrderRecipientEmailOrNull != null; Check.errorIf(mailBoxIsSet != mailAddressIsSet, "If a mailbox is configured, then also a mail address needs to be set and vice versa."); this.deliveryOrderRecipientEmailOrNull = deliveryOrderRecipientEmailOrNull; this.deliveryOrderMailBoxId = Optional.ofNullable(deliveryOrderMailBoxId); Check.assume(parcelNumberAdSequenceId > 0 || parcelNumberAdSequenceId == ParcelNumberGenerator.NO_AD_SEQUENCE_ID_FOR_TESTING, "Parameter parcelNumberAdSequenceId is > 0"); this.parcelNumberAdSequenceId = parcelNumberAdSequenceId; this.parcelNumberGenerator = new ParcelNumberGenerator(parcelNumberAdSequenceId); this.collectorCode = collectorCode; this.customerCode = customerCode; this.desiredTimeFrom = desiredTimeFrom; this.desiredTimeTo = desiredTimeTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\DerKurierShipperConfig.java
2
请完成以下Java代码
public class SysPackPermission implements Serializable { private static final long serialVersionUID = 1L; /**主键编号*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "主键编号") private String id; /**租户产品包名称*/ @Excel(name = "租户产品包名称", width = 15) @Schema(description = "租户产品包名称") private String packId; /**菜单id*/ @Excel(name = "菜单id", width = 15) @Schema(description = "菜单id") private String permissionId; /**创建人*/ @Schema(description = "创建人")
private String createBy; /**创建时间*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") @Schema(description = "创建时间") private Date createTime; /**更新人*/ @Schema(description = "更新人") private String updateBy; /**更新时间*/ @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") @Schema(description = "更新时间") private Date updateTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysPackPermission.java
1
请完成以下Java代码
public void setInheritBusinessKey(boolean inheritBusinessKey) { this.inheritBusinessKey = inheritBusinessKey; } public boolean isFallbackToDefaultTenant() { return fallbackToDefaultTenant; } public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) { this.fallbackToDefaultTenant = fallbackToDefaultTenant; } @Override public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public List<IOParameter> getOutParameters() { return outParameters; } @Override public void addOutParameter(IOParameter outParameter) { this.outParameters.add(outParameter); } @Override public void setOutParameters(List<IOParameter> outParameters) { this.outParameters = outParameters; } public String getCaseInstanceIdVariableName() { return caseInstanceIdVariableName; }
public void setCaseInstanceIdVariableName(String caseInstanceIdVariableName) { this.caseInstanceIdVariableName = caseInstanceIdVariableName; } @Override public CaseServiceTask clone() { CaseServiceTask clone = new CaseServiceTask(); clone.setValues(this); return clone; } public void setValues(CaseServiceTask otherElement) { super.setValues(otherElement); setCaseDefinitionKey(otherElement.getCaseDefinitionKey()); setCaseInstanceName(otherElement.getCaseInstanceName()); setBusinessKey(otherElement.getBusinessKey()); setInheritBusinessKey(otherElement.isInheritBusinessKey()); setSameDeployment(otherElement.isSameDeployment()); setFallbackToDefaultTenant(otherElement.isFallbackToDefaultTenant()); setCaseInstanceIdVariableName(otherElement.getCaseInstanceIdVariableName()); inParameters = new ArrayList<>(); if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } outParameters = new ArrayList<>(); if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getOutParameters()) { outParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CaseServiceTask.java
1
请完成以下Java代码
public static int getBiFrequency(String a, String b) { int idA = CoreDictionary.trie.exactMatchSearch(a); if (idA == -1) { return 0; } int idB = CoreDictionary.trie.exactMatchSearch(b); if (idB == -1) { return 0; } int index = binarySearch(pair, start[idA], start[idA + 1] - start[idA], idB); if (index < 0) return 0; index <<= 1; return pair[index + 1]; } /** * 获取共现频次 * @param idA 第一个词的id * @param idB 第二个词的id * @return 共现频次 */ public static int getBiFrequency(int idA, int idB) { // 负数id表示来自用户词典的词语的词频(用户自定义词语没有id),返回正值增加其亲和度 if (idA < 0) { return -idA; } if (idB < 0) { return -idB; } int index = binarySearch(pair, start[idA], start[idA + 1] - start[idA], idB); if (index < 0) return 0; index <<= 1; return pair[index + 1]; }
/** * 获取词语的ID * * @param a 词语 * @return id */ public static int getWordID(String a) { return CoreDictionary.trie.exactMatchSearch(a); } /** * 热更新二元接续词典<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件 * @return 是否成功 */ public static boolean reload() { String biGramDictionaryPath = HanLP.Config.BiGramDictionaryPath; IOUtil.deleteFile(biGramDictionaryPath + ".table" + Predefine.BIN_EXT); return load(biGramDictionaryPath); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreBiGramTableDictionary.java
1
请完成以下Java代码
public void runJobNow(QuartzJob quartzJob){ try { TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null) { addJob(quartzJob); } JobDataMap dataMap = new JobDataMap(); dataMap.put(QuartzJob.JOB_KEY, quartzJob); JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.triggerJob(jobKey,dataMap); } catch (Exception e){ log.error("定时任务执行失败", e); throw new BadRequestException("定时任务执行失败"); }
} /** * 暂停一个job * @param quartzJob / */ public void pauseJob(QuartzJob quartzJob){ try { JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); scheduler.pauseJob(jobKey); } catch (Exception e){ log.error("定时任务暂停失败", e); throw new BadRequestException("定时任务暂停失败"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\quartz\utils\QuartzManage.java
1
请完成以下Java代码
public void payloadIgnoredForHttpMethod(String method) { logInfo("003", "Ignoring payload for HTTP '{}' method", method); } public ConnectorResponseException unableToReadResponse(Exception cause) { return new ConnectorResponseException(exceptionMessage("004", "Unable to read connectorResponse: {}", cause.getMessage()), cause); } public ConnectorRequestException requestUrlRequired() { return new ConnectorRequestException(exceptionMessage("005", "Request url required.")); } public ConnectorRequestException unknownHttpMethod(String method) { return new ConnectorRequestException(exceptionMessage("006", "Unknown or unsupported HTTP method '{}'", method)); } public ConnectorRequestException unableToExecuteRequest(Exception cause) { return new ConnectorRequestException(exceptionMessage("007", "Unable to execute HTTP request"), cause); }
public ConnectorRequestException invalidConfigurationOption(String optionName, Exception cause) { return new ConnectorRequestException(exceptionMessage("008", "Invalid value for request configuration option: {}", optionName), cause); } public void ignoreConfig(String field, Object value) { logInfo("009", "Ignoring request configuration option with name '{}' and value '{}'", field, value); } public ConnectorRequestException httpRequestError(int statusCode , String connectorResponse) { return new ConnectorRequestException(exceptionMessage("010", "HTTP request failed with Status Code: {} ," + " Response: {}", statusCode, connectorResponse)); } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\HttpConnectorLogger.java
1
请完成以下Java代码
public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); }
@Override public void setQM_Analysis_Report_ID (final int QM_Analysis_Report_ID) { if (QM_Analysis_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_QM_Analysis_Report_ID, QM_Analysis_Report_ID); } @Override public int getQM_Analysis_Report_ID() { return get_ValueAsInt(COLUMNNAME_QM_Analysis_Report_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_QM_Analysis_Report.java
1
请完成以下Java代码
public class X_WEBUI_Board_Lane extends org.compiere.model.PO implements I_WEBUI_Board_Lane, org.compiere.model.I_Persistent { private static final long serialVersionUID = -492769515L; /** Standard Constructor */ public X_WEBUI_Board_Lane (final Properties ctx, final int WEBUI_Board_Lane_ID, @Nullable final String trxName) { super (ctx, WEBUI_Board_Lane_ID, trxName); } /** Load Constructor */ public X_WEBUI_Board_Lane (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 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 setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) {
set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID); } @Override public void setWEBUI_Board_Lane_ID (final int WEBUI_Board_Lane_ID) { if (WEBUI_Board_Lane_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, WEBUI_Board_Lane_ID); } @Override public int getWEBUI_Board_Lane_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_Lane_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_Lane.java
1
请在Spring Boot框架中完成以下Java代码
public class AddToResultGroupRequest { int queryNo; @NonNull ProductId productId; @NonNull AttributesKey storageAttributesKey; @NonNull WarehouseId warehouseId; @Nullable BigDecimal qtyOnHandStock; @Nullable BigDecimal qtyToBeShipped; @Builder public AddToResultGroupRequest( final int queryNo, @NonNull final ProductId productId, @NonNull final AttributesKey storageAttributesKey, @NonNull final WarehouseId warehouseId,
@Nullable final BigDecimal qtyOnHandStock, @Nullable final BigDecimal qtyToBeShipped) { this.queryNo = queryNo; this.productId = productId; this.warehouseId = warehouseId; this.storageAttributesKey = storageAttributesKey; this.qtyOnHandStock = qtyOnHandStock; this.qtyToBeShipped = qtyToBeShipped; } public ArrayKey computeKey() { return ArrayKey.of(productId, storageAttributesKey, warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\AddToResultGroupRequest.java
2
请完成以下Java代码
public class MyCleanerResourceClass implements AutoCloseable { private static Resource resource; private static final Cleaner cleaner = Cleaner.create(); private final Cleaner.Cleanable cleanable; public MyCleanerResourceClass() { resource = new Resource(); this.cleanable = cleaner.register(this, new CleaningState()); } public void useResource() { // using the resource here resource.use(); } @Override public void close() { // perform actions to close all underlying resources this.cleanable.clean(); } static class CleaningState implements Runnable {
CleaningState() { // constructor } @Override public void run() { // some cleanup action System.out.println("Cleanup done"); } } static class Resource { void use() { System.out.println("Using the resource"); } void close() { System.out.println("Cleanup done"); } } }
repos\tutorials-master\core-java-modules\core-java-18\src\main\java\com\baeldung\finalization_closeable_cleaner\MyCleanerResourceClass.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set GL Category. @param GL_Category_ID General Ledger Category */ public void setGL_Category_ID (int GL_Category_ID) { if (GL_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID)); } /** Get GL Category. @return General Ledger Category */ public int getGL_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Category.java
1
请完成以下Java代码
public static Throwable retrieveException() { final Throwable ex = getLastErrorsInstance().getLastExceptionAndReset(); return ex; } /** * Save Warning as ValueNamePair. * * @param AD_Message message key * @param message clear text message */ public static void saveWarning(final Logger logger, final String AD_Message, final String message) { final ValueNamePair lastWarning = ValueNamePair.of(AD_Message, message); getLastErrorsInstance().setLastWarning(lastWarning); // print it if (true) { logger.warn(AD_Message + " - " + message); } } // saveWarning /** * Get Warning from Stack * * @return AD_Message as Value and Message as String */ public static ValueNamePair retrieveWarning() { final ValueNamePair lastWarning = getLastErrorsInstance().getLastWarningAndReset(); return lastWarning; } // retrieveWarning /** * Reset Saved Messages/Errors/Info */ public static void resetLast() { getLastErrorsInstance().reset(); } private final static LastErrorsInstance getLastErrorsInstance() { final Properties ctx = Env.getCtx(); return Env.get(ctx, LASTERRORINSTANCE_CTXKEY, LastErrorsInstance::new); } /** * Holds last error/exception, warning and info. * * @author tsa */ @ThreadSafe @SuppressWarnings("serial") private static class LastErrorsInstance implements Serializable { private ValueNamePair lastError; private Throwable lastException; private ValueNamePair lastWarning; private LastErrorsInstance() { super(); } @Override public synchronized String toString() {
final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append("["); sb.append("lastError=").append(lastError); sb.append(", lastException=").append(lastException); sb.append(", lastWarning=").append(lastWarning); sb.append("]"); return sb.toString(); } public synchronized ValueNamePair getLastErrorAndReset() { final ValueNamePair lastErrorToReturn = lastError; lastError = null; return lastErrorToReturn; } public synchronized void setLastError(final ValueNamePair lastError) { this.lastError = lastError; } public synchronized Throwable getLastExceptionAndReset() { final Throwable lastExceptionAndClear = lastException; lastException = null; return lastExceptionAndClear; } public synchronized void setLastException(final Throwable lastException) { this.lastException = lastException; } public synchronized ValueNamePair getLastWarningAndReset() { final ValueNamePair lastWarningToReturn = lastWarning; lastWarning = null; return lastWarningToReturn; } public synchronized void setLastWarning(final ValueNamePair lastWarning) { this.lastWarning = lastWarning; } public synchronized void reset() { lastError = null; lastException = null; lastWarning = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshLastError.java
1
请在Spring Boot框架中完成以下Java代码
public class PushBPartnersProcessor implements Processor { @Override public void process(final Exchange exchange) { final JsonVendor jsonBPartner = exchange.getIn().getBody(JsonVendor.class); final BPUpsertCamelRequest bpUpsertCamelRequest = getBPUpsertCamelRequest(jsonBPartner); exchange.getIn().setBody(bpUpsertCamelRequest, JsonRequestBPartnerUpsert.class); } @NonNull private BPUpsertCamelRequest getBPUpsertCamelRequest(@NonNull final JsonVendor jsonVendor) { final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials(); final JsonRequestBPartner jsonRequestBPartner = new JsonRequestBPartner(); jsonRequestBPartner.setName(jsonVendor.getName()); jsonRequestBPartner.setCompanyName(jsonVendor.getName()); jsonRequestBPartner.setActive(jsonVendor.isActive()); jsonRequestBPartner.setVendor(true); jsonRequestBPartner.setCode(jsonVendor.getBpartnerValue()); final JsonRequestComposite jsonRequestComposite = JsonRequestComposite.builder() .orgCode(credentials.getOrgCode()) .bpartner(jsonRequestBPartner) .build(); final JsonRequestBPartnerUpsertItem jsonRequestBPartnerUpsertItem = JsonRequestBPartnerUpsertItem.builder() .bpartnerIdentifier(computeBPartnerIdentifier(jsonVendor))
.bpartnerComposite(jsonRequestComposite) .build(); final JsonRequestBPartnerUpsert jsonRequestBPartnerUpsert = JsonRequestBPartnerUpsert.builder() .requestItem(jsonRequestBPartnerUpsertItem) .syncAdvise(SyncAdvise.CREATE_OR_MERGE) .build(); return BPUpsertCamelRequest.builder() .jsonRequestBPartnerUpsert(jsonRequestBPartnerUpsert) .orgCode(credentials.getOrgCode()) .build(); } @NonNull private static String computeBPartnerIdentifier(@NonNull final JsonVendor jsonVendor) { if (jsonVendor.getMetasfreshId() != null && Check.isNotBlank(jsonVendor.getMetasfreshId())) { return jsonVendor.getMetasfreshId(); } throw new RuntimeException("Missing mandatory METASFRESHID! JsonVendor.MKREDID: " + jsonVendor.getBpartnerValue()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\vendor\processor\PushBPartnersProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultEntityLimitsCache implements EntityLimitsCache { private static final int DEVIATION = 10; private final Cache<EntityLimitKey, Boolean> cache; public DefaultEntityLimitsCache(@Value("${cache.entityLimits.timeToLiveInMinutes:5}") int ttl, @Value("${cache.entityLimits.maxSize:100000}") int maxSize) { // We use the 'random' expiration time to avoid peak loads. long mainPart = (TimeUnit.MINUTES.toNanos(ttl) / 100) * (100 - DEVIATION); long randomPart = (TimeUnit.MINUTES.toNanos(ttl) / 100) * DEVIATION; cache = Caffeine.newBuilder() .expireAfter(new Expiry<EntityLimitKey, Boolean>() { @Override public long expireAfterCreate(@NotNull EntityLimitKey key, @NotNull Boolean value, long currentTime) { return mainPart + (long) (randomPart * ThreadLocalRandom.current().nextDouble()); } @Override public long expireAfterUpdate(@NotNull EntityLimitKey key, @NotNull Boolean value, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(@NotNull EntityLimitKey key, @NotNull Boolean value, long currentTime, long currentDuration) { return currentDuration; }
}) .maximumSize(maxSize) .build(); } @Override public boolean get(EntityLimitKey key) { var result = cache.getIfPresent(key); return result != null ? result : false; } @Override public void put(EntityLimitKey key, boolean value) { cache.put(key, value); } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\limits\DefaultEntityLimitsCache.java
2
请完成以下Java代码
public boolean isTemporaryPricingConditionsBreak() { return hasChanges || id == null; } public PricingConditionsBreak toTemporaryPricingConditionsBreak() { if (isTemporaryPricingConditionsBreak()) { return this; } return toBuilder().id(null).build(); }
public PricingConditionsBreak toTemporaryPricingConditionsBreakIfPriceRelevantFieldsChanged(@NonNull final PricingConditionsBreak reference) { if (isTemporaryPricingConditionsBreak()) { return this; } if (equalsByPriceRelevantFields(reference)) { return this; } return toTemporaryPricingConditionsBreak(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreak.java
1
请在Spring Boot框架中完成以下Java代码
public class CommentsConfiguration extends ResourceServerConfigurerAdapter { /** * Provide security so that endpoints are only served if the request is * already authenticated. */ @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http.requestMatchers() .antMatchers("/**") .and() .authorizeRequests() .anyRequest() .authenticated() .antMatchers(HttpMethod.GET, "/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.OPTIONS, "/**").access("#oauth2.hasScope('read')") .antMatchers(HttpMethod.POST, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PUT, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.PATCH, "/**").access("#oauth2.hasScope('write')") .antMatchers(HttpMethod.DELETE, "/**").access("#oauth2.hasScope('write')"); // @formatter:on } /** * Id of the resource that you are letting the client have access to. * Supposing you have another api ("say api2"), then you can customize the * access within resource server to define what api is for what resource id. * <br> * <br> *
* So suppose you have 2 APIs, then you can define 2 resource servers. * <ol> * <li>Client 1 has been configured for access to resourceid1, so he can * only access "api1" if the resource server configures the resourceid to * "api1".</li> * <li>Client 1 can't access resource server 2 since it has configured the * resource id to "api2" * </li> * </ol> * */ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("apis"); } }
repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\config\CommentsConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
private @Nullable String mapFactoryName(String name) { if (!name.startsWith(OPTIONAL_PREFIX)) { return name; } name = name.substring(OPTIONAL_PREFIX.length()); return (!present(name)) ? null : name; } private boolean present(String className) { String resourcePath = ClassUtils.convertClassNameToResourcePath(className) + ".class"; return new ClassPathResource(resourcePath).exists(); } protected Collection<String> loadFactoryNames(Class<?> source) { return ImportCandidates.load(source, getBeanClassLoader()).getCandidates(); } @Override protected Set<String> getExclusions(AnnotationMetadata metadata, @Nullable AnnotationAttributes attributes) { Set<String> exclusions = new LinkedHashSet<>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader()); for (String annotationName : ANNOTATION_NAMES) { AnnotationAttributes merged = AnnotatedElementUtils.getMergedAnnotationAttributes(source, annotationName); Class<?>[] exclude = (merged != null) ? merged.getClassArray("exclude") : null; if (exclude != null) { for (Class<?> excludeClass : exclude) { exclusions.add(excludeClass.getName()); } } } for (List<Annotation> annotations : getAnnotations(metadata).values()) { for (Annotation annotation : annotations) { String[] exclude = (String[]) AnnotationUtils.getAnnotationAttributes(annotation, true).get("exclude"); if (!ObjectUtils.isEmpty(exclude)) { exclusions.addAll(Arrays.asList(exclude)); } }
} exclusions.addAll(getExcludeAutoConfigurationsProperty()); return exclusions; } protected final Map<Class<?>, List<Annotation>> getAnnotations(AnnotationMetadata metadata) { MultiValueMap<Class<?>, Annotation> annotations = new LinkedMultiValueMap<>(); Class<?> source = ClassUtils.resolveClassName(metadata.getClassName(), getBeanClassLoader()); collectAnnotations(source, annotations, new HashSet<>()); return Collections.unmodifiableMap(annotations); } private void collectAnnotations(@Nullable Class<?> source, MultiValueMap<Class<?>, Annotation> annotations, HashSet<Class<?>> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); } } collectAnnotations(source.getSuperclass(), annotations, seen); } } @Override public int getOrder() { return super.getOrder() - 1; } @Override protected void handleInvalidExcludes(List<String> invalidExcludes) { // Ignore for test } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ImportAutoConfigurationImportSelector.java
2
请完成以下Java代码
public List<InventoryLineHU> toInventoryLineHUs( @NonNull final IUOMConversionBL uomConversionBL, @NonNull final UomId targetUomId) { final UnaryOperator<Quantity> uomConverter = qty -> uomConversionBL.convertQuantityTo(qty, productId, targetUomId); return huForInventoryLineList.stream() .map(DraftInventoryLinesCreateCommand::toInventoryLineHU) .map(inventoryLineHU -> inventoryLineHU.convertQuantities(uomConverter)) .collect(ImmutableList.toImmutableList()); } @NonNull public Set<HuId> getHuIds() { return huForInventoryLineList.stream() .map(HuForInventoryLine::getHuId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); }
@NonNull private <K> Map<K, ProductHUInventory> mapByKey(final Function<HuForInventoryLine, K> keyProvider) { final Map<K, List<HuForInventoryLine>> key2Hus = new HashMap<>(); huForInventoryLineList.forEach(hu -> { final ArrayList<HuForInventoryLine> husFromTargetWarehouse = new ArrayList<>(); husFromTargetWarehouse.add(hu); key2Hus.merge(keyProvider.apply(hu), husFromTargetWarehouse, (oldList, newList) -> { oldList.addAll(newList); return oldList; }); }); return key2Hus.keySet() .stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), warehouseId -> ProductHUInventory.of(this.productId, key2Hus.get(warehouseId)))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\ProductHUInventory.java
1
请完成以下Java代码
public static GreetingStandardType ofNullableCode(@Nullable final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); return codeNorm != null ? ofCode(codeNorm) : null; } @JsonCreator public static GreetingStandardType ofCode(@NonNull final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); if (codeNorm == null) { throw new AdempiereException("Invalid code: `" + code + "`"); } return cache.computeIfAbsent(codeNorm, GreetingStandardType::new); } @Override @Deprecated public String toString() { return getCode();
} @JsonValue public String getCode() { return code; } @Nullable public static String toCode(@Nullable final GreetingStandardType type) { return type != null ? type.getCode() : null; } public GreetingStandardType composeWith(@NonNull final GreetingStandardType other) { return ofCode(code + "+" + other.code); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\greeting\GreetingStandardType.java
1
请完成以下Java代码
public Optional<String> getLookupTableName() { return Optional.of(modelTableName); } @Override public void cacheInvalidate() { // nothing } @Override public LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public boolean isHighVolume() { return true; } @Override public LookupSource getLookupSourceType() { return LookupSource.lookup; } @Override public boolean hasParameters()
{ return true; } @Override public boolean isNumericKey() { return true; } @Override public Set<String> getDependsOnFieldNames() { return null; } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } @Override public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression() { return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java
1
请完成以下Java代码
private String buildSummaryInfo(final RecordChangeLog changeLog) { final StringBuilder info = new StringBuilder(); // // Created / Created By final UserId createdBy = changeLog.getCreatedByUserId(); final ZonedDateTime createdTS = TimeUtil.asZonedDateTime(changeLog.getCreatedTimestamp()); info.append(" ") .append(msgBL.translate(Env.getCtx(), "CreatedBy")) .append(": ").append(getUserName(createdBy)) .append(" - ").append(convertToDateTimeString(createdTS)).append("\n"); // // Last Changed / Last Changed By if (changeLog.hasChanges()) { final UserId lastChangedBy = changeLog.getLastChangedByUserId(); final ZonedDateTime lastChangedTS = TimeUtil.asZonedDateTime(changeLog.getLastChangedTimestamp()); info.append(" ") .append(msgBL.translate(Env.getCtx(), "UpdatedBy")) .append(": ").append(getUserName(lastChangedBy)) .append(" - ").append(convertToDateTimeString(lastChangedTS)).append("\n"); } // // TableName / RecordId(s) info.append(changeLog.getTableName()) .append(" (").append(changeLog.getRecordId().toInfoString()).append(")"); return info.toString(); } private final String getUserName(@Nullable final UserId userId)
{ if (userId == null) { return "?"; } return userNamesById.computeIfAbsent(userId, usersRepo::retrieveUserFullName); } @Override public void actionPerformed(final ActionEvent e) { dispose(); } // actionPerformed } // RecordInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\RecordInfo.java
1
请完成以下Java代码
public void writeStartTag(HtmlWriteContext context) { writeLeadingWhitespace(context); writeStartTagOpen(context); writeAttributes(context); writeStartTagClose(context); writeEndLine(context); } public void writeContent(HtmlWriteContext context) { if(textContent != null) { writeLeadingWhitespace(context); writeTextContent(context); writeEndLine(context); } } public void writeEndTag(HtmlWriteContext context) { if(!isSelfClosing) { writeLeadingWhitespace(context); writeEndTagElement(context); writeEndLine(context); } } protected void writeEndTagElement(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write("</"); writer.write(tagName); writer.write(">"); } protected void writeTextContent(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write(" "); // add additional whitespace writer.write(textContent); } protected void writeStartTagOpen(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write("<"); writer.write(tagName); } protected void writeAttributes(HtmlWriteContext context) { StringWriter writer = context.getWriter(); for (Entry<String, String> attribute : attributes.entrySet()) { writer.write(" "); writer.write(attribute.getKey()); if(attribute.getValue() != null) { writer.write("=\"");
String attributeValue = escapeQuotes(attribute.getValue()); writer.write(attributeValue); writer.write("\""); } } } protected String escapeQuotes(String attributeValue){ String escapedHtmlQuote = "&quot;"; String escapedJavaQuote = "\""; return attributeValue.replaceAll(escapedJavaQuote, escapedHtmlQuote); } protected void writeEndLine(HtmlWriteContext context) { StringWriter writer = context.getWriter(); writer.write("\n"); } protected void writeStartTagClose(HtmlWriteContext context) { StringWriter writer = context.getWriter(); if(isSelfClosing) { writer.write(" /"); } writer.write(">"); } protected void writeLeadingWhitespace(HtmlWriteContext context) { int stackSize = context.getElementStackSize(); StringWriter writer = context.getWriter(); for (int i = 0; i < stackSize; i++) { writer.write(" "); } } // builder ///////////////////////////////////// public HtmlElementWriter attribute(String name, String value) { attributes.put(name, value); return this; } public HtmlElementWriter textContent(String text) { if(isSelfClosing) { throw new IllegalStateException("Self-closing element cannot have text content."); } this.textContent = text; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlElementWriter.java
1
请完成以下Java代码
protected ScopeImpl getScopeForActivityInstance(ProcessDefinitionImpl processDefinition, ActivityInstance activityInstance) { String scopeId = activityInstance.getActivityId(); if (processDefinition.getId().equals(scopeId)) { return processDefinition; } else { return processDefinition.findActivity(scopeId); } } protected ExecutionEntity getScopeExecutionForActivityInstance(ExecutionEntity processInstance, ActivityExecutionTreeMapping mapping, ActivityInstance activityInstance) { ensureNotNull("activityInstance", activityInstance); ProcessDefinitionImpl processDefinition = processInstance.getProcessDefinition(); ScopeImpl scope = getScopeForActivityInstance(processDefinition, activityInstance); Set<ExecutionEntity> executions = mapping.getExecutions(scope); Set<String> activityInstanceExecutions = new HashSet<String>(Arrays.asList(activityInstance.getExecutionIds())); // TODO: this is a hack around the activity instance tree // remove with fix of CAM-3574 for (String activityInstanceExecutionId : activityInstance.getExecutionIds()) { ExecutionEntity execution = Context.getCommandContext() .getExecutionManager() .findExecutionById(activityInstanceExecutionId); if (execution.isConcurrent() && execution.hasChildren()) { // concurrent executions have at most one child ExecutionEntity child = execution.getExecutions().get(0); activityInstanceExecutions.add(child.getId()); } } // find the scope execution for the given activity instance Set<ExecutionEntity> retainedExecutionsForInstance = new HashSet<ExecutionEntity>(); for (ExecutionEntity execution : executions) { if (activityInstanceExecutions.contains(execution.getId())) { retainedExecutionsForInstance.add(execution); } }
if (retainedExecutionsForInstance.size() != 1) { throw new ProcessEngineException("There are " + retainedExecutionsForInstance.size() + " (!= 1) executions for activity instance " + activityInstance.getId()); } return retainedExecutionsForInstance.iterator().next(); } protected String describeFailure(String detailMessage) { return "Cannot perform instruction: " + describe() + "; " + detailMessage; } protected abstract String describe(); public String toString() { return describe(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractProcessInstanceModificationCommand.java
1
请完成以下Java代码
public final class CustomColNames { private CustomColNames() { } public static final String AD_OrgInfo_REPORT_PREFIX = "ReportPrefix"; public static final String C_BPartner_M_FREIGHTCOST_ID = "M_FreightCost_ID"; /** * This column is used in BankingPA service */ public final static String C_BP_BankAcount_Value = "Value"; /** * ISO-3166 numerical country code */ public static final String C_Country_NUM_COUNTRY_CODE = "NumCountryCode"; public static final String C_Invoice_DESCRIPTION_BOTTOM = "DescriptionBottom"; public static final String C_Invoice_INCOTERM = "Incoterm"; public static final String C_Invoice_INCOTERMLOCATION = "IncotermLocation"; public static final String C_Invoice_ISUSE_BPARTNER_ADDRESS = "IsUseBPartnerAddress"; public static final String C_Invoice_BPARTNERADDRESS = "BPartnerAddress"; public static final String C_Order_C_BP_BANKACCOUNT_ID = "C_BP_BankAccount_ID"; public static final String C_Order_CREATE_NEW_FROM_PROPOSAL = "CreateNewFromProposal"; public static final String C_Order_REF_PROPOSAL_ID = "Ref_Proposal_ID";
public static final String C_Tax_Acct_T_PAYDISCOUNT_EXTP_ACCT = "T_PayDiscount_Exp_Acct"; public static final String C_Tax_Acct_T_PAYDISCOUNT_REV_ACCT = "T_PayDiscount_Rev_Acct"; public static final String C_Tax_Acct_T_REVENUE_ACCT = "T_Revenue_Acct"; public static final String C_Tax_ISTO_EU_LOCATION = "IsToEULocation"; public static final String M_InOutLine_PRODUCT_DESC = "ProductDescription"; public static final String M_Product_Category_C_DOCTYPE_ID = "C_DocType_ID"; public static final String M_Product_Category_ISSUMMARY = "IsSummary"; public static final String T_Replenish_C_Period_ID = "C_Period_ID"; public static final String T_Replenish_TimeToMarket = "TimeToMarket"; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\CustomColNames.java
1