instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ServiceBeanIdConflictProcessor implements MergedBeanDefinitionPostProcessor, DisposableBean, PriorityOrdered { /** * The key is the class names of interfaces that were exported by {@link ServiceBean} * The value is bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Map<String, String> interfaceNamesToBeanNames = new HashMap<>(); /** * Holds the bean names of {@link ServiceBean} or {@link ServiceConfig}. */ private Set<String> conflictedBeanNames = new LinkedHashSet<>(); @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { // Get raw bean type Class<?> rawBeanType = getUserClass(beanType); if (isAssignable(ServiceConfig.class, rawBeanType)) { // ServiceConfig type or sub-type String interfaceName = (String) beanDefinition.getPropertyValues().get("interface"); String mappedBeanName = interfaceNamesToBeanNames.putIfAbsent(interfaceName, beanName); // If mapped bean name exists and does not equal current bean name if (mappedBeanName != null && !mappedBeanName.equals(beanName)) { // conflictedBeanNames will record current bean name. conflictedBeanNames.add(beanName); } } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (conflictedBeanNames.contains(beanName) && bean instanceof ServiceConfig) { ServiceConfig serviceConfig = (ServiceConfig) bean; if (isConflictedServiceConfig(serviceConfig)) { // Set id as the bean name serviceConfig.setId(beanName); } } return bean; } private boolean isConflictedServiceConfig(ServiceConfig serviceConfig) { return Objects.equals(serviceConfig.getId(), serviceConfig.getInterface()); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * Keep the order being higher than {@link CommonAnnotationBeanPostProcessor#getOrder()} that is * {@link Ordered#LOWEST_PRECEDENCE} * * @return {@link Ordered#LOWEST_PRECEDENCE} +1 */ @Override public int getOrder() { return LOWEST_PRECEDENCE + 1; } @Override public void destroy() throws Exception { interfaceNamesToBeanNames.clear(); conflictedBeanNames.clear(); } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\beans\factory\config\ServiceBeanIdConflictProcessor.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) {
if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Foo other = (Foo) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } @Override public String toString() { return "Foo [id=" + id + ", title=" + title + "]"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\restdocopenapi\Foo.java
1
请在Spring Boot框架中完成以下Java代码
public ConfigurationProperty getProperty() { return this.property; } /** * Return the {@link ConfigDataResource} of the invalid property or {@code null} if * the source was not loaded from {@link ConfigData}. * @return the config data location or {@code null} */ public @Nullable ConfigDataResource getLocation() { return this.location; } /** * Return the replacement property that should be used instead or {@code null} if not * replacement is available. * @return the replacement property name */ public @Nullable ConfigurationPropertyName getReplacement() { return this.replacement; } /** * Throw an {@link InvalidConfigDataPropertyException} if the given * {@link ConfigDataEnvironmentContributor} contains any invalid property. * @param contributor the contributor to check */ static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor) { ConfigurationPropertySource propertySource = contributor.getConfigurationPropertySource(); if (propertySource != null) { ERRORS.forEach((name, replacement) -> { ConfigurationProperty property = propertySource.getConfigurationProperty(name); if (property != null) { throw new InvalidConfigDataPropertyException(property, false, replacement, contributor.getResource()); } }); if (contributor.isFromProfileSpecificImport() && !contributor.hasConfigDataOption(ConfigData.Option.IGNORE_PROFILES)) { PROFILE_SPECIFIC_ERRORS.forEach((name) -> { ConfigurationProperty property = propertySource.getConfigurationProperty(name);
if (property != null) { throw new InvalidConfigDataPropertyException(property, true, null, contributor.getResource()); } }); } } } private static String getMessage(ConfigurationProperty property, boolean profileSpecific, @Nullable ConfigurationPropertyName replacement, @Nullable ConfigDataResource location) { StringBuilder message = new StringBuilder("Property '"); message.append(property.getName()); if (location != null) { message.append("' imported from location '"); message.append(location); } message.append("' is invalid"); if (profileSpecific) { message.append(" in a profile specific resource"); } if (replacement != null) { message.append(" and should be replaced with '"); message.append(replacement); message.append("'"); } if (property.getOrigin() != null) { message.append(" [origin: "); message.append(property.getOrigin()); message.append("]"); } return message.toString(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InvalidConfigDataPropertyException.java
2
请在Spring Boot框架中完成以下Java代码
public String getDISCOUNTPERCENT() { return discountpercent; } /** * Sets the value of the discountpercent property. * * @param value * allowed object is * {@link String } * */ public void setDISCOUNTPERCENT(String value) { this.discountpercent = value; } /** * Gets the value of the discountamount property. * * @return * possible object is * {@link String } * */ public String getDISCOUNTAMOUNT() { return discountamount; } /** * Sets the value of the discountamount property. * * @param value * allowed object is * {@link String } * */
public void setDISCOUNTAMOUNT(String value) { this.discountamount = value; } /** * Gets the value of the paymentdesc property. * * @return * possible object is * {@link String } * */ public String getPAYMENTDESC() { return paymentdesc; } /** * Sets the value of the paymentdesc property. * * @param value * allowed object is * {@link String } * */ public void setPAYMENTDESC(String value) { this.paymentdesc = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HPAYT1.java
2
请完成以下Java代码
public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof ModelInterceptor2ModelValidatorWrapper) { final ModelInterceptor2ModelValidatorWrapper wrapper = (ModelInterceptor2ModelValidatorWrapper)obj; return interceptor.equals(wrapper.interceptor); } else if (obj instanceof IModelInterceptor) { final IModelInterceptor interceptor2 = (IModelInterceptor)obj; return interceptor.equals(interceptor2); } return false; } @Override public final void initialize(final ModelValidationEngine engine, final MClient client) { interceptor.initialize(engine, client); } @Override public final int getAD_Client_ID() { return interceptor.getAD_Client_ID(); } @Override public final String modelChange(final PO po, final int changeTypeCode) throws Exception { final ModelChangeType changeType = ModelChangeType.valueOf(changeTypeCode); interceptor.onModelChange(po, changeType); return null; } @Override public final String docValidate(final PO po, final int timingCode) throws Exception { final DocTimingType timing = DocTimingType.valueOf(timingCode);
interceptor.onDocValidate(po, timing); return null; } @Override public final String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); return null; } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { interceptor.onUserLogin(AD_Org_ID, AD_Role_ID, AD_User_ID); } @Override public void beforeLogout(final MFSession session) { if (userLoginListener != null) { userLoginListener.beforeLogout(session); } } @Override public void afterLogout(final MFSession session) { if (userLoginListener != null) { userLoginListener.afterLogout(session); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelInterceptor2ModelValidatorWrapper.java
1
请完成以下Java代码
public Date calculateRemovalTime(HistoricDecisionInstanceEntity historicRootDecisionInstance, DecisionDefinition decisionDefinition) { Integer historyTimeToLive = decisionDefinition.getHistoryTimeToLive(); if (historyTimeToLive != null) { Date evaluationTime = historicRootDecisionInstance.getEvaluationTime(); return determineRemovalTime(evaluationTime, historyTimeToLive); } return null; } public Date calculateRemovalTime(HistoricBatchEntity historicBatch) { String batchOperation = historicBatch.getType(); if (batchOperation != null) { Integer historyTimeToLive = getTTLByBatchOperation(batchOperation); if (historyTimeToLive != null) { if (isBatchRunning(historicBatch)) { Date startTime = historicBatch.getStartTime(); return determineRemovalTime(startTime, historyTimeToLive); } else if (isBatchEnded(historicBatch)) { Date endTime = historicBatch.getEndTime(); return determineRemovalTime(endTime, historyTimeToLive); } } } return null; } protected boolean isBatchRunning(HistoricBatchEntity historicBatch) { return historicBatch.getEndTime() == null; } protected boolean isBatchEnded(HistoricBatchEntity historicBatch) { return historicBatch.getEndTime() != null; }
protected Integer getTTLByBatchOperation(String batchOperation) { return Context.getCommandContext() .getProcessEngineConfiguration() .getParsedBatchOperationsForHistoryCleanup() .get(batchOperation); } protected boolean isProcessInstanceRunning(HistoricProcessInstanceEventEntity historicProcessInstance) { return historicProcessInstance.getEndTime() == null; } protected boolean isProcessInstanceEnded(HistoricProcessInstanceEventEntity historicProcessInstance) { return historicProcessInstance.getEndTime() != null; } public static Date determineRemovalTime(Date initTime, Integer timeToLive) { Calendar removalTime = Calendar.getInstance(); removalTime.setTime(initTime); removalTime.add(Calendar.DATE, timeToLive); return removalTime.getTime(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\DefaultHistoryRemovalTimeProvider.java
1
请完成以下Java代码
protected String getTrxProperyName() { return COLLECTOR_TRXPROPERTYNAME; } @Override protected String extractTrxNameFromItem(@NonNull final TableRecordReference item) { final Object model = item.getModel(Object.class); return InterfaceWrapperHelper.getTrxName(model); } @Override protected List<TableRecordReference> newCollector(@NonNull final TableRecordReference firstItem) {
return new ArrayList<>(); } @Override protected void collectItem(@NonNull final List<TableRecordReference> collector, @NonNull final TableRecordReference item) { collector.add(item); } @Override protected void processCollector(@NonNull final List<TableRecordReference> collector) { trxManager.runInNewTrx(() -> invoiceSyncCreationService.generateIcsAndInvoices(collector)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ilhandler\CreateCandidatesOnCommitCollector.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalConnector { private static final String PATH_BY_ID = "/data/{id}"; private final WebClient webClient; public Mono<String> getData(String stockId) { return webClient.get() .uri(PATH_BY_ID, stockId) .accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(HttpStatusCode::is5xxServerError, response -> Mono.error(new ServiceException("Server error", response.statusCode().value()))) .bodyToMono(String.class) .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)) .filter(throwable -> throwable instanceof ServiceException) .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> { throw new ServiceException("External Service failed to process after max retries", HttpStatus.SERVICE_UNAVAILABLE.value()); })); } public Mono<String> getDataWithRetry(String stockId) { return webClient.get() .uri(PATH_BY_ID, stockId) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(String.class) .retryWhen(Retry.max(3)); } public Mono<String> getDataWithRetryFixedDelay(String stockId) { return webClient.get() .uri(PATH_BY_ID, stockId) .accept(MediaType.APPLICATION_JSON)
.retrieve() .bodyToMono(String.class) .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(2))); } public Mono<String> getDataWithRetryBackoff(String stockId) { return webClient.get() .uri(PATH_BY_ID, stockId) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(String.class) .retryWhen(Retry.backoff(3, Duration.ofSeconds(2))); } public Mono<String> getDataWithRetryBackoffJitter(String stockId) { return webClient.get() .uri(PATH_BY_ID, stockId) .accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(String.class) .retryWhen(Retry.backoff(3, Duration.ofSeconds(2)) .jitter(1)); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\retry\ExternalConnector.java
2
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getUserPassword() { return UserPassword; } public void setUserPassword(String userPassword) { UserPassword = userPassword; }
public String getRoles() { return roles; } public void setRoles(String roles) { this.roles = roles; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\9.PosilkaAdmin\src\main\java\posilka\admin\model\User.java
1
请完成以下Java代码
public class Sentence implements Comparable { /** * 词语id */ private int[] words; /** * 词性 */ private int[] tags; private int[] brownCluster4thPrefix; private int[] brownCluster6thPrefix; private int[] brownClusterFullString; public Sentence(ArrayList<Integer> tokens, ArrayList<Integer> pos, ArrayList<Integer> brownCluster4thPrefix, ArrayList<Integer> brownCluster6thPrefix, ArrayList<Integer> brownClusterFullString) { words = new int[tokens.size()]; tags = new int[tokens.size()]; this.brownCluster4thPrefix = new int[tokens.size()]; this.brownCluster6thPrefix = new int[tokens.size()]; this.brownClusterFullString = new int[tokens.size()]; for (int i = 0; i < tokens.size(); i++) { words[i] = tokens.get(i); tags[i] = pos.get(i); this.brownCluster4thPrefix[i] = brownCluster4thPrefix.get(i); this.brownCluster6thPrefix[i] = brownCluster6thPrefix.get(i); this.brownClusterFullString[i] = brownClusterFullString.get(i); } } public int size() { return words.length; } public int posAt(int position) { if (position == 0) return 0; return tags[position - 1]; } public int[] getWords() { return words; } public int[] getTags() { return tags; } public int[] getBrownCluster4thPrefix() { return brownCluster4thPrefix; } public int[] getBrownCluster6thPrefix() { return brownCluster6thPrefix; } public int[] getBrownClusterFullString() { return brownClusterFullString; } @Override public boolean equals(Object obj) { if (obj instanceof Sentence) { Sentence sentence = (Sentence) obj;
if (sentence.words.length != words.length) return false; for (int i = 0; i < sentence.words.length; i++) { if (sentence.words[i] != words[i]) return false; if (sentence.tags[i] != tags[i]) return false; } return true; } return false; } @Override public int compareTo(Object o) { if (equals(o)) return 0; return hashCode() - o.hashCode(); } @Override public int hashCode() { int hash = 0; for (int tokenId = 0; tokenId < words.length; tokenId++) { hash ^= (words[tokenId] * tags[tokenId]); } return hash; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\structures\Sentence.java
1
请在Spring Boot框架中完成以下Java代码
public void setHistogramFlavor(HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } public int getMaxScale() { return this.maxScale; } public void setMaxScale(int maxScale) { this.maxScale = maxScale; } public int getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(int maxBucketCount) { this.maxBucketCount = maxBucketCount; } public TimeUnit getBaseTimeUnit() { return this.baseTimeUnit; } public void setBaseTimeUnit(TimeUnit baseTimeUnit) { this.baseTimeUnit = baseTimeUnit; } public Map<String, Meter> getMeter() { return this.meter; } /** * Per-meter settings. */ public static class Meter { /** * Maximum number of buckets to be used for exponential histograms, if configured. * This has no effect on explicit bucket histograms. */ private @Nullable Integer maxBucketCount; /**
* Histogram type when histogram publishing is enabled. */ private @Nullable HistogramFlavor histogramFlavor; public @Nullable Integer getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(@Nullable Integer maxBucketCount) { this.maxBucketCount = maxBucketCount; } public @Nullable HistogramFlavor getHistogramFlavor() { return this.histogramFlavor; } public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java
2
请完成以下Java代码
public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getName() { return key; } @Override public String getUsername() { return value; } @Override public String getParentId() { return parentId;
} @Override public void setParentId(String parentId) { this.parentId = parentId; } @Override public Map<String, String> getDetails() { return details; } @Override public void setDetails(Map<String, String> details) { this.details = details; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public static class Pageable { /** * Page index parameter name. */ private String pageParameter = "page"; /** * Page size parameter name. */ private String sizeParameter = "size"; /** * Whether to expose and assume 1-based page number indexes. Defaults to "false", * meaning a page number of 0 in the request equals the first page. */ private boolean oneIndexedParameters; /** * General prefix to be prepended to the page number and page size parameters. */ private String prefix = ""; /** * Delimiter to be used between the qualifier and the actual page number and size * properties. */ private String qualifierDelimiter = "_"; /** * Default page size. */ private int defaultPageSize = 20; /** * Maximum page size to be accepted. */ private int maxPageSize = 2000; /** * Configures how to render Spring Data Pageable instances. */ private PageSerializationMode serializationMode = PageSerializationMode.DIRECT; public String getPageParameter() { return this.pageParameter; } public void setPageParameter(String pageParameter) { this.pageParameter = pageParameter; } public String getSizeParameter() { return this.sizeParameter; } public void setSizeParameter(String sizeParameter) { this.sizeParameter = sizeParameter; } public boolean isOneIndexedParameters() { return this.oneIndexedParameters; } public void setOneIndexedParameters(boolean oneIndexedParameters) { this.oneIndexedParameters = oneIndexedParameters; } public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getQualifierDelimiter() { return this.qualifierDelimiter; } public void setQualifierDelimiter(String qualifierDelimiter) { this.qualifierDelimiter = qualifierDelimiter;
} public int getDefaultPageSize() { return this.defaultPageSize; } public void setDefaultPageSize(int defaultPageSize) { this.defaultPageSize = defaultPageSize; } public int getMaxPageSize() { return this.maxPageSize; } public void setMaxPageSize(int maxPageSize) { this.maxPageSize = maxPageSize; } public PageSerializationMode getSerializationMode() { return this.serializationMode; } public void setSerializationMode(PageSerializationMode serializationMode) { this.serializationMode = serializationMode; } } /** * Sort properties. */ public static class Sort { /** * Sort parameter name. */ private String sortParameter = "sort"; public String getSortParameter() { return this.sortParameter; } public void setSortParameter(String sortParameter) { this.sortParameter = sortParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } } static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory { private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource(); Jsr250MethodSecurityMetadataSource getBean() { this.source.setDefaultRolePrefix(this.rolePrefix); return this.source; } } static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory { private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); DefaultMethodSecurityExpressionHandler getBean() { this.handler.setDefaultRolePrefix(this.rolePrefix); return this.handler; } } abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware { protected String rolePrefix = "ROLE_"; @Override public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException { applicationContext.getBeanProvider(GrantedAuthorityDefaults.class) .ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix()); }
} /** * Delays setting a bean of a given name to be lazyily initialized until after all the * beans are registered. * * @author Rob Winch * @since 3.2 */ private static final class LazyInitBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { private final String beanName; private LazyInitBeanDefinitionRegistryPostProcessor(String beanName) { this.beanName = beanName; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { if (!registry.containsBeanDefinition(this.beanName)) { return; } BeanDefinition beanDefinition = registry.getBeanDefinition(this.beanName); beanDefinition.setLazyInit(true); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\GlobalMethodSecurityBeanDefinitionParser.java
2
请完成以下Java代码
public void patchRow(final IEditableView.RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests) { rowsHolder.changeRowById(ctx.getRowId(), row -> applyChanges(row, fieldChangeRequests)); headerPropertiesHolder.setValue(null); ViewChangesCollector.getCurrentOrAutoflush().collectHeaderPropertiesChanged(ctx.getViewId()); // NOTE: don't need to notify about row changed because that will be returned by the REST call } private static OIRow applyChanges(@NonNull final OIRow row, @NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests) { final OIRow.OIRowBuilder changedRowBuilder = row.toBuilder(); for (final JSONDocumentChangedEvent event : fieldChangeRequests) { event.assertReplaceOperation(); if (OIRow.FIELD_Selected.equals(event.getPath())) { changedRowBuilder.selected(event.getValueAsBoolean(false)); } } return changedRowBuilder.build(); } public void markRowsAsSelected(final DocumentIdsSelection rowIds) {
rowsHolder.changeRowsByIds(rowIds, row -> row.withSelected(true)); headerPropertiesHolder.setValue(null); } public boolean hasSelectedRows() { return rowsHolder.anyMatch(OIRow::isSelected); } public void clearUserInput() { rowsHolder.changeRowsByIds(DocumentIdsSelection.ALL, OIRow::withUserInputCleared); headerPropertiesHolder.setValue(null); } public OIRowUserInputParts getUserInput() {return OIRowUserInputParts.ofStream(rowsHolder.stream());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIViewData.java
1
请完成以下Java代码
public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImagePath() {
return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public Integer getReadSum() { return readSum; } public void setReadSum(Integer readSum) { this.readSum = readSum; } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\News.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue private Long id; private String name; private String email; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) {
this.email = email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(email, user.email); } @Override public int hashCode() { return Objects.hash(id, name, email); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\spring\data\persistence\customrepository\model\User.java
2
请完成以下Java代码
public class SwitchStatement { private static final Logger LOGGER = LoggerFactory.getLogger(SwitchStatement.class); public String exampleOfIF(String animal) { String result; if (animal.equals("DOG") || animal.equals("CAT")) { result = "domestic animal"; } else if (animal.equals("TIGER")) { result = "wild animal"; } else { result = "unknown animal"; } return result; } public String exampleOfSwitch(String animal) { String result; switch (animal) { case "DOG": case "CAT": result = "domestic animal"; break; case "TIGER": result = "wild animal"; break; default: result = "unknown animal"; break; } return result; } public String forgetBreakInSwitch(String animal) { String result;
switch (animal) { case "DOG": LOGGER.debug("domestic animal"); result = "domestic animal"; default: LOGGER.debug("unknown animal"); result = "unknown animal"; } return result; } public String constantCaseValue(String animal) { String result = ""; final String dog = "DOG"; switch (animal) { case dog: result = "domestic animal"; } return result; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\switchstatement\SwitchStatement.java
1
请完成以下Java代码
public class RfqTopicBL implements IRfqTopicBL { @Override public boolean isProductIncluded(final I_C_RfQ_TopicSubscriber subscriber, final int M_Product_ID) { final List<I_C_RfQ_TopicSubscriberOnly> restrictions = Services.get(IRfqTopicDAO.class).retrieveRestrictions(subscriber); // No restrictions if (restrictions.isEmpty()) { return true; } for (final I_C_RfQ_TopicSubscriberOnly restriction : restrictions) { if (!restriction.isActive()) { continue; } // Product if (restriction.getM_Product_ID() == M_Product_ID) {
return true; } // Product Category if (Services.get(IProductBL.class).isProductInCategory(ProductId.ofRepoIdOrNull(M_Product_ID), ProductCategoryId.ofRepoIdOrNull(restriction.getM_Product_Category_ID()))) { return true; } } // must be on "positive" list return false; } // isIncluded }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqTopicBL.java
1
请在Spring Boot框架中完成以下Java代码
public final class ServletWebSecurityAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnBean(DispatcherServletPath.class) @ConditionalOnClass(DispatcherServletPath.class) static class PathPatternRequestMatcherBuilderConfiguration { @Bean @ConditionalOnMissingBean PathPatternRequestMatcher.Builder pathPatternRequestMatcherBuilder( DispatcherServletPath dispatcherServletPath) { PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults(); String path = dispatcherServletPath.getPath(); return (!path.equals("/")) ? builder.basePath(path) : builder; } } /** * The default configuration for web security. It relies on Spring Security's * content-negotiation strategy to determine what sort of authentication to use. If * the user specifies their own {@link SecurityFilterChain} bean, this will back-off * completely and the users should specify all the bits that they want to configure as * part of the custom security configuration. */ @Configuration(proxyBeanMethods = false) @ConditionalOnDefaultWebSecurity static class SecurityFilterChainConfiguration { @Bean @Order(SecurityFilterProperties.BASIC_AUTH_ORDER) SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) { http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
http.formLogin(withDefaults()); http.httpBasic(withDefaults()); return http.build(); } } /** * Adds the {@link EnableWebSecurity @EnableWebSecurity} annotation if Spring Security * is on the classpath. This will make sure that the annotation is present with * default security auto-configuration and also if the user adds custom security and * forgets to add the annotation. If {@link EnableWebSecurity @EnableWebSecurity} has * already been added or if a bean with name * {@value BeanIds#SPRING_SECURITY_FILTER_CHAIN} has been configured by the user, this * will back-off. */ @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN) @ConditionalOnClass(EnableWebSecurity.class) @EnableWebSecurity static class EnableWebSecurityConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\ServletWebSecurityAutoConfiguration.java
2
请完成以下Java代码
public int getC_Payment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Line No. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Line No. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Datensatz verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo); } return false; } /** Set Referenznummer. @param ReferenceNo Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public void setReferenceNo (java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } /** Get Referenznummer. @return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner */ @Override public java.lang.String getReferenceNo () { return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo); } /** Set Bewegungs-Betrag. @param TrxAmt Betrag einer Transaktion */ @Override public void setTrxAmt (java.math.BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } /** Get Bewegungs-Betrag. @return Betrag einer Transaktion */ @Override public java.math.BigDecimal getTrxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TrxAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_BankStatementLine_Ref.java
1
请完成以下Java代码
public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setTextMsg (final java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } @Override public java.lang.String getTextMsg() { return get_ValueAsString(COLUMNNAME_TextMsg);
} /** * WFState AD_Reference_ID=305 * Reference name: WF_Instance State */ public static final int WFSTATE_AD_Reference_ID=305; /** NotStarted = ON */ public static final String WFSTATE_NotStarted = "ON"; /** Running = OR */ public static final String WFSTATE_Running = "OR"; /** Suspended = OS */ public static final String WFSTATE_Suspended = "OS"; /** Completed = CC */ public static final String WFSTATE_Completed = "CC"; /** Aborted = CA */ public static final String WFSTATE_Aborted = "CA"; /** Terminated = CT */ public static final String WFSTATE_Terminated = "CT"; @Override public void setWFState (final java.lang.String WFState) { set_Value (COLUMNNAME_WFState, WFState); } @Override public java.lang.String getWFState() { return get_ValueAsString(COLUMNNAME_WFState); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Activity.java
1
请在Spring Boot框架中完成以下Java代码
public String getIsDeliveryClosed() { return isDeliveryClosed; } /** * Sets the value of the isDeliveryClosed property. * * @param value * allowed object is * {@link String } * */ public void setIsDeliveryClosed(String value) { this.isDeliveryClosed = value; } /** * Gets the value of the gtincu property. * * @return * possible object is * {@link String } * */ public String getGTINCU() { return gtincu; } /** * Sets the value of the gtincu property. * * @param value * allowed object is * {@link String } * */ public void setGTINCU(String value) { this.gtincu = value;
} /** * Gets the value of the gtintu property. * * @return * possible object is * {@link String } * */ public String getGTINTU() { return gtintu; } /** * Sets the value of the gtintu property. * * @param value * allowed object is * {@link String } * */ public void setGTINTU(String value) { this.gtintu = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EXPMInOutDesadvLineVType.java
2
请完成以下Java代码
private List<OLCandCreateRequest> toOLCandCreateRequestsList(final MSV3OrderSyncRequest request) { final IProductDAO productDAO = Services.get(IProductDAO.class); final IProductBL productBL = Services.get(IProductBL.class); final IInputDataSourceDAO inputDataSourceDAO = Services.get(IInputDataSourceDAO.class); // final OrderResponse order = request.getOrder(); final String poReference = request.getOrderId().getValueAsString(); final LocalDate dateRequired = LocalDate.now().plusDays(1); // TODO final List<OLCandCreateRequest> olCandRequests = new ArrayList<>(); for (final MSV3OrderSyncRequestPackage orderPackage : request.getOrderPackages()) { for (final MSV3OrderSyncRequestPackageItem item : orderPackage.getItems()) { final ProductId productId = productDAO.retrieveProductIdByValue(item.getPzn().getValueAsString()); final UomId uomId = productBL.getStockUOMId(productId); final int huPIItemProductId = -1; // TODO fetch it from item.getPackingMaterialId() olCandRequests.add(OLCandCreateRequest.builder() .externalLineId(item.getId().getValueAsString()) // .bpartner(toOLCandBPartnerInfo(request.getBpartner())) .poReference(poReference) // .dateRequired(dateRequired) // .productId(productId) .qty(item.getQty().getValueAsBigDecimal()) .uomId(uomId) .huPIItemProductId(huPIItemProductId) .dataSourceId(inputDataSourceDAO.retrieveInputDataSourceIdByInternalName(DATA_SOURCE_INTERNAL_NAME)) .dataDestId(inputDataSourceDAO.retrieveInputDataSourceIdByInternalName(OrderCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME)) .build());
} } return olCandRequests; } private static BPartnerInfo toOLCandBPartnerInfo(final BPartnerId bpartnerId) { if (bpartnerId == null) { return null; } final de.metas.bpartner.BPartnerId bPartnerId = de.metas.bpartner.BPartnerId.ofRepoIdOrNull(bpartnerId.getBpartnerId()); final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull(bPartnerId, bpartnerId.getBpartnerLocationId()); return BPartnerInfo.builder() .bpartnerId(bPartnerId) .bpartnerLocationId(bPartnerLocationId) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\listeners\OrderCreateRequestRabbitMQListener.java
1
请完成以下Java代码
public void setDocumentNo (final @Nullable java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return get_ValueAsString(COLUMNNAME_DocumentNo); } @Override public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setIsHUDestroyed (final boolean IsHUDestroyed) { set_Value (COLUMNNAME_IsHUDestroyed, IsHUDestroyed); } @Override public boolean isHUDestroyed() { return get_ValueAsBoolean(COLUMNNAME_IsHUDestroyed); } @Override public org.compiere.model.I_M_ChangeNotice getM_ChangeNotice() { return get_ValueAsPO(COLUMNNAME_M_ChangeNotice_ID, org.compiere.model.I_M_ChangeNotice.class); } @Override public void setM_ChangeNotice(final org.compiere.model.I_M_ChangeNotice M_ChangeNotice) { set_ValueFromPO(COLUMNNAME_M_ChangeNotice_ID, org.compiere.model.I_M_ChangeNotice.class, M_ChangeNotice); } @Override public void setM_ChangeNotice_ID (final int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_Value (COLUMNNAME_M_ChangeNotice_ID, null); else set_Value (COLUMNNAME_M_ChangeNotice_ID, M_ChangeNotice_ID); } @Override public int getM_ChangeNotice_ID() { return get_ValueAsInt(COLUMNNAME_M_ChangeNotice_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); }
@Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistribution.java
1
请在Spring Boot框架中完成以下Java代码
public class C_OrderLine { private final OrderCostService orderCostService; public C_OrderLine( @NonNull final OrderCostService orderCostService) { this.orderCostService = orderCostService; } @NonNull private static OrderAndLineId extractOrderAndLineId(final I_C_OrderLine record) {return OrderAndLineId.ofRepoIds(record.getC_Order_ID(), record.getC_OrderLine_ID());} @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE) public void onBeforeChange(final I_C_OrderLine record) { final OrderCostDetailOrderLinePart orderLineInfo = extractOrderLineInfoIfHasChanges(record); if (orderLineInfo != null) { orderCostService.updateOrderCostsOnOrderLineChanged(orderLineInfo); } } @Nullable private static OrderCostDetailOrderLinePart extractOrderLineInfoIfHasChanges(final I_C_OrderLine record) { final I_C_OrderLine recordBeforeChanges = InterfaceWrapperHelper.createOld(record, I_C_OrderLine.class); final OrderCostDetailOrderLinePart lineInfoBeforeChanges = OrderCostDetailOrderLinePart.ofOrderLine(recordBeforeChanges);
final OrderCostDetailOrderLinePart lineInfo = OrderCostDetailOrderLinePart.ofOrderLine(record); if (lineInfo.equals(lineInfoBeforeChanges)) { return null; // no changes } return lineInfo; } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void onBeforeDelete(final I_C_OrderLine record) { if (InterfaceWrapperHelper.isUIAction(record)) { orderCostService.deleteByCreatedOrderLineId(extractOrderAndLineId(record)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\interceptor\C_OrderLine.java
2
请完成以下Java代码
public String getFailedActivityId() { return failedActivityId; } public String getCauseIncidentId() { return causeIncidentId; } public String getRootCauseIncidentId() { return rootCauseIncidentId; } public String getConfiguration() { return configuration; } public String getIncidentMessage() { return incidentMessage; } public String getTenantId() { return tenantId; } public String getJobDefinitionId() { return jobDefinitionId; } public String getAnnotation() { return annotation; } public static IncidentDto fromIncident(Incident incident) { IncidentDto dto = new IncidentDto(); dto.id = incident.getId(); dto.processDefinitionId = incident.getProcessDefinitionId(); dto.processInstanceId = incident.getProcessInstanceId();
dto.executionId = incident.getExecutionId(); dto.incidentTimestamp = incident.getIncidentTimestamp(); dto.incidentType = incident.getIncidentType(); dto.activityId = incident.getActivityId(); dto.failedActivityId = incident.getFailedActivityId(); dto.causeIncidentId = incident.getCauseIncidentId(); dto.rootCauseIncidentId = incident.getRootCauseIncidentId(); dto.configuration = incident.getConfiguration(); dto.incidentMessage = incident.getIncidentMessage(); dto.tenantId = incident.getTenantId(); dto.jobDefinitionId = incident.getJobDefinitionId(); dto.annotation = incident.getAnnotation(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\IncidentDto.java
1
请完成以下Java代码
public final class OAuth2TokenClaimNames { /** * {@code iss} - the Issuer claim identifies the principal that issued the OAuth 2.0 * Token */ public static final String ISS = "iss"; /** * {@code sub} - the Subject claim identifies the principal that is the subject of the * OAuth 2.0 Token */ public static final String SUB = "sub"; /** * {@code aud} - the Audience claim identifies the recipient(s) that the OAuth 2.0 * Token is intended for */ public static final String AUD = "aud"; /** * {@code exp} - the Expiration time claim identifies the expiration time on or after * which the OAuth 2.0 Token MUST NOT be accepted for processing */ public static final String EXP = "exp"; /** * {@code nbf} - the Not Before claim identifies the time before which the OAuth 2.0 * Token MUST NOT be accepted for processing */ public static final String NBF = "nbf";
/** * {@code iat} - The Issued at claim identifies the time at which the OAuth 2.0 Token * was issued */ public static final String IAT = "iat"; /** * {@code jti} - The ID claim provides a unique identifier for the OAuth 2.0 Token */ public static final String JTI = "jti"; private OAuth2TokenClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimNames.java
1
请完成以下Java代码
public void writeComment(String data) throws XMLStreamException { writer.writeComment(data); } public void writeProcessingInstruction(String target) throws XMLStreamException { writer.writeProcessingInstruction(target); } public void writeProcessingInstruction(String target, String data) throws XMLStreamException { writer.writeProcessingInstruction(target, data); } public void writeCData(String data) throws XMLStreamException { writer.writeCData(data); } public void writeDTD(String dtd) throws XMLStreamException { writer.writeDTD(dtd); } public void writeEntityRef(String name) throws XMLStreamException { writer.writeEntityRef(name); } public void writeStartDocument() throws XMLStreamException { writer.writeStartDocument(); } public void writeStartDocument(String version) throws XMLStreamException { writer.writeStartDocument(version); } public void writeStartDocument(String encoding, String version) throws XMLStreamException { writer.writeStartDocument(encoding, version); } public void writeCharacters(String text) throws XMLStreamException {
writer.writeCharacters(text); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { writer.writeCharacters(text, start, len); } public String getPrefix(String uri) throws XMLStreamException { return writer.getPrefix(uri); } public void setPrefix(String prefix, String uri) throws XMLStreamException { writer.setPrefix(prefix, uri); } public void setDefaultNamespace(String uri) throws XMLStreamException { writer.setDefaultNamespace(uri); } public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { writer.setNamespaceContext(context); } public NamespaceContext getNamespaceContext() { return writer.getNamespaceContext(); } public Object getProperty(String name) throws IllegalArgumentException { return writer.getProperty(name); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\DelegatingXMLStreamWriter.java
1
请完成以下Java代码
public String getCamundaPriority() { return camundaPriorityAttribute.getValue(this); } public void setCamundaPriority(String camundaPriority) { camundaPriorityAttribute.setValue(this, camundaPriority); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(HumanTask.class, CMMN_ELEMENT_HUMAN_TASK) .namespaceUri(CMMN11_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<HumanTask>() { public HumanTask newInstance(ModelTypeInstanceContext instanceContext) { return new HumanTaskImpl(instanceContext); } }); performerRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PERFORMER_REF) .idAttributeReference(Role.class) .build(); /** camunda extensions */ camundaAssigneeAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ASSIGNEE) .namespace(CAMUNDA_NS) .build(); camundaCandidateGroupsAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_GROUPS) .namespace(CAMUNDA_NS) .build(); camundaCandidateUsersAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_USERS)
.namespace(CAMUNDA_NS) .build(); camundaDueDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DUE_DATE) .namespace(CAMUNDA_NS) .build(); camundaFollowUpDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FOLLOW_UP_DATE) .namespace(CAMUNDA_NS) .build(); camundaFormKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FORM_KEY) .namespace(CAMUNDA_NS) .build(); camundaPriorityAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PRIORITY) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); planningTableCollection = sequenceBuilder.elementCollection(PlanningTable.class) .build(); planningTableChild = sequenceBuilder.element(PlanningTable.class) .minOccurs(0) .maxOccurs(1) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\HumanTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable FieldNamingPolicy getFieldNamingPolicy() { return this.fieldNamingPolicy; } public void setFieldNamingPolicy(@Nullable FieldNamingPolicy fieldNamingPolicy) { this.fieldNamingPolicy = fieldNamingPolicy; } public @Nullable Boolean getPrettyPrinting() { return this.prettyPrinting; } public void setPrettyPrinting(@Nullable Boolean prettyPrinting) { this.prettyPrinting = prettyPrinting; } public @Nullable Strictness getStrictness() { return this.strictness; } public void setStrictness(@Nullable Strictness strictness) { this.strictness = strictness; } public void setLenient(@Nullable Boolean lenient) { setStrictness((lenient != null && lenient) ? Strictness.LENIENT : Strictness.STRICT); } public @Nullable Boolean getDisableHtmlEscaping() { return this.disableHtmlEscaping; } public void setDisableHtmlEscaping(@Nullable Boolean disableHtmlEscaping) { this.disableHtmlEscaping = disableHtmlEscaping; } public @Nullable String getDateFormat() { return this.dateFormat; } public void setDateFormat(@Nullable String dateFormat) { this.dateFormat = dateFormat; } /** * Enumeration of levels of strictness. Values are the same as those on
* {@link com.google.gson.Strictness} that was introduced in Gson 2.11. To maximize * backwards compatibility, the Gson enum is not used directly. */ public enum Strictness { /** * Lenient compliance. */ LENIENT, /** * Strict compliance with some small deviations for legacy reasons. */ LEGACY_STRICT, /** * Strict compliance. */ STRICT } }
repos\spring-boot-4.0.1\module\spring-boot-gson\src\main\java\org\springframework\boot\gson\autoconfigure\GsonProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class DubboRelaxedBinding2AutoConfiguration { public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) { ConfigurableEnvironment propertyResolver = new AbstractEnvironment() { @Override protected void customizePropertySources(MutablePropertySources propertySources) { Map<String, Object> dubboScanProperties = getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX); propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties)); } }; ConfigurationPropertySources.attach(propertyResolver); return propertyResolver; } /** * The bean is used to scan the packages of Dubbo Service classes * * @param environment {@link Environment} instance * @return non-null {@link Set} * @since 2.7.8
*/ @ConditionalOnMissingBean(name = BASE_PACKAGES_BEAN_NAME) @Bean(name = BASE_PACKAGES_BEAN_NAME) public Set<String> dubboBasePackages(ConfigurableEnvironment environment) { PropertyResolver propertyResolver = dubboScanBasePackagesPropertyResolver(environment); return propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet()); } @ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class) @Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME) @Scope(scopeName = SCOPE_PROTOTYPE) public ConfigurationBeanBinder relaxedDubboConfigBinder() { return new BinderDubboConfigBinder(); } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboRelaxedBinding2AutoConfiguration.java
2
请完成以下Java代码
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } protected MigrationBatchConfigurationJsonConverter getJsonConverterInstance() { return MigrationBatchConfigurationJsonConverter.INSTANCE; } @Override protected MigrationBatchConfiguration createJobConfiguration(MigrationBatchConfiguration configuration, List<String> processIdsForJob) { return new MigrationBatchConfiguration( processIdsForJob, configuration.getMigrationPlan(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.getBatchId() ); } @Override protected void postProcessJob(MigrationBatchConfiguration configuration, JobEntity job, MigrationBatchConfiguration jobConfiguration) { if (job.getDeploymentId() == null) { CommandContext commandContext = Context.getCommandContext(); String sourceProcessDefinitionId = configuration.getMigrationPlan().getSourceProcessDefinitionId(); ProcessDefinitionEntity processDefinition = getProcessDefinition(commandContext, sourceProcessDefinitionId); job.setDeploymentId(processDefinition.getDeploymentId()); } } @Override public void executeHandler(MigrationBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { MigrationPlanImpl migrationPlan = (MigrationPlanImpl) batchConfiguration.getMigrationPlan(); String batchId = batchConfiguration.getBatchId(); setVariables(batchId, migrationPlan, commandContext);
MigrationPlanExecutionBuilder executionBuilder = commandContext.getProcessEngineConfiguration() .getRuntimeService() .newMigration(migrationPlan) .processInstanceIds(batchConfiguration.getIds()); if (batchConfiguration.isSkipCustomListeners()) { executionBuilder.skipCustomListeners(); } if (batchConfiguration.isSkipIoMappings()) { executionBuilder.skipIoMappings(); } commandContext.executeWithOperationLogPrevented( new MigrateProcessInstanceCmd((MigrationPlanExecutionBuilderImpl)executionBuilder, true)); } protected void setVariables(String batchId, MigrationPlanImpl migrationPlan, CommandContext commandContext) { Map<String, ?> variables = null; if (batchId != null) { variables = VariableUtil.findBatchVariablesSerialized(batchId, commandContext); if (variables != null) { migrationPlan.setVariables(new VariableMapImpl(new HashMap<>(variables))); } } } protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) { return commandContext.getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\batch\MigrationBatchJobHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void setC_POS_Payment(final de.metas.pos.repository.model.I_C_POS_Payment C_POS_Payment) { set_ValueFromPO(COLUMNNAME_C_POS_Payment_ID, de.metas.pos.repository.model.I_C_POS_Payment.class, C_POS_Payment); } @Override public void setC_POS_Payment_ID (final int C_POS_Payment_ID) { if (C_POS_Payment_ID < 1) set_Value (COLUMNNAME_C_POS_Payment_ID, null); else set_Value (COLUMNNAME_C_POS_Payment_ID, C_POS_Payment_ID); } @Override public int getC_POS_Payment_ID() { return get_ValueAsInt(COLUMNNAME_C_POS_Payment_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); }
/** * Type AD_Reference_ID=541892 * Reference name: C_POS_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=541892; /** CashPayment = CASH_PAY */ public static final String TYPE_CashPayment = "CASH_PAY"; /** CardPayment = CARD_PAY */ public static final String TYPE_CardPayment = "CARD_PAY"; /** CashInOut = CASH_INOUT */ public static final String TYPE_CashInOut = "CASH_INOUT"; /** CashClosingDifference = CASH_DIFF */ public static final String TYPE_CashClosingDifference = "CASH_DIFF"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java
2
请完成以下Java代码
public int getSetupTimeReal() { return get_ValueAsInt(COLUMNNAME_SetupTimeReal); } @Override public void setSetupTimeRequiered (final int SetupTimeRequiered) { set_Value (COLUMNNAME_SetupTimeRequiered, SetupTimeRequiered); } @Override public int getSetupTimeRequiered() { return get_ValueAsInt(COLUMNNAME_SetupTimeRequiered); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWaitingTime (final int WaitingTime)
{ set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public int getWaitingTime() { return get_ValueAsInt(COLUMNNAME_WaitingTime); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() { return get_ValueAsInt(COLUMNNAME_Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node.java
1
请完成以下Java代码
public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) { Headers headers = new RecordHeaders(); headers.add("traceId", UUID.randomUUID().toString().getBytes(Charset.forName("UTF8"))); // 修改消息 return new ProducerRecord<>(record.topic(), record.partition(), record.key(), record.value(), headers); } /** * 该方法会在消息从 RecordAccumulator 成功发送到 Kafka Broker 之后,或者在发送过程 中失败时调用。 * 并且通常都是在 producer 回调逻辑触发之前调用。 * onAcknowledgement 运行在 producer 的 IO 线程中,因此不要在该方法中放入很重的逻辑,否则会拖慢 producer 的消息 发送效率。 * * @param metadata * @param exception */
@Override public void onAcknowledgement(RecordMetadata metadata, Exception exception) { if (Objects.isNull(exception)) { // TODO 出错了 } } /** * 关闭 interceptor,主要用于执行一些资源清理工作,只调用一次 */ @Override public void close() { System.out.println("==========close============"); } }
repos\spring-boot-student-master\spring-boot-student-kafka\src\main\java\com\xiaolyuh\interceptor\TraceInterceptor.java
1
请完成以下Java代码
public class Foo implements Serializable { private long id; private String name; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } // API public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } // @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false;
} if (getClass() != obj.getClass()) { return false; } final Foo other = (Foo) obj; if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Foo [name=") .append(name) .append("]"); return builder.toString(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\dto\Foo.java
1
请完成以下Java代码
public static List<List<Integer>> combinations(List<Integer> inputSet, int k) { List<List<Integer>> results = new ArrayList<>(); combinationsInternal(inputSet, k, results, new ArrayList<>(), 0); return results; } private static void combinationsInternal( List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) { int leftToAccumulate = k - accumulator.size(); int possibleToAcculumate = inputSet.size() - index; if (accumulator.size() == k) { results.add(new ArrayList<>(accumulator)); } else if (leftToAccumulate <= possibleToAcculumate) { combinationsInternal(inputSet, k, results, accumulator, index + 1); accumulator.add(inputSet.get(index)); combinationsInternal(inputSet, k, results, accumulator, index + 1); accumulator.remove(accumulator.size() - 1); } } public static List<List<Character>> powerSet(List<Character> sequence) { List<List<Character>> results = new ArrayList<>(); powerSetInternal(sequence, results, new ArrayList<>(), 0); return results;
} private static void powerSetInternal( List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) { if (index == set.size()) { powerSet.add(new ArrayList<>(accumulator)); } else { accumulator.add(set.get(index)); powerSetInternal(set, powerSet, accumulator, index + 1); accumulator.remove(accumulator.size() - 1); powerSetInternal(set, powerSet, accumulator, index + 1); } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-5\src\main\java\com\baeldung\algorithms\combinatorics\Combinatorics.java
1
请完成以下Java代码
public void init() { Faker faker = new Faker(Locale.ENGLISH); final com.github.javafaker.Book book = faker.book(); this.items = IntStream.range(1, faker.random() .nextInt(10, 20)) .mapToObj(i -> new Book(i, book.title(), book.author(), book.genre())) .collect(Collectors.toList()); } public int getCount() { return items.size(); } public List<Book> getItems() { return items; }
public Optional<Book> getById(int id) { return this.items.stream() .filter(item -> id == item.getId()) .findFirst(); } public void save(int id, Book book) { IntStream.range(0, items.size()) .filter(i -> items.get(i) .getId() == id) .findFirst() .ifPresent(i -> this.items.set(i, book)); } }
repos\tutorials-master\spring-web-modules\spring-5-mvc\src\main\java\com\baeldung\idc\BookRepository.java
1
请完成以下Java代码
public int getC_DunningLevel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningLevel_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dunning Run. @param C_DunningRun_ID Dunning Run */ public void setC_DunningRun_ID (int C_DunningRun_ID) { if (C_DunningRun_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DunningRun_ID, Integer.valueOf(C_DunningRun_ID)); } /** Get Dunning Run. @return Dunning Run */ public int getC_DunningRun_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningRun_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 Dunning Date. @param DunningDate Date of Dunning */ public void setDunningDate (Timestamp DunningDate) { set_Value (COLUMNNAME_DunningDate, DunningDate); } /** Get Dunning Date. @return Date of Dunning */ public Timestamp getDunningDate () { return (Timestamp)get_Value(COLUMNNAME_DunningDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getDunningDate())); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed
*/ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Send. @param SendIt Send */ public void setSendIt (String SendIt) { set_Value (COLUMNNAME_SendIt, SendIt); } /** Get Send. @return Send */ public String getSendIt () { return (String)get_Value(COLUMNNAME_SendIt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningRun.java
1
请完成以下Java代码
private String message() { return "This is a Local Class within if clause"; } } Local local = new Local(); return local.message(); } else return "Welcome to " + name; } // Anonymous Inner class extending a class public String greet() { Outer anonymous = new Outer() { @Override public String greet() { return "Running Anonymous Class..."; } }; return anonymous.greet(); } // Anonymous inner class implementing an interface public String greet(String name) { HelloWorld helloWorld = new HelloWorld() { @Override public String greet(String name) { return "Welcome to " + name; } }; return helloWorld.greet(name); } // Anonymous inner class implementing nested interface public String greetSomeone(String name) { HelloSomeone helloSomeOne = new HelloSomeone() { @Override public String greet(String name) { return "Hello " + name; } }; return helloSomeOne.greet(name); } // Nested interface within a class interface HelloOuter { public String hello(String name); } // Enum within a class enum Color { RED, GREEN, BLUE; } } interface HelloWorld { public String greet(String name); // Nested class within an interface class InnerClass implements HelloWorld { @Override public String greet(String name) {
return "Inner class within an interface"; } } // Nested interface within an interfaces interface HelloSomeone { public String greet(String name); } // Enum within an interface enum Directon { NORTH, SOUTH, EAST, WEST; } } enum Level { LOW, MEDIUM, HIGH; } enum Foods { DRINKS, EATS; // Enum within Enum enum DRINKS { APPLE_JUICE, COLA; } enum EATS { POTATO, RICE; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\classfile\Outer.java
1
请完成以下Java代码
private Integer getAttributeValueIdOrSpecialCodeOrNull() { if (type == AttributeKeyPartType.AttributeValueId) { return attributeValueId.getRepoId(); } else if (type == AttributeKeyPartType.All || type == AttributeKeyPartType.Other || type == AttributeKeyPartType.None) { return specialCode; } else { return null; } } private Integer getAttributeIdOrNull() { return AttributeKeyPartType.AttributeIdAndValue == type ? attributeId.getRepoId() : null; } private static int compareNullsLast(final Integer i1, final Integer i2)
{ if (i1 == null) { return +1; } else if (i2 == null) { return -1; } else { return i1 - i2; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKeyPart.java
1
请完成以下Java代码
public Builder addDetail(@Nullable final DocumentLayoutDetailDescriptor detail) { if (detail == null) { return this; } if (detail.isEmpty()) { logger.trace("Skip adding detail to layout because it is empty; detail={}", detail); return this; } details.add(detail); return this; } public Builder setSideListView(final ViewLayout sideListViewLayout) { this._sideListView = sideListViewLayout; return this; } private ViewLayout getSideList() { Preconditions.checkNotNull(_sideListView, "sideList"); return _sideListView;
} public Builder putDebugProperty(final String name, final String value) { debugProperties.put(name, value); return this; } public Builder setStopwatch(final Stopwatch stopwatch) { this.stopwatch = stopwatch; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public List<SysPermissionDataRule> getPermRuleListByDeptIdAndPermId(String departId, String permissionId) { SysDepartPermission departPermission = this.getOne(new QueryWrapper<SysDepartPermission>().lambda().eq(SysDepartPermission::getDepartId, departId).eq(SysDepartPermission::getPermissionId, permissionId)); if(departPermission != null && oConvertUtils.isNotEmpty(departPermission.getDataRuleIds())){ LambdaQueryWrapper<SysPermissionDataRule> query = new LambdaQueryWrapper<SysPermissionDataRule>(); query.in(SysPermissionDataRule::getId, Arrays.asList(departPermission.getDataRuleIds().split(","))); query.orderByDesc(SysPermissionDataRule::getCreateTime); List<SysPermissionDataRule> permRuleList = this.ruleMapper.selectList(query); return permRuleList; }else{ return null; } } /** * 从diff中找出main中没有的元素 * @param main * @param diff * @return */ private List<String> getDiff(String main,String diff){ if(oConvertUtils.isEmpty(diff)) { return null;
} if(oConvertUtils.isEmpty(main)) { return Arrays.asList(diff.split(",")); } String[] mainArr = main.split(","); String[] diffArr = diff.split(","); Map<String, Integer> map = new HashMap(5); for (String string : mainArr) { map.put(string, 1); } List<String> res = new ArrayList<String>(); for (String key : diffArr) { if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) { res.add(key); } } return res; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartPermissionServiceImpl.java
2
请完成以下Java代码
public void setPosted (final boolean Posted) { set_Value (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); }
@Override public org.compiere.model.I_S_TimeExpenseLine getS_TimeExpenseLine() { return get_ValueAsPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class); } @Override public void setS_TimeExpenseLine(final org.compiere.model.I_S_TimeExpenseLine S_TimeExpenseLine) { set_ValueFromPO(COLUMNNAME_S_TimeExpenseLine_ID, org.compiere.model.I_S_TimeExpenseLine.class, S_TimeExpenseLine); } @Override public void setS_TimeExpenseLine_ID (final int S_TimeExpenseLine_ID) { if (S_TimeExpenseLine_ID < 1) set_Value (COLUMNNAME_S_TimeExpenseLine_ID, null); else set_Value (COLUMNNAME_S_TimeExpenseLine_ID, S_TimeExpenseLine_ID); } @Override public int getS_TimeExpenseLine_ID() { return get_ValueAsInt(COLUMNNAME_S_TimeExpenseLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectIssue.java
1
请完成以下Java代码
static Builder newBuilder() { return new Builder(); } /** * Standard Builder to create the Arbiter. */ static final class Builder implements org.apache.logging.log4j.core.util.Builder<SpringProfileArbiter> { private static final Logger statusLogger = StatusLogger.getLogger(); @PluginBuilderAttribute @SuppressWarnings("NullAway.Init") private String name; @PluginConfiguration @SuppressWarnings("NullAway.Init") private Configuration configuration; @PluginLoggerContext @SuppressWarnings("NullAway.Init") private LoggerContext loggerContext; private Builder() { } /** * Sets the profile name or expression. * @param name the profile name or expression * @return this * @see Profiles#of(String...) */ public Builder setName(String name) { this.name = name; return this;
} @Override public SpringProfileArbiter build() { Environment environment = Log4J2LoggingSystem.getEnvironment(this.loggerContext); if (environment == null) { statusLogger.debug("Creating Arbiter without a Spring Environment"); } String name = this.configuration.getStrSubstitutor().replace(this.name); String[] profiles = trimArrayElements(StringUtils.commaDelimitedListToStringArray(name)); return new SpringProfileArbiter(environment, profiles); } // The array has no nulls in it, but StringUtils.trimArrayElements return // @Nullable String[] @SuppressWarnings("NullAway") private String[] trimArrayElements(String[] array) { return StringUtils.trimArrayElements(array); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\SpringProfileArbiter.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public Blob getAvatar() { return avatar; } public void setAvatar(Blob avatar) { this.avatar = avatar; } public Clob getBiography() { return biography; } public void setBiography(Clob biography) { this.biography = biography; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootMappingLobToClobAndBlob\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public Collection<Object> values() { return variableScope.getVariables().values(); } @Override public void putAll(Map<? extends String, ? extends Object> toMerge) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return defaultBindings.remove(key); } @Override public void clear() { throw new UnsupportedOperationException();
} @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } public void addUnstoredKey(String unstoredKey) { UNSTORED_KEYS.add(unstoredKey); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\scripting\ScriptBindings.java
1
请完成以下Java代码
public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validierungscode. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Mandatory Parameters. @param IsManadatoryParams Mandatory Parameters */ @Override public void setIsManadatoryParams (boolean IsManadatoryParams) { set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams)); } /** Get Mandatory Parameters. @return Mandatory Parameters */ @Override public boolean isManadatoryParams () { Object oo = get_Value(COLUMNNAME_IsManadatoryParams); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Display All Parameters. @param IsShowAllParams Display All Parameters */ @Override public void setIsShowAllParams (boolean IsShowAllParams) { set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams)); } /** Get Display All Parameters. @return Display All Parameters */ @Override
public boolean isShowAllParams () { Object oo = get_Value(COLUMNNAME_IsShowAllParams); 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 */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
1
请完成以下Java代码
private Amount extractStatementLineAmt(final I_C_BankStatementLine record) { final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID()); final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(currencyId); final Amount statementLineAmt = Amount.of(record.getStmtAmt(), currencyCode); return statementLineAmt; } public List<PaymentToReconcileRow> getPaymentToReconcileRowsByIds(final Set<PaymentId> paymentIds) { final ImmutableSetMultimap<PaymentId, String> invoiceDocumentNosByPaymentId = getInvoiceDocumentNosByPaymentId(paymentIds); return paymentDAO.getByIds(paymentIds) .stream() .map(record -> toPaymentToReconcileRow(record, invoiceDocumentNosByPaymentId)) .collect(ImmutableList.toImmutableList()); } private ImmutableSetMultimap<PaymentId, String> getInvoiceDocumentNosByPaymentId(final Set<PaymentId> paymentIds) { final SetMultimap<PaymentId, InvoiceId> invoiceIdsByPaymentId = allocationDAO.retrieveInvoiceIdsByPaymentIds(paymentIds); final ImmutableMap<InvoiceId, String> invoiceDocumentNos = invoiceDAO.getDocumentNosByInvoiceIds(invoiceIdsByPaymentId.values()); return invoiceIdsByPaymentId.entries() .stream() .map(GuavaCollectors.mapValue(invoiceDocumentNos::get)) .filter(ImmutableMapEntry::isValueNotNull) .collect(GuavaCollectors.toImmutableSetMultimap()); } private PaymentToReconcileRow toPaymentToReconcileRow( @NonNull final I_C_Payment record, @NonNull final ImmutableSetMultimap<PaymentId, String> invoiceDocumentNosByPaymentId) { final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID()); final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(currencyId); final Amount payAmt = Amount.of(record.getPayAmt(), currencyCode); final PaymentId paymentId = PaymentId.ofRepoId(record.getC_Payment_ID()); String invoiceDocumentNos = joinInvoiceDocumentNos(invoiceDocumentNosByPaymentId.get(paymentId));
return PaymentToReconcileRow.builder() .paymentId(paymentId) .inboundPayment(record.isReceipt()) .documentNo(record.getDocumentNo()) .dateTrx(TimeUtil.asLocalDate(record.getDateTrx())) .bpartner(bpartnerLookup.findById(record.getC_BPartner_ID())) .invoiceDocumentNos(invoiceDocumentNos) .payAmt(payAmt) .reconciled(record.isReconciled()) .build(); } private static String joinInvoiceDocumentNos(final Collection<String> documentNos) { if (documentNos == null || documentNos.isEmpty()) { return ""; } return documentNos.stream() .map(StringUtils::trimBlankToNull) .filter(Objects::nonNull) .collect(Collectors.joining(", ")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementLineAndPaymentsToReconcileRepository.java
1
请完成以下Java代码
public class OrderSchedulingContext { @NonNull OrderId orderId; @Nullable LocalDate orderDate; @Nullable LocalDate letterOfCreditDate; @Nullable LocalDate billOfLadingDate; @Nullable LocalDate ETADate; @Nullable LocalDate invoiceDate; @NonNull Money grandTotal; @NonNull CurrencyPrecision precision; @NonNull PaymentTerm paymentTerm; public DueDateAndStatus computeDueDate(@NonNull final PaymentTermBreak termBreak) { final LocalDate referenceDate = getAvailableReferenceDate(termBreak.getReferenceDateType()); if (referenceDate != null) { final LocalDate dueDate = referenceDate.plusDays(termBreak.getOffsetDays()); return DueDateAndStatus.awaitingPayment(dueDate); } else { return DueDateAndStatus.pending(); } } @Nullable private LocalDate getAvailableReferenceDate(@NonNull final ReferenceDateType referenceDateType)
{ switch (referenceDateType) { case OrderDate: return getOrderDate(); case LetterOfCreditDate: return getLetterOfCreditDate(); case BillOfLadingDate: return getBillOfLadingDate(); case ETADate: return getETADate(); case InvoiceDate: return getInvoiceDate(); default: return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderSchedulingContext.java
1
请在Spring Boot框架中完成以下Java代码
public class ContentLengthController { @GetMapping("/hello") public ResponseEntity<String> hello() { String body = "Hello Spring MVC!"; byte[] bytes = body.getBytes(StandardCharsets.UTF_8); return ResponseEntity.ok() .contentLength(bytes.length) .body(body); } @GetMapping("/binary") public ResponseEntity<byte[]> binary() { byte[] data = {1, 2, 3, 4, 5}; return ResponseEntity.ok() .contentLength(data.length) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(data); } @GetMapping("/download") public ResponseEntity<Resource> download() throws IOException { Path filePath = Paths.get("example.pdf"); // For tests, this file should exist Resource resource = new UrlResource(filePath.toUri()); long fileSize = Files.size(filePath); return ResponseEntity.ok() .contentLength(fileSize) .contentType(MediaType.APPLICATION_PDF) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"example.pdf\"")
.body(resource); } @GetMapping("/manual") public ResponseEntity<String> manual() { String body = "Manual Content-Length"; byte[] bytes = body.getBytes(StandardCharsets.UTF_8); HttpHeaders headers = new HttpHeaders(); headers.setContentLength(bytes.length); return ResponseEntity.ok() .headers(headers) .body(body); } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\contentlenght\ContentLengthController.java
2
请在Spring Boot框架中完成以下Java代码
public class StudentController { @Autowired private StudentService studentService; @GetMapping() public List<Course> retrieveCoursesForStudent(@PathVariable String studentId) { return studentService.retrieveCourses(studentId); } @PostMapping() public ResponseEntity<Void> registerStudentForCourse(@PathVariable String studentId, @RequestBody Course newCourse) { Course course = studentService.addCourse(studentId, newCourse); if (course == null) return ResponseEntity.noContent().build();
URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(course.id()) .toUri(); return ResponseEntity.created(location).build(); } @GetMapping("/{courseId}") public Course retrieveDetailsForCourse(@PathVariable String studentId, @PathVariable String courseId) { return studentService.retrieveCourse(studentId, courseId); } }
repos\spring-boot-examples-master\spring-boot-rest-services\src\main\java\com\in28minutes\springboot\controller\StudentController.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (getClass() != o.getClass()) { return false; } Book other = (Book) o; return Objects.equals(isbn, other.getIsbn()); // including sku // return Objects.equals(isbn, other.getIsbn()) // && Objects.equals(sku, other.getSku()); }
@Override public int hashCode() { return Objects.hash(isbn); // including sku // return Objects.hash(isbn, sku); } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + '}'; // including sku //return "Book{" + "id=" + id + ", title=" + title // + ", isbn=" + isbn + ", price=" + price + ", sku=" + sku + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalId\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isInterrupting() { return isInterrupting; } public void setInterrupting(boolean isInterrupting) { this.isInterrupting = isInterrupting; } public List<FormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<FormProperty> formProperties) { this.formProperties = formProperties; } public StartEvent clone() { StartEvent clone = new StartEvent(); clone.setValues(this);
return clone; } public void setValues(StartEvent otherEvent) { super.setValues(otherEvent); setInitiator(otherEvent.getInitiator()); setFormKey(otherEvent.getFormKey()); setInterrupting(otherEvent.isInterrupting); formProperties = new ArrayList<FormProperty>(); if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) { for (FormProperty property : otherEvent.getFormProperties()) { formProperties.add(property.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\StartEvent.java
1
请完成以下Java代码
public boolean isDropShip() { return BPartnerLocationId.ofRepoIdOrNull(getDropShip_BPartner_ID(), getDropShip_Location_ID()) != null; } @Override public int getDropShip_BPartner_ID() { return delegate.getDropShip_BPartner_ID(); } @Override public void setDropShip_BPartner_ID(final int DropShip_BPartner_ID) { delegate.setDropShip_BPartner_ID(DropShip_BPartner_ID); } @Override public int getDropShip_Location_ID() { return delegate.getDropShip_Location_ID(); } @Override public void setDropShip_Location_ID(final int DropShip_Location_ID) { delegate.setDropShip_Location_ID(DropShip_Location_ID); } @Override public int getDropShip_Location_Value_ID() { return delegate.getDropShip_Location_Value_ID(); } @Override public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID) { delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID); } @Override public int getDropShip_User_ID() { return delegate.getDropShip_User_ID(); } @Override public void setDropShip_User_ID(final int DropShip_User_ID) { delegate.setDropShip_User_ID(DropShip_User_ID); } @Override public int getM_Warehouse_ID() { return -1; } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{ IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from); } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public ContractDropshipLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new ContractDropshipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class)); } @Override public I_C_Flatrate_Term getWrappedRecord() { return delegate; } public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId, final @Nullable BPartnerContactId dropshipContactId) { setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId()); setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId()); setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId()); setDropShip_User_ID(dropshipContactId == null ? -1 : dropshipContactId.getRepoId()); } public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId) { setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId()); setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId()); setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractDropshipLocationAdapter.java
1
请完成以下Java代码
public void clearFields(final GridTab gridTab) { final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class); order.setM_HU_PI_Item_Product_ID(-1); order.setQty_FastInput_TU(null); // these changes will be propagated to the GUI component gridTab.setValue(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID, null); gridTab.setValue(I_C_Order.COLUMNNAME_Qty_FastInput_TU, null); } @Override public boolean requestFocus(final GridTab gridTab) { final I_C_Order order = InterfaceWrapperHelper.create(gridTab, I_C_Order.class); final Integer productId = order.getM_Product_ID(); if (productId <= 0 && gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).isDisplayed()) { gridTab.getField(de.metas.adempiere.model.I_C_Order.COLUMNNAME_M_Product_ID).requestFocus(); return true; } // task 06300: focus shall go from product to TU-qty (not CU-qty) final BigDecimal qtyTU = order.getQty_FastInput_TU(); final BigDecimal qtyCU = order.getQty_FastInput(); final boolean hasTUs = Services.get(IHUOrderBL.class).hasTUs(order); if (!hasTUs || null != qtyCU && qtyCU.signum() > 0) { // the product is not assigned to a TU, so we return false and leave it to the default handler which will probably request the focus for the "CU Qty" field // 06730: Also, we leave it for the default handler if we have a TU quantity with no HU. return false; } if ((qtyTU == null || qtyTU.signum() <= 0) && gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).isDisplayed()) { // product has been set, but qty hasn't gridTab.getField(I_C_Order.COLUMNNAME_Qty_FastInput_TU).requestFocus(); return true;
} final int huPIPId = order.getM_HU_PI_Item_Product_ID(); if (huPIPId <= 0 && gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).isDisplayed()) { gridTab.getField(I_C_Order.COLUMNNAME_M_HU_PI_Item_Product_ID).requestFocus(); return true; } // no focus was requested return false; } @Override public IGridTabRowBuilder createLineBuilderFromHeader(final Object model) { return new OrderLineHUPackingGridRowBuilder(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUOrderFastInputHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void saveEmployee(Employee employee) { this.employeeRepository.save(employee); } @Override public Employee getEmployeeById(long id) { Optional<Employee> optional = employeeRepository.findById(id); Employee employee = null; if( optional.isPresent()) { employee = optional.get(); } else { throw new RuntimeException("Employee not found for id: " + id); } return employee; } @Override
public void deleteEmployeeById(long id) { this.employeeRepository.deleteById(id); } @Override public Page<Employee> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) { Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending(): Sort.by(sortField).descending(); Pageable pageable = PageRequest.of(pageNo-1, pageSize); return this.employeeRepository.findAll(pageable); } }
repos\Spring-Boot-Advanced-Projects-main\Registration-FullStack-Springboot\src\main\java\pagination\sort\service\EmployeeServiceImpl.java
2
请完成以下Java代码
public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setErrorMsg (java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg); } @Override public void setImportStatus (java.lang.String ImportStatus) { set_Value (COLUMNNAME_ImportStatus, ImportStatus); } @Override public java.lang.String getImportStatus() { return (java.lang.String)get_Value(COLUMNNAME_ImportStatus); } @Override public void setJsonRequest (java.lang.String JsonRequest) { set_ValueNoCheck (COLUMNNAME_JsonRequest, JsonRequest); } @Override public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setJsonResponse (java.lang.String JsonResponse) { set_Value (COLUMNNAME_JsonResponse, JsonResponse); } @Override
public java.lang.String getJsonResponse() { return (java.lang.String)get_Value(COLUMNNAME_JsonResponse); } @Override public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID)); } @Override public int getPP_Cost_Collector_ImportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
1
请完成以下Spring Boot application配置
# Spring Boot application.properties for the HTTP Session State Caching Example application. spring.application.name=HttpSessionCachingApplication spring.data.gemfire.cache.log-level=${gemfire.log-level:error} spring.session.data.gemfire.cache.client
.pool.name=DEFAULT spring.session.data.gemfire.session.region.name=Sessions server.servlet.session.timeout=15
repos\spring-boot-data-geode-main\spring-geode-samples\caching\http-session\src\main\resources\application.properties
2
请完成以下Java代码
protected OrderingProperty validateAndGetLastConfiguredProperty() { OrderingProperty lastConfiguredProperty = getLastConfiguredProperty(); if (lastConfiguredProperty == null) { throw LOG.unspecifiedOrderByMethodException(); } return lastConfiguredProperty; } /** * Validates ordering properties all have a non-null direction. */ public void validateOrderingProperties() { boolean hasMissingDirection = orderingProperties.stream() .anyMatch(p -> p.getDirection() == null); if (hasMissingDirection) { throw LOG.missingDirectionException(); } } /** * Converts this {@link OrderingConfig} to a list of {@link SortingDto}s. */ public List<SortingDto> toSortingDtos() { return orderingProperties.stream() .map(SortingDto::fromOrderingProperty) .collect(Collectors.toList()); } /** * Returns the last configured field in this {@link OrderingConfig}. */ protected OrderingProperty getLastConfiguredProperty() { return !orderingProperties.isEmpty() ? orderingProperties.get(orderingProperties.size() - 1) : null; } /** * The field to sort by. */ public enum SortingField { CREATE_TIME("createTime"); private final String name; SortingField(String name) { this.name = name; } public String getName() { return this.name; } } /** * The direction of createTime. */ public enum Direction { ASC, DESC; public String asString() { return super.name().toLowerCase(); } } /** * Static Class that encapsulates an ordering property with a field and its direction. */ public static class OrderingProperty {
protected SortingField field; protected Direction direction; /** * Static factory method to create {@link OrderingProperty} out of a field and its corresponding {@link Direction}. */ public static OrderingProperty of(SortingField field, Direction direction) { OrderingProperty result = new OrderingProperty(); result.setField(field); result.setDirection(direction); return result; } public void setField(SortingField field) { this.field = field; } public SortingField getField() { return this.field; } public void setDirection(Direction direction) { this.direction = direction; } public Direction getDirection() { return this.direction; } } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\OrderingConfig.java
1
请完成以下Java代码
public void setQtyBOM (final @Nullable BigDecimal QtyBOM) { set_Value (COLUMNNAME_QtyBOM, QtyBOM); } @Override public BigDecimal getQtyBOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScrap (final @Nullable BigDecimal Scrap) { set_Value (COLUMNNAME_Scrap, Scrap); } @Override public BigDecimal getScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setShowSubBOMIngredients (final boolean ShowSubBOMIngredients) { set_Value (COLUMNNAME_ShowSubBOMIngredients, ShowSubBOMIngredients); } @Override public boolean isShowSubBOMIngredients() { return get_ValueAsBoolean(COLUMNNAME_ShowSubBOMIngredients); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
} /** * VariantGroup AD_Reference_ID=540490 * Reference name: VariantGroup */ public static final int VARIANTGROUP_AD_Reference_ID=540490; /** 01 = 01 */ public static final String VARIANTGROUP_01 = "01"; /** 02 = 02 */ public static final String VARIANTGROUP_02 = "02"; /** 03 = 03 */ public static final String VARIANTGROUP_03 = "03"; /** 04 = 04 */ public static final String VARIANTGROUP_04 = "04"; /** 05 = 05 */ public static final String VARIANTGROUP_05 = "05"; /** 06 = 06 */ public static final String VARIANTGROUP_06 = "06"; /** 07 = 07 */ public static final String VARIANTGROUP_07 = "07"; /** 08 = 08 */ public static final String VARIANTGROUP_08 = "08"; /** 09 = 09 */ public static final String VARIANTGROUP_09 = "09"; @Override public void setVariantGroup (final @Nullable java.lang.String VariantGroup) { set_Value (COLUMNNAME_VariantGroup, VariantGroup); } @Override public java.lang.String getVariantGroup() { return get_ValueAsString(COLUMNNAME_VariantGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMLine.java
1
请完成以下Java代码
public int getResultSetConcurrency() { return m_resultSetConcurrency; } /** * Get ResultSet Type * * @return rs type */ public int getResultSetType() { return m_resultSetType; } /** * @return transaction name */ public String getTrxName() { return m_trxName; } public final void clearDebugSqlParams() { this.debugSqlParams = null; }
public final void setDebugSqlParam(final int parameterIndex, final Object parameterValue) { if (debugSqlParams == null) { debugSqlParams = new TreeMap<>(); } debugSqlParams.put(parameterIndex, parameterValue); } public final Map<Integer, Object> getDebugSqlParams() { final Map<Integer, Object> debugSqlParams = this.debugSqlParams; return debugSqlParams == null ? ImmutableMap.of() : debugSqlParams; } public final Map<Integer, Object> getAndClearDebugSqlParams() { final Map<Integer, Object> debugSqlParams = getDebugSqlParams(); clearDebugSqlParams(); return debugSqlParams; } } // CStatementVO
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\CStatementVO.java
1
请完成以下Java代码
public OriginalAndCurrentQuantities1 getOrgnlAndCurFaceAmt() { return orgnlAndCurFaceAmt; } /** * Sets the value of the orgnlAndCurFaceAmt property. * * @param value * allowed object is * {@link OriginalAndCurrentQuantities1 } * */ public void setOrgnlAndCurFaceAmt(OriginalAndCurrentQuantities1 value) { this.orgnlAndCurFaceAmt = value; } /** * Gets the value of the prtry property. * * @return * possible object is
* {@link ProprietaryQuantity1 } * */ public ProprietaryQuantity1 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryQuantity1 } * */ public void setPrtry(ProprietaryQuantity1 value) { this.prtry = 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_04\TransactionQuantities2Choice.java
1
请完成以下Java代码
public void setIsInvoiceable (final boolean IsInvoiceable) { set_Value (COLUMNNAME_IsInvoiceable, IsInvoiceable); } @Override public boolean isInvoiceable() { return get_ValueAsBoolean(COLUMNNAME_IsInvoiceable); } @Override public void setLength (final @Nullable BigDecimal Length) { set_Value (COLUMNNAME_Length, Length); } @Override public BigDecimal getLength() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight) { set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight); } @Override public BigDecimal getMaxLoadWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID) { if (M_HU_PackingMaterial_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID); } @Override public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
} @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void 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 setStackabilityFactor (final int StackabilityFactor) { set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor); } @Override public int getStackabilityFactor() { return get_ValueAsInt(COLUMNNAME_StackabilityFactor); } @Override public void setWidth (final @Nullable BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java
1
请完成以下Java代码
public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) { log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); } @Override public void onToTransportUpdateCredentials(ToTransportUpdateCredentialsProto updateCredentials) { this.handler.onToTransportUpdateCredentials(sessionInfo, updateCredentials); } @Override public void onDeviceProfileUpdate(TransportProtos.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) { this.handler.onDeviceProfileUpdate(sessionInfo, deviceProfile); } @Override public void onDeviceUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) { this.handler.onDeviceUpdate(sessionInfo, device, deviceProfileOpt); } @Override public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) { log.trace("[{}] Received RPC command to device", sessionId); this.rpcHandler.onToDeviceRpcRequest(toDeviceRequest, this.sessionInfo); } @Override public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
this.rpcHandler.onToServerRpcResponse(toServerResponse); } @Override public void operationComplete(Future<? super Void> future) throws Exception { log.info("[{}] operationComplete", future); } @Override public void onResourceUpdate(TransportProtos.ResourceUpdateMsg resourceUpdateMsgOpt) { if (ResourceType.LWM2M_MODEL.name().equals(resourceUpdateMsgOpt.getResourceType())) { this.handler.onResourceUpdate(resourceUpdateMsgOpt); } } @Override public void onResourceDelete(TransportProtos.ResourceDeleteMsg resourceDeleteMsgOpt) { if (ResourceType.LWM2M_MODEL.name().equals(resourceDeleteMsgOpt.getResourceType())) { this.handler.onResourceDelete(resourceDeleteMsgOpt); } } @Override public void onDeviceDeleted(DeviceId deviceId) { log.trace("[{}] Device on delete", deviceId); this.handler.onDeviceDelete(deviceId); } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mSessionMsgListener.java
1
请完成以下Java代码
public DecisionExecutionAuditContainer getAuditContainer() { return auditContainer; } public void setAuditContainer(DecisionExecutionAuditContainer auditContainer) { this.auditContainer = auditContainer; } public Map<String, List<Object>> getOutputValues() { return outputValues; } public void addOutputValues(String outputName, List<Object> outputValues) { this.outputValues.put(outputName, outputValues); } public BuiltinAggregator getAggregator() { return aggregator; } public void setAggregator(BuiltinAggregator aggregator) { this.aggregator = aggregator; } public String getInstanceId() { return instanceId; }
public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java
1
请完成以下Java代码
public void setDeserializerDelegateExpression(String deserializerDelegateExpression) { this.deserializerDelegateExpression = deserializerDelegateExpression; } public String getPayloadExtractorDelegateExpression() { return payloadExtractorDelegateExpression; } public void setPayloadExtractorDelegateExpression(String payloadExtractorDelegateExpression) { this.payloadExtractorDelegateExpression = payloadExtractorDelegateExpression; } public String getHeaderExtractorDelegateExpression() { return headerExtractorDelegateExpression; } public void setHeaderExtractorDelegateExpression(String headerExtractorDelegateExpression) { this.headerExtractorDelegateExpression = headerExtractorDelegateExpression; } public String getEventTransformerDelegateExpression() { return eventTransformerDelegateExpression; } public void setEventTransformerDelegateExpression(String eventTransformerDelegateExpression) { this.eventTransformerDelegateExpression = eventTransformerDelegateExpression; } public String getPipelineDelegateExpression() { return pipelineDelegateExpression; } public void setPipelineDelegateExpression(String pipelineDelegateExpression) { this.pipelineDelegateExpression = pipelineDelegateExpression;
} public ChannelEventKeyDetection getChannelEventKeyDetection() { return channelEventKeyDetection; } public void setChannelEventKeyDetection(ChannelEventKeyDetection channelEventKeyDetection) { this.channelEventKeyDetection = channelEventKeyDetection; } public ChannelEventTenantIdDetection getChannelEventTenantIdDetection() { return channelEventTenantIdDetection; } public void setChannelEventTenantIdDetection(ChannelEventTenantIdDetection channelEventTenantIdDetection) { this.channelEventTenantIdDetection = channelEventTenantIdDetection; } public Object getInboundEventProcessingPipeline() { return inboundEventProcessingPipeline; } public void setInboundEventProcessingPipeline(Object inboundEventProcessingPipeline) { this.inboundEventProcessingPipeline = inboundEventProcessingPipeline; } public Object getInboundEventChannelAdapter() { return inboundEventChannelAdapter; } public void setInboundEventChannelAdapter(Object inboundEventChannelAdapter) { this.inboundEventChannelAdapter = inboundEventChannelAdapter; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\InboundChannelModel.java
1
请完成以下Java代码
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID); } @Override public int getC_BPartner_Location_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID); } @Override public void setEDI_cctop_000_v_ID (final int EDI_cctop_000_v_ID) { if (EDI_cctop_000_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_000_v_ID, EDI_cctop_000_v_ID); }
@Override public int getEDI_cctop_000_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_000_v_ID); } @Override public void setEdiInvoicRecipientGLN (final @Nullable java.lang.String EdiInvoicRecipientGLN) { set_ValueNoCheck (COLUMNNAME_EdiInvoicRecipientGLN, EdiInvoicRecipientGLN); } @Override public java.lang.String getEdiInvoicRecipientGLN() { return get_ValueAsString(COLUMNNAME_EdiInvoicRecipientGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_000_v.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull I_C_Order order) { final DocStatus quotationDocStatus = DocStatus.ofNullableCodeOrUnknown(order.getDocStatus()); if (!quotationDocStatus.isCompleted()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not a completed quotation"); } if (!orderBL.isSalesProposalOrQuotation(order)) { return ProcessPreconditionsResolution.rejectWithInternalReason("is not sales proposal or quotation"); } return ProcessPreconditionsResolution.accept(); } @Nullable @Override public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter) { if (PARAM_IsKeepProposalPrices.contentEquals(parameter.getColumnName())) { final I_C_Order proposal = orderBL.getById(OrderId.ofRepoId(getRecord_ID())); if (docTypeBL.isSalesQuotation(DocTypeId.ofRepoId(proposal.getC_DocType_ID()))) { return PARAM_DEFAULT_VALUE_YES; } } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } @Override protected String doIt()
{ final I_C_Order newSalesOrder = CreateSalesOrderFromProposalCommand.builder() .fromProposalId(OrderId.ofRepoId(getRecord_ID())) .newOrderDocTypeId(newOrderDocTypeId) .newOrderDateOrdered(newOrderDateOrdered) .poReference(poReference) .completeIt(completeIt) .isKeepProposalPrices(keepProposalPrices) .build() .execute(); openOrder(newSalesOrder); return newSalesOrder.getDocumentNo(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreateFromProposal.java
1
请完成以下Java代码
protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { if (authToken == null) { return Mono.error(new IllegalStateException("'authToken' must not be null.")); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(authToken); LOGGER.debug("Event: {}", event.getInstance()); return Mono.fromRunnable(() -> restTemplate.postForEntity(url, new HttpEntity<>(createMessage(event, instance), headers), Void.class)); } /** * Creates a message object containing the parameters required for sending a * notification. * @param event the instance event for which the message is being created * @param instance the instance associated with the event * @return a Map object containing the parameters for sending a notification */ protected Object createMessage(InstanceEvent event, Instance instance) { Map<String, Object> parameters = new HashMap<>(); parameters.put("roomId", this.roomId); parameters.put("markdown", createContent(event, instance)); return parameters; } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; }
public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public URI getUrl() { return url; } public void setUrl(URI url) { this.url = url; } @Nullable public String getAuthToken() { return authToken; } public void setAuthToken(@Nullable String authToken) { this.authToken = authToken; } @Nullable public String getRoomId() { return roomId; } public void setRoomId(@Nullable String roomId) { this.roomId = roomId; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\WebexNotifier.java
1
请完成以下Java代码
protected Method getNoParameterMethod(String methodName) { try { return functionClass().getDeclaredMethod(methodName); } catch (Exception e) { throw new FlowableException("Error getting method " + methodName, e); } } protected Method getSingleObjectParameterMethod() { try { return functionClass().getDeclaredMethod(localName(), Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + localName(), e); } } protected Method getSingleObjectParameterMethod(String methodName) { try { return functionClass().getDeclaredMethod(methodName, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + methodName, e); } } protected Method getTwoObjectParameterMethod() { try { return functionClass().getDeclaredMethod(localName(), Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + localName(), e); } } protected Method getTwoObjectParameterMethod(String methodName) { try { return functionClass().getDeclaredMethod(methodName, Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + methodName, e); } } protected Method getThreeObjectParameterMethod() { try { return functionClass().getDeclaredMethod(localName(), Object.class, Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + localName(), e); } }
protected Method getThreeObjectParameterMethod(String methodName) { try { return functionClass().getDeclaredMethod(methodName, Object.class, Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + methodName, e); } } protected Method getFourObjectParameterMethod() { try { return functionClass().getDeclaredMethod(localName(), Object.class, Object.class, Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + localName(), e); } } protected Method getFourObjectParameterMethod(String methodName) { try { return functionClass().getDeclaredMethod(methodName, Object.class, Object.class, Object.class, Object.class); } catch (Exception e) { throw new FlowableException("Error getting method " + methodName, e); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\AbstractFlowableFunctionDelegate.java
1
请完成以下Java代码
public class ExternalTaskFailureDto extends HandleExternalTaskDto { //short error description protected String errorMessage; //full stack trace or error information protected String errorDetails; protected long retryTimeout; protected int retries; protected Map<String, VariableValueDto> variables; protected Map<String, VariableValueDto> localVariables; public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public long getRetryTimeout() { return retryTimeout; } public void setRetryTimeout(long retryTimeout) { this.retryTimeout = retryTimeout; } public int getRetries() { return retries; } public void setRetries(int retries) { this.retries = retries; } public String getErrorDetails() {
return errorDetails; } public void setErrorDetails(String errorDetails) { this.errorDetails = errorDetails; } public Map<String, VariableValueDto> getVariables() { return variables; } public void setVariables(Map<String, VariableValueDto> variables) { this.variables = variables; } public Map<String, VariableValueDto> getLocalVariables() { return localVariables; } public void setLocalVariables(Map<String, VariableValueDto> localVariables) { this.localVariables = localVariables; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskFailureDto.java
1
请完成以下Java代码
public class DefaultDestinationTopicProcessor implements DestinationTopicProcessor { private final DestinationTopicResolver destinationTopicResolver; public DefaultDestinationTopicProcessor(DestinationTopicResolver destinationTopicResolver) { this.destinationTopicResolver = destinationTopicResolver; } @Override public void processDestinationTopicProperties(Consumer<DestinationTopic.Properties> destinationPropertiesProcessor, Context context) { context .properties .forEach(destinationPropertiesProcessor); } @Override public void registerDestinationTopic(String mainTopicName, @Nullable String destinationTopicName, DestinationTopic.Properties destinationTopicProperties, Context context) { List<DestinationTopic> topicDestinations = context.destinationsByTopicMap .computeIfAbsent(mainTopicName, newTopic -> new ArrayList<>()); topicDestinations.add(new DestinationTopic(destinationTopicName, destinationTopicProperties)); }
@Override public void processRegisteredDestinations(Consumer<Collection<String>> topicsCallback, Context context) { context .destinationsByTopicMap .values() .forEach(topicDestinations -> this.destinationTopicResolver.addDestinationTopics( context.listenerId, topicDestinations)); topicsCallback.accept(getAllTopicsNamesForThis(context)); } private List<String> getAllTopicsNamesForThis(Context context) { return context.destinationsByTopicMap .values() .stream() .flatMap(Collection::stream) .map(DestinationTopic::getDestinationName) .collect(Collectors.toList()); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DefaultDestinationTopicProcessor.java
1
请完成以下Java代码
protected void text(ObjectNode parent, TextCapability capability) { ObjectNode text = nodeFactory.objectNode(); text.put("type", capability.getType().getName()); String defaultValue = capability.getContent(); if (StringUtils.hasText(defaultValue)) { text.put("default", defaultValue); } parent.set(capability.getId(), text); } protected ObjectNode mapDependencyGroup(DependencyGroup group) { ObjectNode result = nodeFactory.objectNode(); result.put("name", group.getName()); if ((group instanceof Describable) && ((Describable) group).getDescription() != null) { result.put("description", ((Describable) group).getDescription()); } ArrayNode items = nodeFactory.arrayNode(); group.getContent().forEach((it) -> { JsonNode dependency = mapDependency(it); if (dependency != null) { items.add(dependency); } }); result.set("values", items); return result; } 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
请完成以下Java代码
public abstract class AbstractEntityProfileQueryProcessor<T extends EntityFilter> extends AbstractSimpleQueryProcessor<T> { private final Set<UUID> entityProfileIds = new HashSet<>(); private final Pattern pattern; public AbstractEntityProfileQueryProcessor(TenantRepo repo, QueryContext ctx, EdqsQuery query, T filter, EntityType entityType) { super(repo, ctx, query, filter, entityType); var profileNamesSet = new HashSet<>(getProfileNames(this.filter)); for (EntityData<?> dp : repo.getEntitySet(getProfileEntityType())) { if (profileNamesSet.contains(dp.getFields().getName())) { entityProfileIds.add(dp.getId()); } } pattern = RepositoryUtils.toEntityNameSqlLikePattern(getEntityNameFilter(filter)); }
protected abstract String getEntityNameFilter(T filter); protected abstract List<String> getProfileNames(T filter); protected abstract EntityType getProfileEntityType(); @Override protected boolean matches(EntityData<?> ed) { ProfileAwareData<?> profileAwareData = (ProfileAwareData<?>) ed; return super.matches(ed) && entityProfileIds.contains(profileAwareData.getFields().getProfileId()) && (pattern == null || pattern.matcher(profileAwareData.getFields().getName()).matches()); } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\query\processor\AbstractEntityProfileQueryProcessor.java
1
请完成以下Java代码
public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setPP_Workstation_UserAssign_ID (final int PP_Workstation_UserAssign_ID) { if (PP_Workstation_UserAssign_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Workstation_UserAssign_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Workstation_UserAssign_ID, PP_Workstation_UserAssign_ID); } @Override public int getPP_Workstation_UserAssign_ID() { return get_ValueAsInt(COLUMNNAME_PP_Workstation_UserAssign_ID); } @Override public org.compiere.model.I_S_Resource getWorkStation() { return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class); } @Override public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation) { set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation);
} @Override public void setWorkStation_ID (final int WorkStation_ID) { if (WorkStation_ID < 1) set_ValueNoCheck (COLUMNNAME_WorkStation_ID, null); else set_ValueNoCheck (COLUMNNAME_WorkStation_ID, WorkStation_ID); } @Override public int getWorkStation_ID() { return get_ValueAsInt(COLUMNNAME_WorkStation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_Workstation_UserAssign.java
1
请完成以下Java代码
protected void initializePrivilege(String restAdminId, String privilegeName) { boolean restApiPrivilegeMappingExists = false; Privilege privilege = idmIdentityService.createPrivilegeQuery().privilegeName(privilegeName).singleResult(); if (privilege != null) { restApiPrivilegeMappingExists = restApiPrivilegeMappingExists(restAdminId, privilege); } else { try { privilege = idmIdentityService.createPrivilege(privilegeName); } catch (Exception e) { // Could be created by another server, retrying fetch privilege = idmIdentityService.createPrivilegeQuery().privilegeName(privilegeName).singleResult(); } } if (privilege == null) { throw new FlowableException("Could not find or create " + privilegeName + " privilege"); } if (!restApiPrivilegeMappingExists) { idmIdentityService.addUserPrivilegeMapping(privilege.getId(), restAdminId); } } protected boolean restApiPrivilegeMappingExists(String restAdminId, Privilege privilege) { return idmIdentityService.createPrivilegeQuery() .userId(restAdminId) .privilegeId(privilege.getId()) .singleResult() != null; } protected void initDemoProcessDefinitions() { String deploymentName = "Demo processes"; List<Deployment> deploymentList = repositoryService.createDeploymentQuery().deploymentName(deploymentName).list(); if (deploymentList == null || deploymentList.isEmpty()) { repositoryService.createDeployment().name(deploymentName)
.addClasspathResource("createTimersProcess.bpmn20.xml") .addClasspathResource("oneTaskProcess.bpmn20.xml") .addClasspathResource("VacationRequest.bpmn20.xml") .addClasspathResource("VacationRequest.png") .addClasspathResource("FixSystemFailureProcess.bpmn20.xml") .addClasspathResource("FixSystemFailureProcess.png") .addClasspathResource("Helpdesk.bpmn20.xml") .addClasspathResource("Helpdesk.png") .addClasspathResource("reviewSalesLead.bpmn20.xml") .deploy(); } } @Override public void setEnvironment(Environment environment) { this.environment = environment; } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\conf\BootstrapConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(amount, buyerUsername, closedDate, openDate, orderId, paymentDisputeId, paymentDisputeStatus, reason, respondByDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentDisputeSummary {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" buyerUsername: ").append(toIndentedString(buyerUsername)).append("\n"); sb.append(" closedDate: ").append(toIndentedString(closedDate)).append("\n"); sb.append(" openDate: ").append(toIndentedString(openDate)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" paymentDisputeId: ").append(toIndentedString(paymentDisputeId)).append("\n"); sb.append(" paymentDisputeStatus: ").append(toIndentedString(paymentDisputeStatus)).append("\n"); sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n"); sb.append("}"); return sb.toString();
} /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PaymentDisputeSummary.java
2
请完成以下Java代码
public String getErrorMessage() { return typedValueField.getErrorMessage(); } @Override public void setByteArrayId(String id) { byteArrayField.setByteArrayId(id); } @Override public String getSerializerName() { return typedValueField.getSerializerName(); } @Override public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getByteArrayValueId() { return byteArrayField.getByteArrayId(); } public byte[] getByteArrayValue() { return byteArrayField.getByteArrayValue(); } public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public String getName() { return getVariableName(); } // entity lifecycle ///////////////////////////////////////////////////////// public void postLoad() { // make sure the serializer is initialized typedValueField.postLoad(); } // getters and setters ////////////////////////////////////////////////////// public String getTypeName() { return typedValueField.getTypeName(); } public String getVariableTypeName() { return getTypeName(); } public Date getTime() { return timestamp;
} @Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
1
请完成以下Java代码
public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy { @Override public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { return convertToSnakeCase(identifier); } @Override public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { return convertToSnakeCase(identifier); } @Override public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { return convertToSnakeCase(identifier); } @Override public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { return convertToSnakeCase(identifier);
} @Override public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) { return convertToSnakeCase(identifier); } private Identifier convertToSnakeCase(final Identifier identifier) { if (identifier == null) { return identifier; } final String regex = "([a-z])([A-Z])"; final String replacement = "$1_$2"; final String newName = identifier.getText() .replaceAll(regex, replacement) .toLowerCase(); return Identifier.toIdentifier(newName, identifier.isQuoted()); } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\namingstrategy\CustomPhysicalNamingStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public Date getPosted() { return posted; } /** * @param posted * the posted to set */ public void setPosted(Date posted) { this.posted = posted; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((posted == null) ? 0 : posted.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommentDTO other = (CommentDTO) obj; if (comment == null) { if (other.comment != null) return false; } else if (!comment.equals(other.comment)) return false; if (posted == null) { if (other.posted != null) return false; } else if (!posted.equals(other.posted)) return false; if (taskId == null) { if (other.taskId != null) return false; } else if (!taskId.equals(other.taskId)) return false; return true;
} /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "CommentDTO [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]"; } } /** * Custom date serializer that converts the date to long before sending it out * * @author anilallewar * */ class CustomDateToLongSerializer extends JsonSerializer<Date> { @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeNumber(value.getTime()); } }
repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\dtos\CommentDTO.java
2
请在Spring Boot框架中完成以下Java代码
public class SignatureVerificationType { @XmlElement(name = "SignatureVerificationResult") protected SignatureVerificationResultType signatureVerificationResult; @XmlElement(name = "SignatureVerificationOmittedErrorCode") protected String signatureVerificationOmittedErrorCode; @XmlAttribute(name = "SignatureVerified", namespace = "http://erpel.at/schemas/1p0/messaging/header", required = true) protected boolean signatureVerified; /** * Gets the value of the signatureVerificationResult property. * * @return * possible object is * {@link SignatureVerificationResultType } * */ public SignatureVerificationResultType getSignatureVerificationResult() { return signatureVerificationResult; } /** * Sets the value of the signatureVerificationResult property. * * @param value * allowed object is * {@link SignatureVerificationResultType } * */ public void setSignatureVerificationResult(SignatureVerificationResultType value) { this.signatureVerificationResult = value; } /** * Gets the value of the signatureVerificationOmittedErrorCode property. * * @return * possible object is * {@link String } * */ public String getSignatureVerificationOmittedErrorCode() { return signatureVerificationOmittedErrorCode; } /** * Sets the value of the signatureVerificationOmittedErrorCode property. * * @param value * allowed object is * {@link String }
* */ public void setSignatureVerificationOmittedErrorCode(String value) { this.signatureVerificationOmittedErrorCode = value; } /** * Gets the value of the signatureVerified property. * */ public boolean isSignatureVerified() { return signatureVerified; } /** * Sets the value of the signatureVerified property. * */ public void setSignatureVerified(boolean value) { this.signatureVerified = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SignatureVerificationType.java
2
请在Spring Boot框架中完成以下Java代码
private static Saml2MessageBinding getSingleLogoutServiceBinding(Element relyingPartyRegistrationElt) { String singleLogoutServiceBinding = relyingPartyRegistrationElt.getAttribute(ATT_SINGLE_LOGOUT_SERVICE_BINDING); if (StringUtils.hasText(singleLogoutServiceBinding)) { return Saml2MessageBinding.valueOf(singleLogoutServiceBinding); } return null; } private static Saml2X509Credential getSaml2VerificationCredential(String certificateLocation) { return getSaml2Credential(certificateLocation, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); } private static Saml2X509Credential getSaml2EncryptionCredential(String certificateLocation) { return getSaml2Credential(certificateLocation, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } private static Saml2X509Credential getSaml2SigningCredential(String privateKeyLocation, String certificateLocation) { return getSaml2Credential(privateKeyLocation, certificateLocation, Saml2X509Credential.Saml2X509CredentialType.SIGNING); } private static Saml2X509Credential getSaml2DecryptionCredential(String privateKeyLocation, String certificateLocation) { return getSaml2Credential(privateKeyLocation, certificateLocation, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } private static Saml2X509Credential getSaml2Credential(String privateKeyLocation, String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { RSAPrivateKey privateKey = readPrivateKey(privateKeyLocation); X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(privateKey, certificate, credentialType);
} private static Saml2X509Credential getSaml2Credential(String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(certificate, credentialType); } private static RSAPrivateKey readPrivateKey(String privateKeyLocation) { Resource privateKey = resourceLoader.getResource(privateKeyLocation); try (InputStream inputStream = privateKey.getInputStream()) { return RsaKeyConverters.pkcs8().convert(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static X509Certificate readCertificate(String certificateLocation) { Resource certificate = resourceLoader.getResource(certificateLocation); try (InputStream inputStream = certificate.getInputStream()) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static String resolveAttribute(ParserContext pc, String value) { return pc.getReaderContext().getEnvironment().resolvePlaceholders(value); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\saml2\RelyingPartyRegistrationsBeanDefinitionParser.java
2
请完成以下Java代码
protected String doIt() throws Exception { final List<I_M_HU> fromHUs = getSelectedPickingSlotTopLevelHUs(); final IAllocationSource source = HUListAllocationSourceDestination.of(fromHUs) .setDestroyEmptyHUs(true); final IHUProducerAllocationDestination destination = createHUProducer(); HULoader.of(source, destination) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .unloadAllFromSource(); // If the source HU was destroyed, then "remove" it from picking slots final ImmutableSet<HuId> destroyedHUIds = fromHUs.stream() .filter(handlingUnitsBL::isDestroyedRefreshFirst) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (!destroyedHUIds.isEmpty()) { pickingCandidateService.inactivateForHUIds(destroyedHUIds); } return MSG_OK; }
@Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } private IHUProducerAllocationDestination createHUProducer() { final PickingSlotRow pickingRow = getRootRowForSelectedPickingSlotRows(); return createNewHUProducer(pickingRow, targetHUPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutMultiHUsAndAddToNewHU.java
1
请完成以下Java代码
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException { ByteArrayInputStream bIn = new ByteArrayInputStream(signedData); ASN1InputStream aIn = new ASN1InputStream(bIn); CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject())); aIn.close(); bIn.close(); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); SignerInformation signer = c.iterator().next(); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder)); if (!verifResult) { return false; } return true; } public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build(); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor); encryptedData = cmsEnvelopedData.getEncoded();
} return encryptedData; } public static byte[] decryptData(final byte[] encryptedData, final PrivateKey decryptionKey) throws CMSException { byte[] decryptedData = null; if (null != encryptedData && null != decryptionKey) { CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData); Collection<RecipientInformation> recip = envelopedData.getRecipientInfos().getRecipients(); KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recip.iterator().next(); JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey); decryptedData = recipientInfo.getContent(recipient); } return decryptedData; } }
repos\tutorials-master\libraries-security\src\main\java\com\baeldung\bouncycastle\BouncyCastleCrypto.java
1
请完成以下Java代码
public void setSourceVariableName(String sourceVariableName) { this.sourceVariableName = sourceVariableName; } public Expression getSourceExpression() { return sourceExpression; } public void setSourceExpression(Expression sourceExpression) { this.sourceExpression = sourceExpression; } public String getDestinationVariableName() { return destinationVariableName; } public void setDestinationVariableName(String destinationVariableName) { this.destinationVariableName = destinationVariableName; } public Expression getDestinationExpression() { return destinationExpression; }
public void setDestinationExpression(Expression destinationExpression) { this.destinationExpression = destinationExpression; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Expression getLinkExpression() { return linkExpression; } public void setLinkExpression(Expression linkExpression) { this.linkExpression = linkExpression; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\VariableDeclaration.java
1
请完成以下Java代码
public class ValidateV5EntitiesCmd implements Command<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(ValidateV5EntitiesCmd.class); @Override public Void execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); if (!processEngineConfiguration.isFlowable5CompatibilityEnabled() || processEngineConfiguration.getFlowable5CompatibilityHandler() == null) { RepositoryService repositoryService = processEngineConfiguration.getRepositoryService(); long numberOfV5Deployments = repositoryService.createDeploymentQuery().deploymentEngineVersion(Flowable5Util.V5_ENGINE_TAG).count(); LOGGER.info("Total of v5 deployments found: {}", numberOfV5Deployments); if (numberOfV5Deployments > 0) { List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery() .latestVersion() .processDefinitionEngineVersion(Flowable5Util.V5_ENGINE_TAG) .list(); if (!processDefinitions.isEmpty()) { String message = new StringBuilder("Found v5 process definitions that are the latest version.") .append(" Enable the 'flowable5CompatibilityEnabled' property in the process engine configuration") .append(" and make sure the flowable5-compatibility dependency is available on the classpath").toString(); LOGGER.error(message);
for (ProcessDefinition processDefinition : processDefinitions) { LOGGER.error("Found v5 process definition with id: {}, and key: {}", processDefinition.getId(), processDefinition.getKey()); } throw new FlowableException(message); } RuntimeService runtimeService = processEngineConfiguration.getRuntimeService(); long numberOfV5ProcessInstances = runtimeService.createProcessInstanceQuery().processDefinitionEngineVersion(Flowable5Util.V5_ENGINE_TAG).count(); if (numberOfV5ProcessInstances > 0) { String message = new StringBuilder("Found at least one running v5 process instance.") .append(" Enable the 'flowable5CompatibilityEnabled' property in the process engine configuration") .append(" and make sure the flowable5-compatibility dependency is available on the classpath").toString(); LOGGER.error(message); throw new FlowableException(message); } } } return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ValidateV5EntitiesCmd.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID())); final ShipmentScheduleQuery shipmentScheduleQuery = ShipmentScheduleQuery.builder() .warehouseId(currentRow.getWarehouseId())
.orgId(currentRow.getOrgId()) .productId(currentRow.getProductId()) .attributesKey(currentRow.getAttributesKey()) .onlyNonZeroReservedQty(true) .build(); final List<TableRecordReference> recordReferences = shipmentScheduleRepository.getIdsByQuery(shipmentScheduleQuery) .stream() .map(id -> TableRecordReference.of(I_M_ShipmentSchedule.Table_Name, id)) .collect(Collectors.toList()); getResult().setRecordsToOpen(recordReferences); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_ShipmentSchedule.java
1
请完成以下Spring Boot application配置
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.primary.username=root spring.datasource.primary.password=root spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.secondary.username=root spring.datasource.secondary.password=root spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver spring.server.maxThreads=600
repos\spring-boot-leaning-master\2.x_42_courses\第 3-1 课: Spring Boot 使用 JDBC 操作数据库\spring-boot-multi-jdbc\src\main\resources\application.properties
2
请完成以下Java代码
public abstract class RemoteInvocationUtils { /** * Fill the current client-side stack trace into the given exception. * <p>The given exception is typically thrown on the server and serialized * as-is, with the client wanting it to contain the client-side portion * of the stack trace as well. What we can do here is to update the * {@code StackTraceElement} array with the current client-side stack * trace, provided that we run on JDK 1.4+. * @param ex the exception to update * @see Throwable#getStackTrace() * @see Throwable#setStackTrace(StackTraceElement[]) */ public static void fillInClientStackTraceIfPossible(@Nullable Throwable ex) { if (ex != null) { StackTraceElement[] clientStack = new Throwable().getStackTrace();
Set<Throwable> visitedExceptions = new HashSet<>(); Throwable exToUpdate = ex; while (exToUpdate != null && !visitedExceptions.contains(exToUpdate)) { StackTraceElement[] serverStack = exToUpdate.getStackTrace(); StackTraceElement[] combinedStack = new StackTraceElement[serverStack.length + clientStack.length]; System.arraycopy(serverStack, 0, combinedStack, 0, serverStack.length); System.arraycopy(clientStack, 0, combinedStack, serverStack.length, clientStack.length); exToUpdate.setStackTrace(combinedStack); visitedExceptions.add(exToUpdate); exToUpdate = exToUpdate.getCause(); } } } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\RemoteInvocationUtils.java
1
请完成以下Java代码
public class HttpCallScheduler { private CompletableFuture<Void> executorFuture; private final LinkedBlockingQueue<ScheduledRequest> requestsQueue; private final Executor executor; public HttpCallScheduler() { this.requestsQueue = new LinkedBlockingQueue<>(); this.executor = Executors.newFixedThreadPool(1); this.executorFuture = new CompletableFuture<>(); this.executorFuture.complete(null); } public synchronized void schedule(final ScheduledRequest request) { this.requestsQueue.add(request); if (executorFuture.isDone()) { executorFuture = executorFuture.thenRunAsync(this::run, executor); } } private void run() { try { while (!requestsQueue.isEmpty()) {
final ScheduledRequest scheduleRequest = requestsQueue.poll(); try { final ApiResponse response = scheduleRequest.getHttpResponseSupplier().get(); scheduleRequest.getCompletableFuture().complete(response); } catch (final Exception exception) { scheduleRequest.getCompletableFuture().completeExceptionally(exception); } } } finally { executorFuture.complete(null); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\HttpCallScheduler.java
1
请完成以下Java代码
public void update(Collection<Integer> featureVector, float value, double[] total, int[] timestamp, int current) { for (Integer i : featureVector) update(i, value, total, timestamp, current); } /** * 根据答案和预测更新参数 * * @param index 特征向量的下标 * @param value 更新量 * @param total 权值向量总和 * @param timestamp 每个权值上次更新的时间戳 * @param current 当前时间戳 */ private void update(int index, float value, double[] total, int[] timestamp, int current)
{ int passed = current - timestamp[index]; total[index] += passed * parameter[index]; parameter[index] += value; timestamp[index] = current; } public void average(double[] total, int[] timestamp, int current) { for (int i = 0; i < parameter.length; i++) { parameter[i] = (float) ((total[i] + (current - timestamp[i]) * parameter[i]) / current); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\model\AveragedPerceptron.java
1
请完成以下Java代码
public static Object extractJSONValue( @NonNull final IAttributeStorage attributesStorage, @NonNull final IAttributeValue attributeValue, @NonNull final JSONOptions jsonOpts) { final Object value = extractValueAndResolve(attributesStorage, attributeValue); return Values.valueToJsonObject(value, jsonOpts); } @Nullable private static Object extractValueAndResolve( @NonNull final IAttributeStorage attributesStorage, @NonNull final IAttributeValue attributeValue) { final Object value = attributeValue.getValue(); if (!attributeValue.isList()) { return value; } final IAttributeValuesProvider valuesProvider = attributeValue.getAttributeValuesProvider(); final Evaluatee evalCtx = valuesProvider.prepareContext(attributesStorage); final NamePair valueNP = valuesProvider.getAttributeValueOrNull(evalCtx, value); final TooltipType tooltipType = Services.get(IADTableDAO.class).getTooltipTypeByTableName(I_M_Attribute.Table_Name); return LookupValue.fromNamePair(valueNP, null, tooltipType); } public static DocumentFieldWidgetType extractWidgetType(final IAttributeValue attributeValue) { if (attributeValue.isList()) { final I_M_Attribute attribute = attributeValue.getM_Attribute(); if (attribute.isHighVolume()) { return DocumentFieldWidgetType.Lookup; } else { return DocumentFieldWidgetType.List; } } else if (attributeValue.isStringValue()) { return DocumentFieldWidgetType.Text; } else if (attributeValue.isNumericValue()) { return DocumentFieldWidgetType.Number; } else if (attributeValue.isDateValue()) { return DocumentFieldWidgetType.LocalDate; } else { throw new IllegalArgumentException("Cannot extract widgetType from " + attributeValue); } } @NonNull
private static Optional<DocumentLayoutElementDescriptor> getClearanceNoteLayoutElement(@NonNull final I_M_HU hu) { if (Check.isBlank(hu.getClearanceNote())) { return Optional.empty(); } final boolean isDisplayedClearanceStatus = Services.get(ISysConfigBL.class).getBooleanValue(SYS_CONFIG_CLEARANCE, true); if (!isDisplayedClearanceStatus) { return Optional.empty(); } return Optional.of(createClearanceNoteLayoutElement()); } @NonNull private static DocumentLayoutElementDescriptor createClearanceNoteLayoutElement() { final ITranslatableString caption = Services.get(IMsgBL.class).translatable(I_M_HU.COLUMNNAME_ClearanceNote); return DocumentLayoutElementDescriptor.builder() .setCaption(caption) .setWidgetType(DocumentFieldWidgetType.Text) .addField(DocumentLayoutElementFieldDescriptor .builder(I_M_HU.COLUMNNAME_ClearanceNote) .setPublicField(true)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesHelper.java
1
请完成以下Java代码
public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) { dispose(); return; } String columnName = null; String from_Info = null; String to_Info = null; int from_ID = 0; int to_ID = 0; // get first merge pair for (int i = 0; (i < m_columnName.length && from_ID == 0 && to_ID == 0); i++) { Object value = m_from[i].getValue(); if (value != null) { if (value instanceof Integer) from_ID = ((Integer)value).intValue(); else continue; value = m_to[i].getValue(); if (value != null && value instanceof Integer) to_ID = ((Integer)value).intValue(); else from_ID = 0; if (from_ID != 0) { columnName = m_columnName[i]; from_Info = m_from[i].getDisplay (); to_Info = m_to[i].getDisplay (); } } } // get first merge pair if (from_ID == 0 || from_ID == to_ID) return; String msg = Msg.getMsg(Env.getCtx(), "MergeFrom") + " = " + from_Info + "\n" + Msg.getMsg(Env.getCtx(), "MergeTo") + " = " + to_Info; if (!ADialog.ask(m_WindowNo, panel, "MergeQuestion", msg)) return; updateDeleteTable(columnName); panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
confirmPanel.getOKButton().setEnabled(false); // boolean success = merge (columnName, from_ID, to_ID); postMerge(columnName, to_ID); // confirmPanel.getOKButton().setEnabled(true); panel.setCursor(Cursor.getDefaultCursor()); // if (success) { ADialog.info(m_WindowNo, panel, "MergeSuccess", msg + " #" + m_totalCount); } else { ADialog.error(m_WindowNo, panel, "MergeError", m_errorLog.toString()); return; } dispose(); } // actionPerformed } // VMerge
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VMerge.java
1
请完成以下Java代码
public JwsHeader.Builder getJwsHeader() { return get(JwsHeader.Builder.class); } /** * Returns the {@link JwtClaimsSet.Builder claims} allowing the ability to add, * replace, or remove. * @return the {@link JwtClaimsSet.Builder} */ public JwtClaimsSet.Builder getClaims() { return get(JwtClaimsSet.Builder.class); } /** * Constructs a new {@link Builder} with the provided JWS headers and claims. * @param jwsHeaderBuilder the JWS headers to initialize the builder * @param claimsBuilder the claims to initialize the builder * @return the {@link Builder} */ public static Builder with(JwsHeader.Builder jwsHeaderBuilder, JwtClaimsSet.Builder claimsBuilder) { return new Builder(jwsHeaderBuilder, claimsBuilder); } /** * A builder for {@link JwtEncodingContext}. */ public static final class Builder extends AbstractBuilder<JwtEncodingContext, Builder> { private Builder(JwsHeader.Builder jwsHeaderBuilder, JwtClaimsSet.Builder claimsBuilder) { Assert.notNull(jwsHeaderBuilder, "jwsHeaderBuilder cannot be null");
Assert.notNull(claimsBuilder, "claimsBuilder cannot be null"); put(JwsHeader.Builder.class, jwsHeaderBuilder); put(JwtClaimsSet.Builder.class, claimsBuilder); } /** * Builds a new {@link JwtEncodingContext}. * @return the {@link JwtEncodingContext} */ @Override public JwtEncodingContext build() { return new JwtEncodingContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\JwtEncodingContext.java
1
请完成以下Java代码
public class SubmitTaskFormCmd extends NeedsActiveTaskCmd<Void> { private static final long serialVersionUID = 1L; protected String taskId; protected Map<String, String> properties; protected boolean completeTask; public SubmitTaskFormCmd(String taskId, Map<String, String> properties, boolean completeTask) { super(taskId); this.taskId = taskId; this.properties = properties; this.completeTask = completeTask; } @Override protected Void execute(CommandContext commandContext, TaskEntity task) { // Backwards compatibility if (task.getProcessDefinitionId() != null) { if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.submitTaskFormData(taskId, properties, completeTask); return null; } } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ExecutionEntity executionEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getExecutionId()); CommandContextUtil.getHistoryManager(commandContext)
.recordFormPropertiesSubmitted(executionEntity, properties, taskId, processEngineConfiguration.getClock().getCurrentTime()); FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper(); TaskFormHandler taskFormHandler = formHandlerHelper.getTaskFormHandlder(task); if (taskFormHandler != null) { taskFormHandler.submitFormProperties(properties, executionEntity); if (completeTask) { TaskHelper.completeTask(task, null, null, null, null, null, commandContext); } } return null; } @Override protected String getSuspendedTaskExceptionPrefix() { return "Cannot submit a form to"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SubmitTaskFormCmd.java
1
请完成以下Java代码
public void registerPermanentCustomizer(@NonNull final IConnectionCustomizer connectionCustomizer) { permanentCustomizers.add(connectionCustomizer); } @Override public AutoCloseable registerTemporaryCustomizer(@NonNull final ITemporaryConnectionCustomizer connectionCustomizer) { temporaryCustomizers.get().add(connectionCustomizer); return new AutoCloseable() { @Override public void close() throws Exception { removeTemporaryCustomizer(connectionCustomizer); } }; } private void removeTemporaryCustomizer(@NonNull final ITemporaryConnectionCustomizer dlmConnectionCustomizer) { final boolean wasInTheList = temporaryCustomizers.get().remove(dlmConnectionCustomizer); Check.errorIf(!wasInTheList, "ITemporaryConnectionCustomizer={} was not in the thread-local list of temperary customizers; this={}", dlmConnectionCustomizer, this); } @Override public void fireRegisteredCustomizers(@NonNull final Connection c) { getRegisteredCustomizers().forEach( customizer -> { invokeIfNotYetInvoked(customizer, c); }); } @Override
public String toString() { return "ConnectionCustomizerService [permanentCustomizers=" + permanentCustomizers + ", (thread-local-)temporaryCustomizers=" + temporaryCustomizers.get() + ", (thread-local-)currentlyInvokedCustomizers=" + currentlyInvokedCustomizers + "]"; } private List<IConnectionCustomizer> getRegisteredCustomizers() { return new ImmutableList.Builder<IConnectionCustomizer>() .addAll(permanentCustomizers) .addAll(temporaryCustomizers.get()) .build(); } /** * Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish. * So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}. * * @param customizer * @param connection */ private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection) { try { if (currentlyInvokedCustomizers.get().add(customizer)) { customizer.customizeConnection(connection); currentlyInvokedCustomizers.get().remove(customizer); } } finally { currentlyInvokedCustomizers.get().remove(customizer); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
1
请完成以下Java代码
public static HardwareTrayId ofRepoId(final int printerId, final int trayId) { return new HardwareTrayId(HardwarePrinterId.ofRepoId(printerId), trayId); } public static HardwareTrayId ofRepoIdOrNull( @Nullable final Integer printerId, @Nullable final Integer trayId) { return printerId != null && printerId > 0 && trayId != null && trayId > 0 ? ofRepoId(printerId, trayId) : null; } public static HardwareTrayId ofRepoIdOrNull( @Nullable final HardwarePrinterId printerId, final int trayId)
{ return printerId != null && trayId > 0 ? ofRepoId(printerId, trayId) : null; } private HardwareTrayId(@NonNull final HardwarePrinterId printerId, final int trayId) { this.repoId = Check.assumeGreaterThanZero(trayId, "trayId"); this.printerId = printerId; } public static int toRepoId(@Nullable final HardwareTrayId trayId) { return trayId != null ? trayId.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwareTrayId.java
1
请完成以下Java代码
public OrderCheckupBuilder setWarehouseId(@Nullable final WarehouseId warehouseId) { this._warehouseId = warehouseId; return this; } private WarehouseId getWarehouseId() { return _warehouseId; } public OrderCheckupBuilder setPlantId(ResourceId plantId) { this._plantId = plantId; return this; } private ResourceId getPlantId() { return _plantId; } public OrderCheckupBuilder setReponsibleUserId(UserId reponsibleUserId)
{ this._reponsibleUserId = reponsibleUserId; return this; } private UserId getReponsibleUserId() { return _reponsibleUserId; } public OrderCheckupBuilder setDocumentType(String documentType) { this._documentType = documentType; return this; } private String getDocumentType() { Check.assumeNotEmpty(_documentType, "documentType not empty"); return _documentType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\impl\OrderCheckupBuilder.java
1