instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public final String getSummary(@NonNull final Object model) { final IDocument doc = getDocumentOrNull(model); if (doc != null) { return doc.getSummary(); } // Fallback: use toString() return String.valueOf(model); } @Override public boolean isReversalDocument(@NonNull final Object model) { // Try Reversal_ID column if available final Integer original_ID = InterfaceWrapperHelper.getValueOrNull(model, IDocument.Reversal_ID); if (original_ID != null && original_ID > 0) { final int reversal_id = InterfaceWrapperHelper.getId(model); return reversal_id > original_ID; } return false; } @Override public final Map<String, IDocActionItem> retrieveDocActionItemsIndexedByValue() { final ADReferenceService adReferenceService = ADReferenceService.get(); final Properties ctx = Env.getCtx(); final String adLanguage = Env.getAD_Language(ctx); return adReferenceService.retrieveListItems(X_C_Order.DOCACTION_AD_Reference_ID) // 135 .stream() .map(adRefListItem -> new DocActionItem(adRefListItem, adLanguage)) .sorted(Comparator.comparing(DocActionItem::toString)) .collect(GuavaCollectors.toImmutableMapByKey(IDocActionItem::getValue)); } private static final class DocActionItem implements IDocActionItem { private final String value; private final String caption; private final String description; private DocActionItem(final ADRefListItem adRefListItem, final String adLanguage) { this.value = adRefListItem.getValue(); this.caption = adRefListItem.getName().translate(adLanguage); this.description = adRefListItem.getDescription().translate(adLanguage); } @Override public String toString() { // IMPORTANT: this is how it will be displayed to user return caption; } @Override public int hashCode() { return Objects.hashCode(value); } @Override
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof DocActionItem) { final DocActionItem other = (DocActionItem)obj; return Objects.equal(value, other.value); } else { return false; } } @Override public String getValue() { return value; } @Override public String getDescription() { return description; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\AbstractDocumentBL.java
1
请完成以下Java代码
public void commit() { if (consumerLock.isLocked()) { if (stopped) { return; } log.error("commit. consumerLock is locked. will wait with no timeout. it looks like a race conditions or deadlock topic " + topic, new RuntimeException("stacktrace")); } consumerLock.lock(); try { doCommit(); } finally { consumerLock.unlock(); } } @Override public void stop() { stopped = true; } @Override public void unsubscribe() { log.info("Unsubscribing and stopping consumer for {}", partitions); stopped = true; consumerLock.lock(); try { if (subscribed) { doUnsubscribe(); } } finally { consumerLock.unlock(); } } @Override public boolean isStopped() {
return stopped; } abstract protected List<R> doPoll(long durationInMillis); abstract protected T decode(R record) throws IOException; abstract protected void doSubscribe(Set<TopicPartitionInfo> partitions); abstract protected void doCommit(); abstract protected void doUnsubscribe(); @Override public Set<TopicPartitionInfo> getPartitions() { return partitions; } @Override public List<String> getFullTopicNames() { if (partitions == null) { return Collections.emptyList(); } return partitions.stream() .map(TopicPartitionInfo::getFullTopicName) .toList(); } protected boolean isLongPollingSupported() { return false; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AbstractTbQueueConsumerTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public class KPIDataSet { String name; String unit; ImmutableList<KPIDataSetValuesMap> values; public static KPIDataSetBuilder builder(@NonNull final String name) { return new KPIDataSetBuilder().name(name); } private KPIDataSet(final KPIDataSetBuilder builder) { this.name = builder.name; this.unit = builder.unit; this.values = builder.valuesByKey .values() .stream() .map(KPIDataSetValuesMap.KPIDataSetValuesMapBuilder::build) .collect(ImmutableList.toImmutableList()); } // // // // // public static class KPIDataSetBuilder { private String name; @Getter @Nullable private String unit; private final Map<KPIDataSetValuesAggregationKey, KPIDataSetValuesMap.KPIDataSetValuesMapBuilder> valuesByKey = new LinkedHashMap<>(); public KPIDataSet build() { return new KPIDataSet(this); }
public KPIDataSetBuilder name(final String name) { this.name = name; return this; } public KPIDataSetBuilder unit(@Nullable final String unit) { this.unit = unit; return this; } public KPIDataSetValuesMap.KPIDataSetValuesMapBuilder dataSetValue(final KPIDataSetValuesAggregationKey dataSetValueKey) { return valuesByKey.computeIfAbsent(dataSetValueKey, KPIDataSetValuesMap::builder); } public void putValue(@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSetValue(dataSetValueKey).put(fieldName, value); } public void putValueIfAbsent(@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value) { dataSetValue(dataSetValueKey).putIfAbsent(fieldName, value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataSet.java
2
请在Spring Boot框架中完成以下Java代码
public class ServerData { private final String source; private final String data; private final long timestamp; private final String state; public ServerData(String source, String data, long timestamp, String state) { this.source = source; this.data = data; this.timestamp = timestamp; this.state = state; } public String getData() {
return data; } public long getTimestamp() { return timestamp; } public String getSource() { return source; } public String getState() { return state; } }
repos\spring-examples-java-17\spring-jcasbin\src\main\java\itx\examples\springboot\security\services\dto\ServerData.java
2
请完成以下Java代码
public void setInvoiceRule(final JsonInvoiceRule invoiceRule) { this.invoiceRule = invoiceRule; this.invoiceRuleSet = true; } public void setUrl(final String url) { this.url = url; this.urlSet = true; } public void setUrl2(final String url2) { this.url2 = url2; this.url2Set = true; } public void setUrl3(final String url3) { this.url3 = url3; this.url3Set = true; } public void setGroup(final String group) { this.group = group; this.groupSet = true; } public void setGlobalId(final String globalId) {
this.globalId = globalId; this.globalIdset = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } public void setVatId(final String vatId) { this.vatId = vatId; this.vatIdSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java
1
请完成以下Java代码
public class BoundaryEventImpl extends CatchEventImpl implements BoundaryEvent { protected static Attribute<Boolean> cancelActivityAttribute; protected static AttributeReference<Activity> attachedToRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BoundaryEvent.class, BPMN_ELEMENT_BOUNDARY_EVENT) .namespaceUri(BPMN20_NS) .extendsType(CatchEvent.class) .instanceProvider(new ModelTypeInstanceProvider<BoundaryEvent>() { public BoundaryEvent newInstance(ModelTypeInstanceContext instanceContext) { return new BoundaryEventImpl(instanceContext); } }); cancelActivityAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_CANCEL_ACTIVITY) .defaultValue(true) .build(); attachedToRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ATTACHED_TO_REF) .required() .qNameAttributeReference(Activity.class) .build(); typeBuilder.build(); } public BoundaryEventImpl(ModelTypeInstanceContext context) { super(context); }
@Override public BoundaryEventBuilder builder() { return new BoundaryEventBuilder((BpmnModelInstance) modelInstance, this); } public boolean cancelActivity() { return cancelActivityAttribute.getValue(this); } public void setCancelActivity(boolean cancelActivity) { cancelActivityAttribute.setValue(this, cancelActivity); } public Activity getAttachedTo() { return attachedToRefAttribute.getReferenceTargetElement(this); } public void setAttachedTo(Activity attachedTo) { attachedToRefAttribute.setReferenceTargetElement(this, attachedTo); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BoundaryEventImpl.java
1
请完成以下Java代码
public class LoopBreaking { public String simpleBreak() { String result = ""; for (int outerCounter = 0; outerCounter < 2; outerCounter++) { result += "outer" + outerCounter; for (int innerCounter = 0; innerCounter < 2; innerCounter++) { result += "inner" + innerCounter; if (innerCounter == 0) { break; } } } return result; } public String labelBreak() { String result = ""; myBreakLabel: for (int outerCounter = 0; outerCounter < 2; outerCounter++) { result += "outer" + outerCounter; for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
result += "inner" + innerCounter; if (innerCounter == 0) { break myBreakLabel; } } } return result; } public String usingReturn() { String result = ""; for (int outerCounter = 0; outerCounter < 2; outerCounter++) { result += "outer" + outerCounter; for (int innerCounter = 0; innerCounter < 2; innerCounter++) { result += "inner" + innerCounter; if (innerCounter == 0) { return result; } } } return "failed"; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-3\src\main\java\com\baeldung\breakloop\LoopBreaking.java
1
请完成以下Java代码
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); String i18nFile = MessageFormat.format("i18n/message_{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; } /** * get val of i18n key * * @param key * @return */ public static String getString(String key) { return loadI18nProp().getProperty(key); }
/** * get mult val of i18n mult key, as json * * @param keys * @return */ public static String getMultString(String... keys) { Map<String, String> map = new HashMap<String, String>(); Properties prop = loadI18nProp(); if (keys!=null && keys.length>0) { for (String key: keys) { map.put(key, prop.getProperty(key)); } } else { for (String key: prop.stringPropertyNames()) { map.put(key, prop.getProperty(key)); } } String json = JacksonUtil.writeValueAsString(map); return json; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\I18nUtil.java
1
请完成以下Java代码
public void createExternalSystemInstance(final I_ExternalSystem_Config_GRSSignum grsConfig) { final ExternalSystemParentConfigId parentConfigId = ExternalSystemParentConfigId.ofRepoId(grsConfig.getExternalSystem_Config_ID()); externalServices.initializeServiceInstancesIfRequired(parentConfigId); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsSyncBPartnersToRestEndpoint) public void updateIsAutoFlag(final I_ExternalSystem_Config_GRSSignum grsConfig) { if (!grsConfig.isSyncBPartnersToRestEndpoint()) { grsConfig.setIsAutoSendVendors(false); grsConfig.setIsAutoSendCustomers(false); } } @ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_ExternalSystem_Config_GRSSignum.COLUMNNAME_IsCreateBPartnerFolders, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BasePathForExportDirectories, I_ExternalSystem_Config_GRSSignum.COLUMNNAME_BPartnerExportDirectories }) public void checkIsCreateBPartnerFoldersFlag(final I_ExternalSystem_Config_GRSSignum grsConfig)
{ if (!grsConfig.isCreateBPartnerFolders()) { return; } if (Check.isBlank(grsConfig.getBPartnerExportDirectories()) || Check.isBlank(grsConfig.getBasePathForExportDirectories())) { throw new AdempiereException("BPartnerExportDirectories and BasePathForExportDirectories must be set!") .appendParametersToMessage() .setParameter("ExternalSystem_Config_GRSSignum_ID", grsConfig.getExternalSystem_Config_GRSSignum_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\grssignum\interceptor\ExternalSystem_Config_GRSSignum.java
1
请在Spring Boot框架中完成以下Java代码
public DeviceToCreateMaintenances lastServiceDate(String lastServiceDate) { this.lastServiceDate = lastServiceDate; return this; } /** * Letzte Prüfung * @return lastServiceDate **/ @Schema(example = "01.06.2020", description = "Letzte Prüfung") public String getLastServiceDate() { return lastServiceDate; } public void setLastServiceDate(String lastServiceDate) { this.lastServiceDate = lastServiceDate; } public DeviceToCreateMaintenances nextServiceDate(String nextServiceDate) { this.nextServiceDate = nextServiceDate; return this; } /** * Nächste Prüfung * @return nextServiceDate **/ @Schema(example = "01.12.2020", description = "Nächste Prüfung") public String getNextServiceDate() { return nextServiceDate; } public void setNextServiceDate(String nextServiceDate) { this.nextServiceDate = nextServiceDate; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeviceToCreateMaintenances deviceToCreateMaintenances = (DeviceToCreateMaintenances) o; return Objects.equals(this.maintenanceCode, deviceToCreateMaintenances.maintenanceCode) && Objects.equals(this.maintenanceInterval, deviceToCreateMaintenances.maintenanceInterval) && Objects.equals(this.lastServiceDate, deviceToCreateMaintenances.lastServiceDate) && Objects.equals(this.nextServiceDate, deviceToCreateMaintenances.nextServiceDate); }
@Override public int hashCode() { return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DeviceToCreateMaintenances {\n"); sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n"); sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n"); sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n"); sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java
2
请在Spring Boot框架中完成以下Java代码
protected Class<? extends Annotation> getAnnotationType() { return UseLocators.class; } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { if (isAnnotationPresent(importMetadata)) { AnnotationAttributes useLocatorsAttributes = getAnnotationAttributes(importMetadata); setLocators(useLocatorsAttributes.containsKey("locators") ? useLocatorsAttributes.getString("locators") : null); setRemoteLocators(useLocatorsAttributes.containsKey("remoteLocators") ? useLocatorsAttributes.getString("remoteLocators") : null); } } protected void setLocators(String locators) { this.locators = StringUtils.hasText(locators) ? locators : null; } protected Optional<String> getLocators() { return Optional.ofNullable(this.locators) .filter(StringUtils::hasText); } protected Logger getLogger() { return this.logger; } protected void setRemoteLocators(String remoteLocators) { this.remoteLocators = StringUtils.hasText(remoteLocators) ? remoteLocators : null; } protected Optional<String> getRemoteLocators() { return Optional.ofNullable(this.remoteLocators) .filter(StringUtils::hasText); } @Bean ClientCacheConfigurer clientCacheLocatorsConfigurer() { return (beanName, clientCacheFactoryBean) -> { Logger logger = getLogger(); getLocators().ifPresent(locators -> {
if (logger.isWarnEnabled()) { logger.warn("The '{}' property was configured [{}];" + " however, this value does not have any effect for ClientCache instances", LOCATORS_PROPERTY, locators); } }); getRemoteLocators().ifPresent(remoteLocators -> { if (logger.isWarnEnabled()) { logger.warn("The '{}' property was configured [{}];" + " however, this value does not have any effect for ClientCache instances", REMOTE_LOCATORS_PROPERTY, remoteLocators); } }); }; } @Bean LocatorConfigurer locatorLocatorsConfigurer() { return (beanName, locatorFactoryBean) -> { Properties gemfireProperties = locatorFactoryBean.getGemFireProperties(); getLocators().ifPresent(locators -> gemfireProperties.setProperty(LOCATORS_PROPERTY, locators)); getRemoteLocators().ifPresent(remoteLocators -> gemfireProperties.setProperty(REMOTE_LOCATORS_PROPERTY, remoteLocators)); }; } @Bean PeerCacheConfigurer peerCacheLocatorsConfigurer() { return (beanName, cacheFactoryBean) -> { Properties gemfireProperties = cacheFactoryBean.getProperties(); getLocators().ifPresent(locators -> gemfireProperties.setProperty(LOCATORS_PROPERTY, locators)); getRemoteLocators().ifPresent(remoteLocators -> gemfireProperties.setProperty(REMOTE_LOCATORS_PROPERTY, remoteLocators)); }; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\LocatorsConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public boolean deleteAndStopJob(QuartzJob job) { schedulerDelete(job.getId()); boolean ok = this.removeById(job.getId()); return ok; } @Override public void execute(QuartzJob quartzJob) throws Exception { String jobName = quartzJob.getJobClassName().trim(); Date startDate = new Date(); String ymd = DateUtils.date2Str(startDate,DateUtils.yyyymmddhhmmss.get()); String identity = jobName + ymd; //3秒后执行 只执行一次 // 代码逻辑说明: 定时任务立即执行,延迟3秒改成0.1秒------- startDate.setTime(startDate.getTime() + 100L); // 定义一个Trigger SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger() .withIdentity(identity, JOB_TEST_GROUP) .startAt(startDate) .build(); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(getClass(jobName).getClass()).withIdentity(identity).usingJobData("parameter", quartzJob.getParameter()).build(); // 将trigger和 jobDetail 加入这个调度 scheduler.scheduleJob(jobDetail, trigger); // 启动scheduler scheduler.start(); } @Override @Transactional(rollbackFor = JeecgBootException.class) public void pause(QuartzJob quartzJob){ schedulerDelete(quartzJob.getId()); quartzJob.setStatus(CommonConstant.STATUS_DISABLE); this.updateById(quartzJob); } /** * 添加定时任务 * * @param jobClassName * @param cronExpression * @param parameter */ private void schedulerAdd(String id, String jobClassName, String cronExpression, String parameter) { try { // 启动调度器 scheduler.start(); // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(id).usingJobData("parameter", parameter).build();
// 表达式调度构建器(即任务执行的时间) CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression); // 按新的cronExpression表达式构建一个新的trigger CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(id).withSchedule(scheduleBuilder).build(); scheduler.scheduleJob(jobDetail, trigger); } catch (SchedulerException e) { throw new JeecgBootException("创建定时任务失败", e); } catch (RuntimeException e) { throw new JeecgBootException(e.getMessage(), e); }catch (Exception e) { throw new JeecgBootException("后台找不到该类名:" + jobClassName, e); } } /** * 删除定时任务 * * @param id */ private void schedulerDelete(String id) { try { scheduler.pauseTrigger(TriggerKey.triggerKey(id)); scheduler.unscheduleJob(TriggerKey.triggerKey(id)); scheduler.deleteJob(JobKey.jobKey(id)); } catch (Exception e) { log.error(e.getMessage(), e); throw new JeecgBootException("删除定时任务失败"); } } private static Job getClass(String classname) throws Exception { Class<?> class1 = Class.forName(classname); return (Job) class1.newInstance(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\quartz\service\impl\QuartzJobServiceImpl.java
2
请完成以下Java代码
public <JSONType> ResponseEntity<JSONType> toDocumentJson(final BiFunction<R, JSONDocumentOptions, JSONType> toJsonMapper) { return toResponseEntity((responseBuilder, result) -> responseBuilder.body(toJsonMapper.apply(result, getJSONDocumentOptions()))); } public <BodyType> ResponseEntity<BodyType> toResponseEntity(final BiFunction<ResponseEntity.BodyBuilder, R, ResponseEntity<BodyType>> toJsonMapper) { // Check ETag final String etag = getETag().toETagString(); if (request.checkNotModified(etag)) { // Response: 304 Not Modified return newResponse(HttpStatus.NOT_MODIFIED, etag).build(); } // Get the result and convert it to JSON final R result = this.result.get(); final ResponseEntity.BodyBuilder newResponse = newResponse(HttpStatus.OK, etag); return toJsonMapper.apply(newResponse, result); } private final ResponseEntity.BodyBuilder newResponse(final HttpStatus status, final String etag) {
ResponseEntity.BodyBuilder response = ResponseEntity.status(status) .eTag(etag) .cacheControl(CacheControl.maxAge(cacheMaxAgeSec, TimeUnit.SECONDS)); final String adLanguage = getAdLanguage(); if (adLanguage != null && !adLanguage.isEmpty()) { final String contentLanguage = ADLanguageList.toHttpLanguageTag(adLanguage); response.header(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); response.header(HttpHeaders.VARY, HttpHeaders.ACCEPT_LANGUAGE); // advice browser to include ACCEPT_LANGUAGE in their caching key } return response; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETagResponseEntityBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class DataSourceItemReaderDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; // 注入数据源 @Autowired private DataSource dataSource; @Bean public Job dataSourceItemReaderJob() throws Exception { return jobBuilderFactory.get("dataSourceItemReaderJob") .start(step()) .build(); } private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(dataSourceItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> dataSourceItemReader() throws Exception { JdbcPagingItemReader<TestData> reader = new JdbcPagingItemReader<>(); reader.setDataSource(dataSource); // 设置数据源 reader.setFetchSize(5); // 每次取多少条记录 reader.setPageSize(5); // 设置每页数据量 // 指定sql查询语句 select id,field1,field2,field3 from TEST MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider(); provider.setSelectClause("id,field1,field2,field3"); //设置查询字段 provider.setFromClause("from TEST"); // 设置从哪张表查询
// 将读取到的数据转换为TestData对象 reader.setRowMapper((resultSet, rowNum) -> { TestData data = new TestData(); data.setId(resultSet.getInt(1)); data.setField1(resultSet.getString(2)); // 读取第一个字段,类型为String data.setField2(resultSet.getString(3)); data.setField3(resultSet.getString(4)); return data; }); Map<String, Order> sort = new HashMap<>(1); sort.put("id", Order.ASCENDING); provider.setSortKeys(sort); // 设置排序,通过id 升序 reader.setQueryProvider(provider); // 设置namedParameterJdbcTemplate等属性 reader.afterPropertiesSet(); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\DataSourceItemReaderDemo.java
2
请完成以下Java代码
public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToConstant(final String toColumnName, final Object constantValue) { final IQueryInsertFromColumn from = new ConstantQueryInsertFromColumn(constantValue); mapColumn(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToSql(final String toColumnName, final String fromSql) { final IQueryInsertFromColumn from = new SqlQueryInsertFromColumn(fromSql); mapColumn(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> mapPrimaryKey() { final String toColumnName = getToKeyColumnName(); final IQueryInsertFromColumn from = new PrimaryKeyQueryInsertFromColumn(getToTableName()); mapColumn(toColumnName, from); return this; } @Override public QueryInsertExecutor<ToModelType, FromModelType> creatingSelectionOfInsertedRows() { this.createSelectionOfInsertedRows = true; return this; } /* package */ boolean isCreateSelectionOfInsertedRows() { return createSelectionOfInsertedRows; } /* package */String getToKeyColumnName() { return InterfaceWrapperHelper.getKeyColumnName(toModelClass); } /** * @return "To ColumnName" to "From Column" map */
/* package */ Map<String, IQueryInsertFromColumn> getColumnMapping() { return toColumn2fromColumnRO; } /* package */ boolean isEmpty() { return toColumn2fromColumn.isEmpty(); } /* package */ String getToTableName() { return toTableName; } /* package */ Class<ToModelType> getToModelClass() { return toModelClass; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryInsertExecutor.java
1
请完成以下Java代码
public Mono<User> updateUser(UpdateUserRequest request, User user) { ofNullable(request.getBio()) .ifPresent(user::setBio); ofNullable(request.getImage()) .ifPresent(user::setImage); ofNullable(request.getPassword()) .ifPresent(password -> updatePassword(password, user)); return updateUsername(request, user) .then(updateEmail(request, user)) .thenReturn(user); } private void updatePassword(String password, User user) { var encodedPassword = passwordService.encodePassword(password); user.setEncodedPassword(encodedPassword); } private Mono<?> updateUsername(UpdateUserRequest request, User user) { if (request.getUsername() == null) { return Mono.empty(); } if (request.getUsername().equals(user.getUsername())) { return Mono.empty(); } return userRepository.existsByUsername(request.getUsername()) .doOnNext(existsByUsername -> updateUsername(request, user, existsByUsername)); } private void updateUsername(UpdateUserRequest request, User user, boolean existsByUsername) { if (existsByUsername) { throw usernameAlreadyInUseException(); } user.setUsername(request.getUsername()); } private Mono<?> updateEmail(UpdateUserRequest request, User user) { if (request.getEmail() == null) {
return Mono.empty(); } if (request.getEmail().equals(user.getEmail())) { return Mono.empty(); } return userRepository.existsByEmail(request.getEmail()) .doOnNext(existsByEmail -> updateEmail(request, user, existsByEmail)); } private void updateEmail(UpdateUserRequest request, User user, boolean existsByEmail) { if (existsByEmail) { throw emailAlreadyInUseException(); } user.setEmail(request.getEmail()); } private InvalidRequestException usernameAlreadyInUseException() { return new InvalidRequestException("Username", "already in use"); } private InvalidRequestException emailAlreadyInUseException() { return new InvalidRequestException("Email", "already in use"); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\UserUpdater.java
1
请完成以下Java代码
public IAttributeSetInstanceAware createOrNull(final Object model) { if (model == null) { return null; } if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OLCand.class)) { return null; } final I_C_OLCand olCand = InterfaceWrapperHelper.create(model, I_C_OLCand.class); // note: returning an anonymous implementation because it is rather trivial and it feels a bit like pollution to add another "real" class just for this purpose. return new IAttributeSetInstanceAware() { @Override public I_M_Product getM_Product() { return Services.get(IOLCandEffectiveValuesBL.class).getM_Product_Effective(olCand); } @Override public int getM_Product_ID() { final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class); return ProductId.toRepoId(olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand)); } @Override public I_M_AttributeSetInstance getM_AttributeSetInstance() { return olCand.getM_AttributeSetInstance(); } @Override public int getM_AttributeSetInstance_ID()
{ return olCand.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi) { olCand.setM_AttributeSetInstance(asi); } @Override public String toString() { return "IAttributeSetInstanceAware[" + olCand.toString() + "]"; } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandASIAwareFactory.java
1
请完成以下Java代码
public I_ExternalSystem_Config_Shopware6 getExternalSystem_Config_Shopware6() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_Shopware6_ID, I_ExternalSystem_Config_Shopware6.class); } @Override public void setExternalSystem_Config_Shopware6(final I_ExternalSystem_Config_Shopware6 ExternalSystem_Config_Shopware6) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_Shopware6_ID, I_ExternalSystem_Config_Shopware6.class, ExternalSystem_Config_Shopware6); } @Override public void setExternalSystem_Config_Shopware6_ID (final int ExternalSystem_Config_Shopware6_ID) { if (ExternalSystem_Config_Shopware6_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_Shopware6_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_Shopware6_ID, ExternalSystem_Config_Shopware6_ID); } @Override public int getExternalSystem_Config_Shopware6_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_ID); } @Override
public void setExternalSystem_Config_Shopware6_UOM_ID (final int ExternalSystem_Config_Shopware6_UOM_ID) { if (ExternalSystem_Config_Shopware6_UOM_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, ExternalSystem_Config_Shopware6_UOM_ID); } @Override public int getExternalSystem_Config_Shopware6_UOM_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID); } @Override public void setShopwareCode (final String ShopwareCode) { set_Value (COLUMNNAME_ShopwareCode, ShopwareCode); } @Override public String getShopwareCode() { return get_ValueAsString(COLUMNNAME_ShopwareCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6_UOM.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_Job_ID (final int AD_User_Occupation_Job_ID) { if (AD_User_Occupation_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, AD_User_Occupation_Job_ID); } @Override public int getAD_User_Occupation_Job_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Job_ID); } @Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation() { return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); }
@Override public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Job.java
1
请在Spring Boot框架中完成以下Java代码
public class MongoConfig extends AbstractMongoClientConfiguration { @Override protected String getDatabaseName() { return "test"; } @Override public MongoClient mongoClient() { final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); final MongoClientSettings mongoClientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .build(); return MongoClients.create(mongoClientSettings); } @Override public Collection<String> getMappingBasePackages() { return Collections.singleton("com.baeldung"); }
@Bean public UserCascadeSaveMongoEventListener userCascadingMongoEventListener() { return new UserCascadeSaveMongoEventListener(); } @Bean public CascadeSaveMongoEventListener cascadingMongoEventListener() { return new CascadeSaveMongoEventListener(); } @Bean MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { return new MongoTransactionManager(dbFactory); } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\config\MongoConfig.java
2
请完成以下Java代码
public class ReactiveApplicationFactory extends DefaultApplicationFactory { private final ManagementServerProperties management; private final ServerProperties server; private final WebFluxProperties webflux; private final InstanceProperties instance; public ReactiveApplicationFactory(InstanceProperties instance, ManagementServerProperties management, ServerProperties server, PathMappedEndpoints pathMappedEndpoints, WebEndpointProperties webEndpoint, MetadataContributor metadataContributor, WebFluxProperties webFluxProperties) { super(instance, management, server, pathMappedEndpoints, webEndpoint, metadataContributor); this.management = management; this.server = server; this.webflux = webFluxProperties; this.instance = instance; } @Override protected String getServiceUrl() { if (instance.getServiceUrl() != null) { return instance.getServiceUrl(); } return UriComponentsBuilder.fromUriString(getServiceBaseUrl()) .path(getServicePath()) .path(getWebfluxBasePath()) .toUriString(); } @Override
protected String getManagementBaseUrl() { String baseUrl = this.instance.getManagementBaseUrl(); if (StringUtils.hasText(baseUrl)) { return baseUrl; } if (isManagementPortEqual()) { return this.getServiceUrl(); } Ssl ssl = (this.management.getSsl() != null) ? this.management.getSsl() : this.server.getSsl(); return UriComponentsBuilder.newInstance() .scheme(getScheme(ssl)) .host(getManagementHost()) .port(getLocalManagementPort()) .path(getManagementContextPath()) .toUriString(); } protected String getManagementContextPath() { return management.getBasePath(); } protected String getWebfluxBasePath() { return webflux.getBasePath(); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\ReactiveApplicationFactory.java
1
请完成以下Java代码
public class C_Doc_Outbound_Log_SendPDFMails extends JavaProcess implements IProcessPrecondition { private static final AdMessageKey MSG_EMPTY_MailTo = AdMessageKey.of("SendMailsForSelection.EMPTY_MailTo"); private static final AdMessageKey MSG_No_DocOutboundLog_Selection = AdMessageKey.of("AbstractMailDocumentsForSelection.No_DocOutboundLog_Selection"); private static final String PARA_OnlyNotSentMails = "OnlyNotSentMails"; @NonNull private final transient DocOutboundService docOutboundService = SpringContextHolder.instance.getBean(DocOutboundService.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { final SelectionSize selectionSize = context.getSelectionSize(); if (selectionSize.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (selectionSize.isAllSelected() || selectionSize.getSize() > 500) { // Checking is too expensive; just assume that some selected records have an email address return ProcessPreconditionsResolution.accept(); } final boolean atLeastOneRecordHasEmail = context .streamSelectedModels(I_C_Doc_Outbound_Log.class) .anyMatch(record -> !Check.isEmpty(record.getCurrentEMailAddress(), true)); if (!atLeastOneRecordHasEmail) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_EMPTY_MailTo)); }
return ProcessPreconditionsResolution.accept(); } @Param(parameterName = PARA_OnlyNotSentMails, mandatory=true) private boolean p_OnlyNotSentMails = false; @Override protected final void prepare() { if (docOutboundService.retrieveLogs(getFilter(), true).isEmpty()) { throw new AdempiereException(MSG_No_DocOutboundLog_Selection); } } protected IQueryFilter<I_C_Doc_Outbound_Log> getFilter() { final ProcessInfo pi = getProcessInfo(); return pi.getQueryFilterOrElse(ConstantQueryFilter.of(false)); } @Override @RunOutOfTrx protected final String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); final int counter = docOutboundService.sendMails( getFilter(), pinstanceId, p_OnlyNotSentMails); return msgBL.getMsg(Async_Constants.MSG_WORKPACKAGES_CREATED, ImmutableList.of(counter)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\process\C_Doc_Outbound_Log_SendPDFMails.java
1
请完成以下Java代码
public CountryAwareAttributeUpdater setSourceModel(final Object sourceModel) { this.sourceModel = sourceModel; return this; } private Object getSourceModel() { Check.assumeNotNull(sourceModel, "sourceModel not null"); return sourceModel; } private String getSourceTableName() { return InterfaceWrapperHelper.getModelTableName(getSourceModel()); } public CountryAwareAttributeUpdater setCountryAwareFactory(final ICountryAwareFactory countryAwareFactory) { this.countryAwareFactory = countryAwareFactory; return this; }
private ICountryAwareFactory getCountryAwareFactory() { Check.assumeNotNull(countryAwareFactory, "countryAwareFactory not null"); return countryAwareFactory; } public final CountryAwareAttributeUpdater setCountryAwareAttributeService(final ICountryAwareAttributeService countryAwareAttributeService) { this.countryAwareAttributeService = countryAwareAttributeService; return this; } private ICountryAwareAttributeService getCountryAwareAttributeService() { Check.assumeNotNull(countryAwareAttributeService, "countryAwareAttributeService not null"); return countryAwareAttributeService; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\CountryAwareAttributeUpdater.java
1
请完成以下Java代码
public String getDescription() { return description; } /** * 设置 角色说明. * * @param description 角色说明. */ public void setDescription(String description) { this.description = description; } /** * 获取 创建时间. * * @return 创建时间. */ public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 更新时间. * * @return 更新时间. */
public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Role.java
1
请完成以下Java代码
public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { this.processDefinitionKeyIn = processDefinitionKeyIn; } @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } @Override protected HistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricProcessInstanceReport(); } @Override protected void applyFilters(HistoricProcessInstanceReport reportQuery) { if (processDefinitionIdIn != null && processDefinitionIdIn.length > 0) { reportQuery.processDefinitionIdIn(processDefinitionIdIn); }
if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { reportQuery.processDefinitionKeyIn(processDefinitionKeyIn); } if (startedAfter != null) { reportQuery.startedAfter(startedAfter); } if (startedBefore != null) { reportQuery.startedBefore(startedBefore); } if (!REPORT_TYPE_DURATION.equals(reportType)) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unknown report type " + reportType); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricProcessInstanceReportDto.java
1
请完成以下Java代码
public class FormDataWithFile { private String name; private String email; private MultipartFile file; 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; } public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } }
repos\tutorials-master\spring-web-modules\spring-mvc-java\src\main\java\com\baeldung\model\FormDataWithFile.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getBasename() { return this.basename; } public void setBasename(List<String> basename) { this.basename = basename; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } public @Nullable Duration getCacheDuration() { return this.cacheDuration; } public void setCacheDuration(@Nullable Duration cacheDuration) { this.cacheDuration = cacheDuration; } public boolean isFallbackToSystemLocale() { return this.fallbackToSystemLocale; } public void setFallbackToSystemLocale(boolean fallbackToSystemLocale) { this.fallbackToSystemLocale = fallbackToSystemLocale;
} public boolean isAlwaysUseMessageFormat() { return this.alwaysUseMessageFormat; } public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) { this.alwaysUseMessageFormat = alwaysUseMessageFormat; } public boolean isUseCodeAsDefaultMessage() { return this.useCodeAsDefaultMessage; } public void setUseCodeAsDefaultMessage(boolean useCodeAsDefaultMessage) { this.useCodeAsDefaultMessage = useCodeAsDefaultMessage; } public @Nullable List<Resource> getCommonMessages() { return this.commonMessages; } public void setCommonMessages(@Nullable List<Resource> commonMessages) { this.commonMessages = commonMessages; } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class TaxType { @XmlElement(name = "VAT") protected VATType vat; @XmlElement(name = "OtherTax") protected List<OtherTaxType> otherTax; /** * Used to provide information about the VAT or a potential tax exemptation (if applicable). * * @return * possible object is * {@link VATType } * */ public VATType getVAT() { return vat; } /** * Sets the value of the vat property. * * @param value * allowed object is * {@link VATType } * */ public void setVAT(VATType value) { this.vat = value; } /** * Used to provide information about other tax.Gets the value of the otherTax property. * * <p>
* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the otherTax property. * * <p> * For example, to add a new item, do as follows: * <pre> * getOtherTax().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link OtherTaxType } * * */ public List<OtherTaxType> getOtherTax() { if (otherTax == null) { otherTax = new ArrayList<OtherTaxType>(); } return this.otherTax; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\TaxType.java
2
请完成以下Java代码
public boolean isMethodInvocation() { return getChild(0).isMethodInvocation(); } public ValueReference getValueReference(Bindings bindings, ELContext context) { return child.getValueReference(bindings, context); } @Override public Object eval(Bindings bindings, ELContext context) { return child.eval(bindings, context); } @Override public String toString() { return (deferred ? "#" : "$") + "{...}"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { b.append(deferred ? "#{" : "${"); child.appendStructure(b, bindings); b.append("}"); } public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return child.getMethodInfo(bindings, context, returnType, paramTypes); } public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return child.invoke(bindings, context, returnType, paramTypes, paramValues); } public Class<?> getType(Bindings bindings, ELContext context) {
return child.getType(bindings, context); } public boolean isLiteralText() { return child.isLiteralText(); } public boolean isReadOnly(Bindings bindings, ELContext context) { return child.isReadOnly(bindings, context); } public void setValue(Bindings bindings, ELContext context, Object value) { child.setValue(bindings, context, value); } public int getCardinality() { return 1; } public AstNode getChild(int i) { return i == 0 ? child : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstEval.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Duration getConnectTimeout() { return this.connectTimeout; } public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Duration getReadTimeout() { return this.readTimeout; } public void setReadTimeout(Duration readTimeout) { this.readTimeout = readTimeout; } public Integer getNumThreads() { return this.numThreads; } public void setNumThreads(Integer numThreads) { this.numThreads = numThreads; } public Integer getBatchSize() { return this.batchSize; } public void setBatchSize(Integer batchSize) { this.batchSize = batchSize; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } public Duration getMeterTimeToLive() { return this.meterTimeToLive; } public void setMeterTimeToLive(Duration meterTimeToLive) { this.meterTimeToLive = meterTimeToLive; } public boolean isLwcEnabled() { return this.lwcEnabled; } public void setLwcEnabled(boolean lwcEnabled) { this.lwcEnabled = lwcEnabled; } public Duration getLwcStep() { return this.lwcStep; } public void setLwcStep(Duration lwcStep) { this.lwcStep = lwcStep; } public boolean isLwcIgnorePublishStep() { return this.lwcIgnorePublishStep;
} public void setLwcIgnorePublishStep(boolean lwcIgnorePublishStep) { this.lwcIgnorePublishStep = lwcIgnorePublishStep; } public Duration getConfigRefreshFrequency() { return this.configRefreshFrequency; } public void setConfigRefreshFrequency(Duration configRefreshFrequency) { this.configRefreshFrequency = configRefreshFrequency; } public Duration getConfigTimeToLive() { return this.configTimeToLive; } public void setConfigTimeToLive(Duration configTimeToLive) { this.configTimeToLive = configTimeToLive; } public String getConfigUri() { return this.configUri; } public void setConfigUri(String configUri) { this.configUri = configUri; } public String getEvalUri() { return this.evalUri; } public void setEvalUri(String evalUri) { this.evalUri = evalUri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
2
请完成以下Java代码
public class PersistHistoricDecisionExecutionCmd implements Command<Void> { protected ExecuteDecisionContext executeDecisionContext; public PersistHistoricDecisionExecutionCmd(ExecuteDecisionContext executeDecisionContext) { this.executeDecisionContext = executeDecisionContext; } @Override public Void execute(CommandContext commandContext) { if (executeDecisionContext == null) { throw new FlowableIllegalArgumentException("ExecuteDecisionContext is null"); } DmnEngineConfiguration engineConfiguration = CommandContextUtil.getDmnEngineConfiguration(); if (engineConfiguration.isHistoryEnabled()) { HistoricDecisionExecutionEntityManager historicDecisionExecutionEntityManager = engineConfiguration.getHistoricDecisionExecutionEntityManager(); HistoricDecisionExecutionEntity decisionExecutionEntity = historicDecisionExecutionEntityManager.create(); decisionExecutionEntity.setDecisionDefinitionId(executeDecisionContext.getDecisionId()); decisionExecutionEntity.setDeploymentId(executeDecisionContext.getDeploymentId()); decisionExecutionEntity.setStartTime(executeDecisionContext.getDecisionExecution().getStartTime()); decisionExecutionEntity.setEndTime(executeDecisionContext.getDecisionExecution().getEndTime()); decisionExecutionEntity.setInstanceId(executeDecisionContext.getInstanceId()); decisionExecutionEntity.setExecutionId(executeDecisionContext.getExecutionId()); decisionExecutionEntity.setActivityId(executeDecisionContext.getActivityId()); decisionExecutionEntity.setScopeType(executeDecisionContext.getScopeType()); decisionExecutionEntity.setTenantId(executeDecisionContext.getTenantId()); Boolean failed = executeDecisionContext.getDecisionExecution().isFailed(); if (BooleanUtils.isTrue(failed)) {
decisionExecutionEntity.setFailed(failed.booleanValue()); } ObjectMapper objectMapper = engineConfiguration.getObjectMapper(); if (objectMapper == null) { objectMapper = JsonMapper.shared(); } try { decisionExecutionEntity.setExecutionJson(objectMapper.writeValueAsString(executeDecisionContext.getDecisionExecution())); } catch (Exception e) { throw new FlowableException("Error writing execution json", e); } historicDecisionExecutionEntityManager.insert(decisionExecutionEntity); } return null; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\cmd\PersistHistoricDecisionExecutionCmd.java
1
请完成以下Java代码
protected void onAfterInit() { registerFactories(); // task 08452 Services.get(IReceiptScheduleBL.class).addReceiptScheduleListener(OrderLineReceiptScheduleListener.INSTANCE); } /** * Public for testing purposes only! */ public static void registerRSAggregationKeyDependencies() { final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class); final String registrationKey = ReceiptScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY; // // Register Handlers keyRegistry.registerAggregationKeyValueHandler(registrationKey, new ReceiptScheduleKeyValueHandler()); // // Register ReceiptScheduleHeaderAggregationKeyBuilder keyRegistry.registerDependsOnColumnnames(registrationKey, I_M_ReceiptSchedule.COLUMNNAME_C_DocType_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Location_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BP_Location_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID, I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_User_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID, I_M_ReceiptSchedule.COLUMNNAME_DateOrdered, I_M_ReceiptSchedule.COLUMNNAME_C_Order_ID, I_M_ReceiptSchedule.COLUMNNAME_POReference); } public void registerFactories() { Services.get(IAttributeSetInstanceAwareFactoryService.class) .registerFactoryForTableName(I_M_ReceiptSchedule.Table_Name, new ReceiptScheduleASIAwareFactory()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\ReceiptScheduleValidator.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day)
*/ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobAssignment.java
1
请完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; private String title; private String isbn; private String genre; private int price; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getGenre() { return genre;
} public void setGenre(String genre) { this.genre = genre; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Book{" + "title=" + title + ", isbn=" + isbn + ", genre=" + genre + ", price=" + price + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoElementCollection\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public void setDATE3(String value) { this.date3 = value; } /** * Gets the value of the date4 property. * * @return * possible object is * {@link String } * */ public String getDATE4() { return date4; } /** * Sets the value of the date4 property. * * @param value * allowed object is * {@link String } * */ public void setDATE4(String value) { this.date4 = value; }
/** * Gets the value of the date5 property. * * @return * possible object is * {@link String } * */ public String getDATE5() { return date5; } /** * Sets the value of the date5 property. * * @param value * allowed object is * {@link String } * */ public void setDATE5(String value) { this.date5 = 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\DPLQU1.java
2
请在Spring Boot框架中完成以下Java代码
public class BasicApplication { // Register Servlet @Bean public ServletRegistrationBean servletRegistrationBean() { ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(), "/myServlet"); return bean; } // Register Filter @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean bean = new FilterRegistrationBean((Filter) new MyFilter()); // Mapping filter to a Servlet bean.addServletRegistrationBeans(new ServletRegistrationBean[] { servletRegistrationBean() }); return bean; }
// Register ServletContextListener @Bean public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean() { ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<>(); bean.setListener(new MyServletContextListener()); return bean; } public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } }
repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSources\SpringServletFilter\src\main\java\spring\basic\BasicApplication.java
2
请完成以下Java代码
public class StockDetailsView extends AbstractCustomView<StockDetailsRow> { private final ViewId parentViewId; protected StockDetailsView( final ViewId viewId, final ViewId parentViewId, final IRowsData<StockDetailsRow> rowsData, final DocumentFilterDescriptorsProvider viewFilterDescriptors) { super( Check.assumeNotNull(viewId, "viewId"), null, // description Check.assumeNotNull(rowsData, "rowsData"), Check.assumeNotNull(viewFilterDescriptors, "viewFilterDescriptors")); this.parentViewId = parentViewId; } public static StockDetailsView cast(IView view)
{ return (StockDetailsView)view; } @Override public String getTableNameOrNull(DocumentId IGNORED) { return I_M_HU_Stock_Detail_V.Table_Name; } @Override public ViewId getParentViewId() { return parentViewId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\stockdetails\StockDetailsView.java
1
请完成以下Java代码
public I_M_Locator getM_Locator() { return locator; } public DistributionNetworkLine getDD_NetworkDistributionLine() { loadIfNeeded(); return networkLine; } public ResourceId getRawMaterialsPlantId() { loadIfNeeded(); return rawMaterialsPlantId; } public I_M_Warehouse getRawMaterialsWarehouse() { loadIfNeeded(); return rawMaterialsWarehouse; } public I_M_Locator getRawMaterialsLocator() { loadIfNeeded(); return rawMaterialsLocator; }
public OrgId getOrgId() { loadIfNeeded(); return orgId; } public BPartnerLocationId getOrgBPLocationId() { loadIfNeeded(); return orgBPLocationId; } public UserId getPlannerId() { loadIfNeeded(); return productPlanning == null ? null : productPlanning.getPlannerId(); } public WarehouseId getInTransitWarehouseId() { loadIfNeeded(); return inTransitWarehouseId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\RawMaterialsReturnDDOrderLineCandidate.java
1
请完成以下Java代码
public java.sql.Timestamp getExternallyUpdatedAt() { return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt); } @Override public void setIsArchived (final boolean IsArchived) { set_Value (COLUMNNAME_IsArchived, IsArchived); } @Override public boolean isArchived() { return get_ValueAsBoolean(COLUMNNAME_IsArchived); } @Override public void setIsInitialCare (final boolean IsInitialCare) { set_Value (COLUMNNAME_IsInitialCare, IsInitialCare); } @Override public boolean isInitialCare() { return get_ValueAsBoolean(COLUMNNAME_IsInitialCare); } @Override public void setIsSeriesOrder (final boolean IsSeriesOrder) { set_Value (COLUMNNAME_IsSeriesOrder, IsSeriesOrder); } @Override public boolean isSeriesOrder() { return get_ValueAsBoolean(COLUMNNAME_IsSeriesOrder); } @Override
public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery) { set_Value (COLUMNNAME_NextDelivery, NextDelivery); } @Override public java.sql.Timestamp getNextDelivery() { return get_ValueAsTimestamp(COLUMNNAME_NextDelivery); } @Override public void setRootId (final @Nullable String RootId) { set_Value (COLUMNNAME_RootId, RootId); } @Override public String getRootId() { return get_ValueAsString(COLUMNNAME_RootId); } @Override public void setStartDate (final @Nullable java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } @Override public java.sql.Timestamp getStartDate() { return get_ValueAsTimestamp(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_Order.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode) { return huQRCodeService.getHuIdByQRCodeIfExists(qrCode); } public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId) { final boolean ensureSingleAssignment = true; huQRCodeService.assign(qrCode, huId, ensureSingleAssignment); } public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId) { return huQRCodeService.getFirstQRCodeByHuId(huId); } public Quantity getHUCapacity( @NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final I_C_UOM uom) { final I_M_HU hu = handlingUnitsBL.getById(huId); return handlingUnitsBL .getStorageFactory() .getStorage(hu) .getQuantity(productId, uom); } @NonNull public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId) { final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId) .stream() .map(locatorId -> { final String caption = getLocatorName(locatorId); return LocatorInfo.builder() .id(locatorId) .caption(caption) .qrCode(LocatorQRCode.builder() .locatorId(locatorId) .caption(caption)
.build()) .build(); }) .collect(ImmutableList.toImmutableList()); return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList); } @NonNull public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId) { return productBL.getCatchUOMId(productId); } @NonNull private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId) { final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId); return handlingUnitsBL.getLocatorIds(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java
2
请完成以下Java代码
public int getAD_Table_ID() { return AD_Table_ID; } public int getAD_Column_ID() { return AD_Column_ID; } public int getRecord_ID() { return record_ID; } public int getAD_Client_ID() { return AD_Client_ID; } public int getAD_Org_ID() { return AD_Org_ID; } public Object getOldValue() { return oldValue; } public Object getNewValue() { return newValue; } public String getEventType() { return eventType; } public int getAD_User_ID() { return AD_User_ID; } public PInstanceId getAD_PInstance_ID() { return AD_PInstance_ID; } public static final class Builder { private int AD_Session_ID; private String trxName; private int AD_Table_ID; private int AD_Column_ID; private int record_ID; private int AD_Client_ID; private int AD_Org_ID; private Object oldValue; private Object newValue; private String eventType; private int AD_User_ID; private PInstanceId AD_PInstance_ID; private Builder() { super(); } public ChangeLogRecord build() { return new ChangeLogRecord(this); } public Builder setAD_Session_ID(final int AD_Session_ID) { this.AD_Session_ID = AD_Session_ID; return this; } public Builder setTrxName(final String trxName) { this.trxName = trxName; return this; } public Builder setAD_Table_ID(final int AD_Table_ID) { this.AD_Table_ID = AD_Table_ID; return this; } public Builder setAD_Column_ID(final int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public Builder setRecord_ID(final int record_ID) {
this.record_ID = record_ID; return this; } public Builder setAD_Client_ID(final int AD_Client_ID) { this.AD_Client_ID = AD_Client_ID; return this; } public Builder setAD_Org_ID(final int AD_Org_ID) { this.AD_Org_ID = AD_Org_ID; return this; } public Builder setOldValue(final Object oldValue) { this.oldValue = oldValue; return this; } public Builder setNewValue(final Object newValue) { this.newValue = newValue; return this; } public Builder setEventType(final String eventType) { this.eventType = eventType; return this; } public Builder setAD_User_ID(final int AD_User_ID) { this.AD_User_ID = AD_User_ID; return this; } /** * * @param AD_PInstance_ID * @return * @task https://metasfresh.atlassian.net/browse/FRESH-314 */ public Builder setAD_PInstance_ID(final PInstanceId AD_PInstance_ID) { this.AD_PInstance_ID = AD_PInstance_ID; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\ChangeLogRecord.java
1
请在Spring Boot框架中完成以下Java代码
JavaMailSenderImpl mailSender(MailProperties properties, ObjectProvider<SslBundles> sslBundles) { JavaMailSenderImpl sender = new JavaMailSenderImpl(); applyProperties(properties, sender, sslBundles.getIfAvailable()); return sender; } private void applyProperties(MailProperties properties, JavaMailSenderImpl sender, @Nullable SslBundles sslBundles) { sender.setHost(properties.getHost()); if (properties.getPort() != null) { sender.setPort(properties.getPort()); } sender.setUsername(properties.getUsername()); sender.setPassword(properties.getPassword()); sender.setProtocol(properties.getProtocol()); if (properties.getDefaultEncoding() != null) { sender.setDefaultEncoding(properties.getDefaultEncoding().name()); } Properties javaMailProperties = asProperties(properties.getProperties()); String protocol = properties.getProtocol(); protocol = (!StringUtils.hasLength(protocol)) ? "smtp" : protocol; Ssl ssl = properties.getSsl(); if (ssl.isEnabled()) { javaMailProperties.setProperty("mail." + protocol + ".ssl.enable", "true"); } if (ssl.getBundle() != null) { Assert.state(sslBundles != null, "'sslBundles' must not be null");
SslBundle sslBundle = sslBundles.getBundle(ssl.getBundle()); javaMailProperties.put("mail." + protocol + ".ssl.socketFactory", sslBundle.createSslContext().getSocketFactory()); } if (!javaMailProperties.isEmpty()) { sender.setJavaMailProperties(javaMailProperties); } } private Properties asProperties(Map<String, String> source) { Properties properties = new Properties(); properties.putAll(source); return properties; } }
repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailSenderPropertiesConfiguration.java
2
请完成以下Java代码
public void setMinValue (BigDecimal MinValue) { set_Value (COLUMNNAME_MinValue, MinValue); } /** Get Min Value. @return Min Value */ public BigDecimal getMinValue () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinValue); if (bd == null) return Env.ZERO; return bd; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListLine.java
1
请完成以下Java代码
public void migrateState() { eventSubscription.setActivity((ActivityImpl) targetScope); currentScope = targetScope; } @Override public void migrateDependentEntities() { } @Override public void addMigratingDependentInstance(MigratingInstance migratingInstance) { } @Override public ExecutionEntity resolveRepresentativeExecution() { return null; } @Override public void attachState(MigratingScopeInstance targetActivityInstance) { setParent(targetActivityInstance); ExecutionEntity representativeExecution = targetActivityInstance.resolveRepresentativeExecution(); eventSubscription.setExecution(representativeExecution); } @Override
public void setParent(MigratingScopeInstance parentInstance) { if (this.parentInstance != null) { this.parentInstance.removeChild(this); } this.parentInstance = parentInstance; if (parentInstance != null) { parentInstance.addChild(this); } } public void remove() { eventSubscription.delete(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCompensationEventSubscriptionInstance.java
1
请在Spring Boot框架中完成以下Java代码
public String remitUI(Model model, @RequestParam("id") String id) { RpSettRecord settRecord = rpSettQueryService.getDataById(id); model.addAttribute("settRecord", settRecord); return "sett/remit"; } /** * 函数功能说明 : 发起打款 * * @参数: @return * @return String * @throws */ @RequiresPermissions("sett:record:edit") @RequestMapping(value = "/remit", method = RequestMethod.POST) public String remit(HttpServletRequest request, Model model, DwzAjax dwz) { String settId = request.getParameter("settId"); String settStatus = request.getParameter("settStatus"); String remark = request.getParameter("remark"); rpSettHandleService.remit(settId, settStatus, remark); dwz.setStatusCode(DWZ.SUCCESS); dwz.setMessage(DWZ.SUCCESS_MSG); model.addAttribute("dwz", dwz); return DWZ.AJAX_DONE; } /** * 函数功能说明 :查看 * * @参数: @return * @return String * @throws
*/ @RequestMapping(value = "/view", method = RequestMethod.GET) public String view(Model model, @RequestParam("id") String id) { RpSettRecord settRecord = rpSettQueryService.getDataById(id); model.addAttribute("settRecord", settRecord); return "sett/view"; } /** * 函数功能说明 :根据支付产品获取支付方式 * * @参数: @return * @return String * @throws */ @RequestMapping(value = "/getSettAmount", method = RequestMethod.GET) @ResponseBody public RpAccount getSettAmount(@RequestParam("userNo") String userNo) { RpAccount rpAccount = rpAccountService.getDataByUserNo(userNo); return rpAccount; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\sett\SettController.java
2
请完成以下Java代码
public static <T> AdditionalRequiredFactorsBuilder<T> multiFactor() { return new AdditionalRequiredFactorsBuilder<>(); } /** * A builder that allows creating {@link DefaultAuthorizationManagerFactory} with * additional requirements for {@link RequiredFactor}s. * * @param <T> the type for the {@link DefaultAuthorizationManagerFactory} * @author Rob Winch */ public static final class AdditionalRequiredFactorsBuilder<T> { private final AllRequiredFactorsAuthorizationManager.Builder<T> factors = AllRequiredFactorsAuthorizationManager .builder(); /** * Add additional authorities that will be required. * @param additionalAuthorities the additional authorities. * @return the {@link AdditionalRequiredFactorsBuilder} to further customize. */ public AdditionalRequiredFactorsBuilder<T> requireFactors(String... additionalAuthorities) { requireFactors((factors) -> { for (String authority : additionalAuthorities) { factors.requireFactor((factor) -> factor.authority(authority)); } }); return this; } public AdditionalRequiredFactorsBuilder<T> requireFactors( Consumer<AllRequiredFactorsAuthorizationManager.Builder<T>> factors) { factors.accept(this.factors); return this; } public AdditionalRequiredFactorsBuilder<T> requireFactor(Consumer<RequiredFactor.Builder> factor) { this.factors.requireFactor(factor); return this; }
/** * Builds a {@link DefaultAuthorizationManagerFactory} that has the * {@link DefaultAuthorizationManagerFactory#setAdditionalAuthorization(AuthorizationManager)} * set. * @return the {@link DefaultAuthorizationManagerFactory}. */ public DefaultAuthorizationManagerFactory<T> build() { DefaultAuthorizationManagerFactory<T> result = new DefaultAuthorizationManagerFactory<>(); AllRequiredFactorsAuthorizationManager<T> additionalChecks = this.factors.build(); result.setAdditionalAuthorization(additionalChecks); return result; } private AdditionalRequiredFactorsBuilder() { } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationManagerFactories.java
1
请在Spring Boot框架中完成以下Java代码
default List<VariableInstanceEntity> findVariableInstancesByExecutionId(String executionId) { return createInternalVariableInstanceQuery().executionId(executionId).withoutTaskId().list(); } default List<VariableInstanceEntity> findVariableInstanceByScopeIdAndScopeType(String scopeId, String scopeType) { return createInternalVariableInstanceQuery().scopeId(scopeId).withoutSubScopeId().scopeType(scopeType).list(); } default List<VariableInstanceEntity> findVariableInstanceBySubScopeIdAndScopeType(String subScopeId, String scopeType) { return createInternalVariableInstanceQuery().subScopeId(subScopeId).scopeType(scopeType).list(); } /** * Create a variable instance with the given name and value for the given tenant. * * @param name the name of the variable to create * @return the {@link VariableInstanceEntity} to be used */ VariableInstanceEntity createVariableInstance(String name); void insertVariableInstance(VariableInstanceEntity variable);
/** * Inserts a variable instance with the given value. * @param variable the variable instance to insert * @param value the value to set * @param tenantId the tenant id of the variable instance */ void insertVariableInstanceWithValue(VariableInstanceEntity variable, Object value, String tenantId); void deleteVariableInstance(VariableInstanceEntity variable); void deleteVariablesByExecutionId(String executionId); void deleteVariablesByTaskId(String taskId); }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\VariableService.java
2
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "book_title") private String title; @Column(name = "book_isbn") private String isbn; @Column(name = "book_pages") private int pages; @OneToMany(cascade = CascadeType.ALL, mappedBy = "book", orphanRemoval = true) private List<Chapter> chapters = new ArrayList<>(); public void addChapter(Chapter chapter) { this.chapters.add(chapter); chapter.setBook(this); } public void removeChapter(Chapter chapter) { chapter.setBook(null); this.chapters.remove(chapter); } public void removeChapters() { Iterator<Chapter> iterator = this.chapters.iterator(); while (iterator.hasNext()) { Chapter chapter = iterator.next(); chapter.setBook(null); iterator.remove(); } } 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 getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public ImmutableSet<HuId> getVHUIds(final HuId huId) {return vhuIds.computeIfAbsent(huId, this::retrieveVHUIds);} private ImmutableSet<HuId> retrieveVHUIds(final HuId huId) { final I_M_HU hu = getHUById(huId); final List<I_M_HU> vhus = handlingUnitsBL.getVHUs(hu); addToCache(vhus); return extractHUIds(vhus); } private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) {return hus.stream().map(HUsLoadingCache::extractHUId).collect(ImmutableSet.toImmutableSet());} private static HuId extractHUId(final I_M_HU hu) {return HuId.ofRepoId(hu.getM_HU_ID());} public ImmutableAttributeSet getHUAttributes(final HuId huId) {
return huAttributesCache.computeIfAbsent(huId, this::retrieveHUAttributes); } private ImmutableAttributeSet retrieveHUAttributes(final HuId huId) { final I_M_HU hu = getHUById(huId); final IAttributeStorage attributes = attributesFactory.getAttributeStorage(hu); return ImmutableAttributeSet.createSubSet(attributes, a -> attributesToConsider.contains(AttributeCode.ofString(a.getValue()))); } public LocatorId getLocatorIdByHuId(final HuId huId) { final I_M_HU hu = getHUById(huId); return IHandlingUnitsBL.extractLocatorId(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\HUsLoadingCache.java
1
请完成以下Java代码
public class HistoricTaskInstanceReportQueryDto extends AbstractReportDto<HistoricTaskInstanceReport> { public static final String PROCESS_DEFINITION = "processDefinition"; public static final String TASK_NAME = "taskName"; protected Date completedBefore; protected Date completedAfter; protected String groupby; public HistoricTaskInstanceReportQueryDto() {} public HistoricTaskInstanceReportQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) { super(objectMapper, queryParameters); } public Date getCompletedBefore() { return completedBefore; } public Date getCompletedAfter() { return completedAfter; } public String getGroupBy() { return groupby; } @CamundaQueryParam(value = "completedAfter", converter = DateConverter.class) public void setCompletedAfter(Date completedAfter) { this.completedAfter = completedAfter; } @CamundaQueryParam(value = "completedBefore", converter = DateConverter.class) public void setCompletedBefore(Date completedBefore) { this.completedBefore = completedBefore; } @CamundaQueryParam("groupBy") public void setGroupBy(String groupby) { this.groupby = groupby; } protected void applyFilters(HistoricTaskInstanceReport reportQuery) { if (completedBefore != null) { reportQuery.completedBefore(completedBefore);
} if (completedAfter != null) { reportQuery.completedAfter(completedAfter); } if(REPORT_TYPE_DURATION.equals(reportType)) { if(periodUnit == null) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "periodUnit is null"); } } } protected HistoricTaskInstanceReport createNewReportQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricTaskInstanceReport(); } public List<HistoricTaskInstanceReportResult> executeCompletedReport(ProcessEngine engine) { HistoricTaskInstanceReport reportQuery = createNewReportQuery(engine); applyFilters(reportQuery); if(PROCESS_DEFINITION.equals(groupby)) { return reportQuery.countByProcessDefinitionKey(); } else if( TASK_NAME.equals(groupby) ){ return reportQuery.countByTaskName(); } else { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupby); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class BusinessRuleTriggerInterceptor extends AbstractModelInterceptor { @NonNull private static final Logger logger = LogManager.getLogger(BusinessRuleTriggerInterceptor.class); @NonNull private final BusinessRuleService ruleService; @NonNull private final RecordWarningRepository recordWarningRepository; private IModelValidationEngine engine; @NonNull private BusinessRulesCollection rules = BusinessRulesCollection.EMPTY; @NonNull private final HashSet<String> registeredTableNames = new HashSet<>(); private @NotNull BusinessRulesCollection getRules() {return rules;} private IModelValidationEngine getEngine() {return Check.assumeNotNull(this.engine, "engine is set");} @Override protected void onInit(final IModelValidationEngine engine, final I_AD_Client client) { this.engine = engine; ruleService.addRulesChangedListener(this::updateFromBusinessRulesRepository); Services.get(INotificationBL.class).addCtxProvider(new RecordWarningTextProvider(recordWarningRepository)); updateFromBusinessRulesRepository(); } private synchronized void updateFromBusinessRulesRepository() { final BusinessRulesCollection rulesPrev = this.rules; this.rules = ruleService.getRules(); if (Objects.equals(this.rules, rulesPrev)) { return; } updateRegisteredInterceptors(); } private synchronized void updateRegisteredInterceptors() { final IModelValidationEngine engine = getEngine(); final BusinessRulesCollection rules = getRules(); final HashSet<String> registeredTableNamesNoLongerNeeded = new HashSet<>(registeredTableNames); for (final AdTableId triggerTableId : rules.getTriggerTableIds()) { final String triggerTableName = TableIdsCache.instance.getTableName(triggerTableId); registeredTableNamesNoLongerNeeded.remove(triggerTableName); if (registeredTableNames.contains(triggerTableName)) {
// already registered continue; } engine.addModelChange(triggerTableName, this); registeredTableNames.add(triggerTableName); logger.info("Registered trigger for {}", triggerTableName); } // // Remove no longer needed interceptors for (final String triggerTableName : registeredTableNamesNoLongerNeeded) { engine.removeModelChange(triggerTableName, this); registeredTableNames.remove(triggerTableName); logger.info("Unregistered trigger for {}", triggerTableName); } } @Override public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType modelChangeType) throws Exception { final TriggerTiming timing = TriggerTiming.ofModelChangeType(modelChangeType).orElse(null); if (timing == null) { return; } ruleService.fireTriggersForSourceModel(model, timing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\interceptor\BusinessRuleTriggerInterceptor.java
2
请在Spring Boot框架中完成以下Java代码
public class RestartJobDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Bean public Job restartJob() { return jobBuilderFactory.get("restartJob") .start(step()) .build(); } private Step step() {
return stepBuilderFactory.get("step") .<String, String>chunk(2) .reader(listItemReader()) .writer(list -> list.forEach(System.out::println)) // .allowStartIfComplete(true) .startLimit(1) .build(); } private ListItemReader<String> listItemReader() { ArrayList<String> datas = new ArrayList<>(); IntStream.range(0, 5).forEach(i -> datas.add(String.valueOf(i))); return new ListItemReader<>(datas); } }
repos\SpringAll-master\72.spring-batch-exception\src\main\java\cc\mrbird\batch\job\RestartJobDemo.java
2
请完成以下Java代码
public static List<Long> getCurrentUserDataScope(){ UserDetails userDetails = getCurrentUser(); // 将 Java 对象转换为 JSONObject 对象 JSONObject jsonObject = (JSONObject) JSON.toJSON(userDetails); JSONArray jsonArray = jsonObject.getJSONArray("dataScopes"); return JSON.parseArray(jsonArray.toJSONString(), Long.class); } /** * 获取数据权限级别 * @return 级别 */ public static String getDataScopeType() { List<Long> dataScopes = getCurrentUserDataScope(); if(CollUtil.isEmpty(dataScopes)){ return ""; } return DataScopeEnum.ALL.getValue(); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId() { return getCurrentUserId(getToken()); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId(String token) { JWT jwt = JWTUtil.parseToken(token); return Long.valueOf(jwt.getPayload("userId").toString()); } /** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername() { return getCurrentUsername(getToken()); }
/** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername(String token) { JWT jwt = JWTUtil.parseToken(token); return jwt.getPayload("sub").toString(); } /** * 获取Token * @return / */ public static String getToken() { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder .getRequestAttributes())).getRequest(); String bearerToken = request.getHeader(header); if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) { // 去掉令牌前缀 return bearerToken.replace(tokenStartWith, ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SecurityUtils.java
1
请在Spring Boot框架中完成以下Java代码
public Flux<User> getUserByCondition(int size, int page, User user) { Query query = getQuery(user); Sort sort = new Sort(Sort.Direction.DESC, "age"); Pageable pageable = PageRequest.of(page, size, sort); return template.find(query.with(pageable), User.class); } /** * 返回 count,配合 getUserByCondition使用 */ public Mono<Long> getUserByConditionCount(User user) { Query query = getQuery(user); return template.count(query, User.class); }
private Query getQuery(User user) { Query query = new Query(); Criteria criteria = new Criteria(); if (!StringUtils.isEmpty(user.getName())) { criteria.and("name").is(user.getName()); } if (!StringUtils.isEmpty(user.getDescription())) { criteria.and("description").regex(user.getDescription()); } query.addCriteria(criteria); return query; } }
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public void fetchByMultipleIdsIn() { List<Book> books = bookRepository.fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books); } public void fetchByMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books); } public void fetchInBatchesByMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchInBatchesByMultipleIds(List.of(1L, 2L, 5L), 2); System.out.println(books); } @Transactional(readOnly = true) public void fetchBySessionCheckMultipleIds() { List<Book> books1 = bookMultipleIdsRepository .fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books1);
// loaded from Persistence Context List<Book> books2 = bookMultipleIdsRepository .fetchBySessionCheckMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books2); } public void fetchInBatchesBySessionCheckMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchInBatchesBySessionCheckMultipleIds(List.of(1L, 2L, 3L), 2); System.out.println(books); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLoadMultipleIds\src\main\java\com\bookstore\service\BookstoreService.java
2
请在Spring Boot框架中完成以下Java代码
public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "STUDENT_NAME", length = 50, nullable = false, unique = false) private String name; @Transient private Integer age; @Temporal(TemporalType.DATE) private Date birthDate; @Enumerated(EnumType.STRING) private Gender gender; 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 Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entity\Student.java
2
请在Spring Boot框架中完成以下Java代码
public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) {
this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities; } public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } @Override public String toString() { return "UserDTO{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
2
请完成以下Java代码
public @NonNull String getColumnSql(@NonNull String columnName) { final String columnSqlNew = "UPPER(" + columnName + ")"; return columnSqlNew; } @Override public String getValueSql(Object value, List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); } else { valueSql = "?"; params.add(value); }
return "UPPER(" + valueSql + ")"; } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return null; } final String str = (String)value; return str.toUpperCase(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\UpperCaseQueryFilterModifier.java
1
请在Spring Boot框架中完成以下Java代码
public String prefix() { return "management.datadog.metrics.export"; } @Override public String apiKey() { return obtain(DatadogProperties::getApiKey, DatadogConfig.super::apiKey); } @Override public @Nullable String applicationKey() { return get(DatadogProperties::getApplicationKey, DatadogConfig.super::applicationKey); } @Override
public @Nullable String hostTag() { return get(DatadogProperties::getHostTag, DatadogConfig.super::hostTag); } @Override public String uri() { return obtain(DatadogProperties::getUri, DatadogConfig.super::uri); } @Override public boolean descriptions() { return obtain(DatadogProperties::isDescriptions, DatadogConfig.super::descriptions); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\datadog\DatadogPropertiesConfigAdapter.java
2
请完成以下Java代码
public void installLicense() { try { Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class); CipherParam cipherParam = new DefaultCipherParam(storePass); KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class, publicKeysStorePath, publicAlias, storePass, null); LicenseParam licenseParam = new DefaultLicenseParam(subject, preferences, publicStoreParam, cipherParam); licenseManager = new CustomLicenseManager(licenseParam); licenseManager.uninstall(); LicenseContent licenseContent = licenseManager.install(new File(licensePath)); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); installSuccess = true; log.info("------------------------------- 证书安装成功 -------------------------------"); log.info(MessageFormat.format("证书校验通过,证书有效期:{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter()))); } catch (Exception e) { installSuccess = false; log.error("------------------------------- 证书安装失败 -------------------------------"); log.error(e.getMessage(), e); } } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: LicenseVerify.java </p> * <p>方法描述: 卸载证书,在 Bean 从容器移除的时候自动调用 </p> * <p>创建时间: 2020/10/10 15:58 </p> * * @return void * @author 方瑞冬 * @version 1.0 */ public void unInstallLicense() { if (installSuccess) { try { licenseManager.uninstall(); log.info("------------------------------- 证书卸载成功 -------------------------------"); } catch (Exception e) { log.error("------------------------------- 证书卸载失败 -------------------------------"); log.error(e.getMessage(), e); }
} } /** * <p>项目名称: true-license-demo </p> * <p>文件名称: LicenseVerify.java </p> * <p>方法描述: </p> * <p>创建时间: 2020/10/10 16:00 </p> * * @return boolean * @author 方瑞冬 * @version 1.0 */ public boolean verify() { try { LicenseContent licenseContent = licenseManager.verify(); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); log.info(MessageFormat.format("证书有效期:{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter()))); return true; } catch (Exception e) { log.error("证书校验失败" + e.getMessage(), e); return false; } } }
repos\springboot-demo-master\SoftwareLicense\src\main\java\com\et\license\license\LicenseVerify.java
1
请完成以下Java代码
public RefundConfig save(@NonNull final RefundConfig refundConfig) { final I_C_Flatrate_RefundConfig configRecord; if (refundConfig.getId() == null) { configRecord = newInstance(I_C_Flatrate_RefundConfig.class); } else { configRecord = load(refundConfig.getId(), I_C_Flatrate_RefundConfig.class); } switch (refundConfig.getRefundBase()) { case PERCENTAGE: configRecord.setRefundBase(X_C_Flatrate_RefundConfig.REFUNDBASE_Percentage); configRecord.setRefundPercent(refundConfig.getPercent().toBigDecimal()); configRecord.setRefundAmt(null); break; case AMOUNT_PER_UNIT: configRecord.setRefundBase(X_C_Flatrate_RefundConfig.REFUNDBASE_Amount); configRecord.setRefundAmt(refundConfig.getAmount().toBigDecimal()); configRecord.setC_Currency_ID(refundConfig.getAmount().getCurrencyId().getRepoId()); configRecord.setRefundPercent(null); break; default: Check.fail("Unexpected refundbase={}", refundConfig.getRefundBase()); break; } final InvoiceSchedule savedInvoiceSchedule = invoiceScheduleRepository.save(refundConfig.getInvoiceSchedule()); configRecord.setC_InvoiceSchedule_ID(savedInvoiceSchedule.getId().getRepoId()); configRecord.setC_Flatrate_Conditions_ID(refundConfig.getConditionsId().getRepoId()); configRecord.setMinQty(refundConfig.getMinQty()); configRecord.setM_Product_ID(ProductId.toRepoId(refundConfig.getProductId())); switch (refundConfig.getRefundInvoiceType()) { case CREDITMEMO: configRecord.setRefundInvoiceType(X_C_Flatrate_RefundConfig.REFUNDINVOICETYPE_Creditmemo); break; case INVOICE: configRecord.setRefundInvoiceType(X_C_Flatrate_RefundConfig.REFUNDINVOICETYPE_Invoice); break; default: Check.fail("Unexpected refundInvoiceType={}", refundConfig.getRefundInvoiceType()); break; } switch (refundConfig.getRefundMode()) { case APPLY_TO_ALL_QTIES: configRecord.setRefundMode(X_C_Flatrate_RefundConfig.REFUNDMODE_Accumulated); break;
case APPLY_TO_EXCEEDING_QTY: configRecord.setRefundMode(X_C_Flatrate_RefundConfig.REFUNDMODE_Tiered); break; default: Check.fail("Unexpected refundMode={}", refundConfig.getRefundMode()); break; } saveRecord(configRecord); return refundConfig .toBuilder() .id(RefundConfigId.ofRepoId(configRecord.getC_Flatrate_RefundConfig_ID())) .build(); } public List<RefundConfig> saveAll(@NonNull final List<RefundConfig> refundConfigs) { final ImmutableList.Builder<RefundConfig> result = ImmutableList.builder(); for (final RefundConfig refundConfig : refundConfigs) { result.add(save(refundConfig)); } return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundConfigRepository.java
1
请完成以下Java代码
public int getPA_MeasureCalc_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Ratio getPA_Ratio() throws RuntimeException { return (I_PA_Ratio)MTable.get(getCtx(), I_PA_Ratio.Table_Name) .getPO(getPA_Ratio_ID(), get_TrxName()); } /** Set Ratio. @param PA_Ratio_ID Performace Ratio */ public void setPA_Ratio_ID (int PA_Ratio_ID) { if (PA_Ratio_ID < 1) set_Value (COLUMNNAME_PA_Ratio_ID, null); else set_Value (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID)); }
/** Get Ratio. @return Performace Ratio */ public int getPA_Ratio_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Measure.java
1
请完成以下Java代码
public void setRevision(int revision) { this.revision = revision; } public void setByteArrayId(String id) { byteArrayId = id; } public String getByteArrayId() { return byteArrayId; } public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } public String getScopeActivityInstanceId() { return scopeActivityInstanceId; } public void setScopeActivityInstanceId(String scopeActivityInstanceId) { this.scopeActivityInstanceId = scopeActivityInstanceId; } public void setInitial(Boolean isInitial) { this.isInitial = isInitial; } public Boolean isInitial() { return isInitial; }
@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 + ", scopeActivityInstanceId=" + scopeActivityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", tenantId=" + tenantId + ", isInitial=" + isInitial + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricVariableUpdateEventEntity.java
1
请完成以下Java代码
public Instruction3Code getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link Instruction3Code } * */ public void setCd(Instruction3Code value) { this.cd = value; } /** * Gets the value of the instrInf property. * * @return * possible object is
* {@link String } * */ public String getInstrInf() { return instrInf; } /** * Sets the value of the instrInf property. * * @param value * allowed object is * {@link String } * */ public void setInstrInf(String value) { this.instrInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\InstructionForCreditorAgent1.java
1
请完成以下Java代码
public static void conditionalSleepWithPoll(Supplier<Boolean> shouldSleepCondition, long interval, Consumer<?, ?> consumer) throws InterruptedException { boolean isFirst = true; long timeout = System.currentTimeMillis() + interval; long sleepInterval = interval > SMALL_INTERVAL_THRESHOLD ? DEFAULT_SLEEP_INTERVAL : SMALL_SLEEP_INTERVAL; do { Thread.sleep(sleepInterval); if (!shouldSleepCondition.get()) { break; } if (isFirst) { isFirst = false; } else { // To prevent consumer group rebalancing during retry backoff. consumer.poll(Duration.ZERO); } } while (System.currentTimeMillis() < timeout); } /**
* Create a new {@link OffsetAndMetadata} using the given container and offset. * @param container a container. * @param offset an offset. * @return an offset and metadata. * @since 2.8.6 */ public static OffsetAndMetadata createOffsetAndMetadata(@Nullable MessageListenerContainer container, long offset) { Assert.state(container != null, "Container cannot be null"); final OffsetAndMetadataProvider metadataProvider = container.getContainerProperties() .getOffsetAndMetadataProvider(); if (metadataProvider != null) { return metadataProvider.provide(new DefaultListenerMetadata(container), offset); } return new OffsetAndMetadata(offset); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ListenerUtils.java
1
请在Spring Boot框架中完成以下Java代码
private void saveNewPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitInsert = new ArrayList<>(); for (Integer newPerm : newPerms) { if (!oldPerms.contains(newPerm)) { waitInsert.add(newPerm); } } if (waitInsert.size() > 0) { userDao.insertRolePermission(roleId, waitInsert); } } /** * 删除角色 旧的 不再拥有的权限 */ private void removeOldPermission(String roleId, Collection<Integer> newPerms, Collection<Integer> oldPerms) { List<Integer> waitRemove = new ArrayList<>(); for (Integer oldPerm : oldPerms) { if (!newPerms.contains(oldPerm)) { waitRemove.add(oldPerm); } } if (waitRemove.size() > 0) { userDao.removeOldPermission(roleId, waitRemove); } }
/** * 删除角色 */ @Transactional(rollbackFor = Exception.class) public JSONObject deleteRole(JSONObject jsonObject) { String roleId = jsonObject.getString("roleId"); int userCount = userDao.countRoleUser(roleId); if (userCount > 0) { return CommonUtil.errorJson(ErrorEnum.E_10008); } userDao.removeRole(roleId); userDao.removeRoleAllPermission(roleId); return CommonUtil.successJson(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\UserService.java
2
请完成以下Java代码
public class BlockingRegistrationClient implements RegistrationClient { private static final ParameterizedTypeReference<Map<String, Object>> RESPONSE_TYPE = new ParameterizedTypeReference<>() { }; private final RestTemplate restTemplate; public BlockingRegistrationClient(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Override public String register(String adminUrl, Application application) { ResponseEntity<Map<String, Object>> response = this.restTemplate.exchange(adminUrl, HttpMethod.POST, new HttpEntity<>(application, this.createRequestHeaders()), RESPONSE_TYPE);
return response.getBody().get("id").toString(); } @Override public void deregister(String adminUrl, String id) { this.restTemplate.delete(adminUrl + '/' + id); } protected HttpHeaders createRequestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); return HttpHeaders.readOnlyHttpHeaders(headers); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\BlockingRegistrationClient.java
1
请完成以下Java代码
public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ObscureType AD_Reference_ID=291 * Reference name: AD_Field ObscureType */ public static final int OBSCURETYPE_AD_Reference_ID=291; /** Obscure Digits but last 4 = 904 */ public static final String OBSCURETYPE_ObscureDigitsButLast4 = "904"; /** Obscure Digits but first/last 4 = 944 */ public static final String OBSCURETYPE_ObscureDigitsButFirstLast4 = "944"; /** Obscure AlphaNumeric but first/last 4 = A44 */ public static final String OBSCURETYPE_ObscureAlphaNumericButFirstLast4 = "A44"; /** Obscure AlphaNumeric but last 4 = A04 */ public static final String OBSCURETYPE_ObscureAlphaNumericButLast4 = "A04"; @Override public void setObscureType (final @Nullable java.lang.String ObscureType) { set_Value (COLUMNNAME_ObscureType, ObscureType); } @Override public java.lang.String getObscureType() { return get_ValueAsString(COLUMNNAME_ObscureType); } @Override public void setSelectionColumnSeqNo (final @Nullable BigDecimal SelectionColumnSeqNo) { set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo); } @Override public BigDecimal getSelectionColumnSeqNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); }
@Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override public int getSpanX() { return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请在Spring Boot框架中完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @ApiModelProperty(example = "Smith") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @ApiModelProperty(example = "Fred Smith") public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @JsonInclude(JsonInclude.Include.NON_NULL) public String getPassword() { return passWord; } public void setPassword(String passWord) { this.passWord = passWord; } @JsonInclude(JsonInclude.Include.NON_NULL) @ApiModelProperty(example = "companyTenantId")
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "http://localhost:8182/identity/users/testuser/picture") public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\identity\UserResponse.java
2
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSumDeliveredInStockingUOM (final @Nullable BigDecimal SumDeliveredInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM); } @Override public BigDecimal getSumDeliveredInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSumOrderedInStockingUOM (final @Nullable BigDecimal SumOrderedInStockingUOM) { set_ValueNoCheck (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM);
} @Override public BigDecimal getSumOrderedInStockingUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUserFlag (final @Nullable java.lang.String UserFlag) { set_ValueNoCheck (COLUMNNAME_UserFlag, UserFlag); } @Override public java.lang.String getUserFlag() { return get_ValueAsString(COLUMNNAME_UserFlag); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_M_InOut_Desadv_V.java
1
请完成以下Java代码
public String getScopeType() { return null; } @Override public void setScopeId(String scopeId) { } @Override public void setSubScopeId(String subScopeId) { } @Override public void setScopeType(String scopeType) { } @Override public String getScopeDefinitionId() {
return null; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { } @Override public String getMetaInfo() { return null; } @Override public void setMetaInfo(String metaInfo) { } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java
1
请完成以下Java代码
public class ExcelUtility { private static final String ENDLINE = System.getProperty("line.separator"); public static String readExcel(String filePath) throws IOException { File file = new File(filePath); FileInputStream inputStream = null; StringBuilder toReturn = new StringBuilder(); try { inputStream = new FileInputStream(file); Workbook baeuldungWorkBook = new XSSFWorkbook(inputStream); for (Sheet sheet : baeuldungWorkBook) { toReturn.append("--------------------------------------------------------------------") .append(ENDLINE); toReturn.append("Worksheet :") .append(sheet.getSheetName()) .append(ENDLINE); toReturn.append("--------------------------------------------------------------------") .append(ENDLINE); int firstRow = sheet.getFirstRowNum(); int lastRow = sheet.getLastRowNum(); for (int index = firstRow + 1; index <= lastRow; index++) { Row row = sheet.getRow(index); toReturn.append("|| "); for (int cellIndex = row.getFirstCellNum(); cellIndex < row.getLastCellNum(); cellIndex++) { Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); printCellValue(cell, toReturn); } toReturn.append(" ||") .append(ENDLINE); } } inputStream.close(); baeuldungWorkBook.close(); } catch (IOException e) { throw e; } return toReturn.toString(); } public static void printCellValue(Cell cell, StringBuilder toReturn) { CellType cellType = cell.getCellType()
.equals(CellType.FORMULA) ? cell.getCachedFormulaResultType() : cell.getCellType(); if (cellType.equals(CellType.STRING)) { toReturn.append(cell.getStringCellValue()) .append(" | "); } if (cellType.equals(CellType.NUMERIC)) { if (DateUtil.isCellDateFormatted(cell)) { toReturn.append(cell.getDateCellValue()) .append(" | "); } else { toReturn.append(cell.getNumericCellValue()) .append(" | "); } } if (cellType.equals(CellType.BOOLEAN)) { toReturn.append(cell.getBooleanCellValue()) .append(" | "); } } }
repos\tutorials-master\apache-poi\src\main\java\com\baeldung\poi\excel\ExcelUtility.java
1
请完成以下Java代码
public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { if (!StringUtils.hasText(config.regexp) && config.predicate == null) { // check existence of header return exchange.getRequest().getQueryParams().containsKey(config.param); } List<String> values = exchange.getRequest().getQueryParams().get(config.param); if (values == null) { return false; } Predicate<String> predicate = config.predicate; if (StringUtils.hasText(config.regexp)) { predicate = value -> value.matches(config.regexp); } for (String value : values) { if (value != null && predicate != null && predicate.test(value)) { return true; } } return false; } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Query: param=%s regexp=%s", config.getParam(), config.getRegexp()); } }; } public static class Config { @NotEmpty private @Nullable String param; private @Nullable String regexp; private @Nullable Predicate<String> predicate;
public @Nullable String getParam() { return this.param; } public Config setParam(String param) { this.param = param; return this; } public @Nullable String getRegexp() { return this.regexp; } public Config setRegexp(@Nullable String regexp) { this.regexp = regexp; return this; } public @Nullable Predicate<String> getPredicate() { return this.predicate; } public Config setPredicate(Predicate<String> predicate) { this.predicate = predicate; return this; } /** * Enforces the validation done on predicate configuration: {@link #regexp} and * {@link #predicate} can't be both set at runtime. * @return <code>false</code> if {@link #regexp} and {@link #predicate} are both * set in this predicate factory configuration */ @AssertTrue public boolean isValid() { return !(StringUtils.hasText(this.regexp) && this.predicate != null); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\QueryRoutePredicateFactory.java
1
请完成以下Spring Boot application配置
spring.ai.ollama.init.pull-model-strategy=when_missing spring.ai.ollama.init.chat.include=true spring.ai.ollama.embedding.options.model=nomic-embed-text spring.ai.vectorstore.pgvector.initialize-schema=true spring.ai.vectorstore.pgvector.dimensions=768 spring.ai.vectorstore.pgvector.index-type=hnsw spring.docker.compose.file=docker-compose.yml spring.docker.compose.enabled=true spring.datasource.url=jdbc:postgresql://localhost:5434/vectordb sprin
g.datasource.username=postgres spring.datasource.password=postgres spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-semantic-search.properties
2
请完成以下Java代码
public abstract class DiagramElementImpl extends BpmnModelElementInstanceImpl implements DiagramElement { protected static Attribute<String> idAttribute; protected static ChildElement<Extension> extensionChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DiagramElement.class, DI_ELEMENT_DIAGRAM_ELEMENT) .namespaceUri(DI_NS) .abstractType(); idAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_ID) .idAttribute() .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); extensionChild = sequenceBuilder.element(Extension.class) .build(); typeBuilder.build(); }
public DiagramElementImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } public Extension getExtension() { return extensionChild.getChild(this); } public void setExtension(Extension extension) { extensionChild.setChild(this, extension); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\DiagramElementImpl.java
1
请完成以下Java代码
public java.lang.String getResult () { return (java.lang.String)get_Value(COLUMNNAME_Result); } @Override public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class); } @Override public void setSalesRep(org.compiere.model.I_AD_User SalesRep) { set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep); } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Startdatum. @param StartTime Startdatum */ @Override public void setStartTime (java.sql.Timestamp StartTime) { set_Value (COLUMNNAME_StartTime, StartTime); } /** Get Startdatum. @return Startdatum */ @Override public java.sql.Timestamp getStartTime () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartTime); } /** Set Summary. @param Summary Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */
@Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); } /** * TaskStatus AD_Reference_ID=366 * Reference name: R_Request TaskStatus */ public static final int TASKSTATUS_AD_Reference_ID=366; /** 0% Not Started = 0 */ public static final String TASKSTATUS_0NotStarted = "0"; /** 100% Complete = D */ public static final String TASKSTATUS_100Complete = "D"; /** 20% Started = 2 */ public static final String TASKSTATUS_20Started = "2"; /** 80% Nearly Done = 8 */ public static final String TASKSTATUS_80NearlyDone = "8"; /** 40% Busy = 4 */ public static final String TASKSTATUS_40Busy = "4"; /** 60% Good Progress = 6 */ public static final String TASKSTATUS_60GoodProgress = "6"; /** 90% Finishing = 9 */ public static final String TASKSTATUS_90Finishing = "9"; /** 95% Almost Done = A */ public static final String TASKSTATUS_95AlmostDone = "A"; /** 99% Cleaning up = C */ public static final String TASKSTATUS_99CleaningUp = "C"; /** Set Task Status. @param TaskStatus Status of the Task */ @Override public void setTaskStatus (java.lang.String TaskStatus) { set_Value (COLUMNNAME_TaskStatus, TaskStatus); } /** Get Task Status. @return Status of the Task */ @Override public java.lang.String getTaskStatus () { return (java.lang.String)get_Value(COLUMNNAME_TaskStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Request.java
1
请完成以下Java代码
public PointOfInteraction1 getPOI() { return poi; } /** * Sets the value of the poi property. * * @param value * allowed object is * {@link PointOfInteraction1 } * */ public void setPOI(PointOfInteraction1 value) { this.poi = value; } /** * Gets the value of the tx property. * * @return * possible object is * {@link CardTransaction2Choice } * */ public CardTransaction2Choice getTx() { return tx; } /** * Sets the value of the tx property. * * @param value * allowed object is * {@link CardTransaction2Choice } * */
public void setTx(CardTransaction2Choice value) { this.tx = value; } /** * Gets the value of the prePdAcct property. * * @return * possible object is * {@link CashAccount24 } * */ public CashAccount24 getPrePdAcct() { return prePdAcct; } /** * Sets the value of the prePdAcct property. * * @param value * allowed object is * {@link CashAccount24 } * */ public void setPrePdAcct(CashAccount24 value) { this.prePdAcct = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\CardTransaction2.java
1
请完成以下Java代码
public boolean isOpenItem() { return get_ValueAsBoolean(COLUMNNAME_IsOpenItem); } @Override public void setIsSummary (final boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, IsSummary); } @Override public boolean isSummary() { return get_ValueAsBoolean(COLUMNNAME_IsSummary); } @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 org.compiere.model.I_C_ElementValue getParent() { return get_ValueAsPO(COLUMNNAME_Parent_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setParent(final org.compiere.model.I_C_ElementValue Parent) { set_ValueFromPO(COLUMNNAME_Parent_ID, org.compiere.model.I_C_ElementValue.class, Parent); } @Override public void setParent_ID (final int Parent_ID) { if (Parent_ID < 1) set_ValueNoCheck (COLUMNNAME_Parent_ID, null); else set_ValueNoCheck (COLUMNNAME_Parent_ID, Parent_ID); } @Override public int getParent_ID() { return get_ValueAsInt(COLUMNNAME_Parent_ID); } @Override public void setPostActual (final boolean PostActual) { set_Value (COLUMNNAME_PostActual, PostActual); } @Override public boolean isPostActual() { return get_ValueAsBoolean(COLUMNNAME_PostActual); } @Override public void setPostBudget (final boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, PostBudget); } @Override public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical);
} @Override public void setSeqNo (final int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @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\compiere\model\X_C_ElementValue.java
1
请完成以下Java代码
public static AttachmentEntryCreateRequest fromByteArray( @NonNull final String fileName, @NonNull final byte[] data) { final AttachmentEntryCreateRequest request = builderFromByteArray(fileName, data).build(); return request; } public static AttachmentEntryCreateRequest.AttachmentEntryCreateRequestBuilder builderFromByteArray( @NonNull final String fileName, final byte[] data) { return AttachmentEntryCreateRequest.builder() .type(AttachmentEntryType.Data) .filename(fileName) .contentType(MimeType.getMimeType(fileName)) .data(data); } public static AttachmentEntryCreateRequest fromDataSource(final DataSource dataSource) { final String filename = dataSource.getName(); final String contentType = dataSource.getContentType(); final byte[] data; try { data = Util.readBytes(dataSource.getInputStream()); } catch (final IOException e) { throw new AdempiereException("Failed reading data from " + dataSource); } return builder() .type(AttachmentEntryType.Data) .filename(filename) .contentType(contentType) .data(data) .build(); } public static Collection<AttachmentEntryCreateRequest> fromResources(@NonNull final Collection<Resource> resources) { return resources .stream() .map(AttachmentEntryCreateRequest::fromResource) .collect(ImmutableList.toImmutableList()); } public static AttachmentEntryCreateRequest fromResource(@NonNull final Resource resource) { final String filename = resource.getFilename(); final String contentType = MimeType.getMimeType(filename); final byte[] data; try { data = Util.readBytes(resource.getInputStream()); } catch (final IOException e) { throw new AdempiereException("Failed reading data from " + resource); } return builder() .type(AttachmentEntryType.Data) .filename(filename)
.contentType(contentType) .data(data) .build(); } public static Collection<AttachmentEntryCreateRequest> fromFiles(@NonNull final Collection<File> files) { return files .stream() .map(AttachmentEntryCreateRequest::fromFile) .collect(ImmutableList.toImmutableList()); } public static AttachmentEntryCreateRequest fromFile(@NonNull final File file) { final String filename = file.getName(); final String contentType = MimeType.getMimeType(filename); final byte[] data = Util.readBytes(file); return builder() .type(AttachmentEntryType.Data) .filename(filename) .contentType(contentType) .data(data) .build(); } @NonNull AttachmentEntryType type; String filename; String contentType; byte[] data; URI url; AttachmentTags tags; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryCreateRequest.java
1
请完成以下Java代码
public static boolean isEnglishLetter(char input) { return (input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z'); } public static boolean isArabicNumber(char input) { return input >= '0' && input <= '9'; } public static boolean isCJKCharacter(char input) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(input); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A //全角数字字符和日韩字符 || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS //韩文字符集 || ub == Character.UnicodeBlock.HANGUL_SYLLABLES || ub == Character.UnicodeBlock.HANGUL_JAMO || ub == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO //日文字符集 || ub == Character.UnicodeBlock.HIRAGANA //平假名 || ub == Character.UnicodeBlock.KATAKANA //片假名 || ub == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS ) { return true; } else { return false; } //其他的CJK标点符号,可以不做处理 //|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION //|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION }
/** * 进行字符规格化(全角转半角,大写转小写处理) * * @param input * @return char */ public static char regularize(char input) { if (input == 12288) { input = (char) 32; } else if (input > 65280 && input < 65375) { input = (char) (input - 65248); } else if (input >= 'A' && input <= 'Z') { input += 32; } return input; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\CharacterHelper.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_K_Source[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description URL. @param DescriptionURL URL for the description */ public void setDescriptionURL (String DescriptionURL) { set_Value (COLUMNNAME_DescriptionURL, DescriptionURL); } /** Get Description URL. @return URL for the description */ public String getDescriptionURL () { return (String)get_Value(COLUMNNAME_DescriptionURL); } /** Set Knowledge Source. @param K_Source_ID Source of a Knowledge Entry */ public void setK_Source_ID (int K_Source_ID) { if (K_Source_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Source_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID)); } /** Get Knowledge Source. @return Source of a Knowledge Entry */ public int getK_Source_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Source.java
1
请完成以下Java代码
public void setCurrentWindow(@NonNull final AdWindowId windowId) { setCurrentWindow(windowId, null); } public void setCurrentWindow(@NonNull final DocumentEntityDescriptor entityDescriptor) { setCurrentWindow(entityDescriptor.getWindowId().toAdWindowId(), entityDescriptor.getCaption().translate(adLanguage)); } public void setCurrentWindow(@NonNull final AdWindowId windowId, @Nullable final String windowName) { this.currentWindowId = windowId; this._currentWindowName = windowName; } public void clearCurrentWindow() { this.currentWindowId = null; this._currentWindowName = null; } @Nullable public String getCurrentWindowName() { if (this._currentWindowName == null && this.currentWindowId != null)
{ this._currentWindowName = adWindowDAO.retrieveWindowName(currentWindowId).translate(adLanguage); } return this._currentWindowName; } public void collectError(@NonNull final String errorMessage) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .errorMessage(errorMessage) .build()); } public void collectError(@NonNull final Throwable exception) { errors.add(JsonWindowsHealthCheckResponse.Entry.builder() .windowId(WindowId.of(currentWindowId)) .windowName(getCurrentWindowName()) .error(JsonErrors.ofThrowable(exception, adLanguage)) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ErrorsCollector.java
1
请完成以下Java代码
public String getCaseDefinitionId() { return caseDefinitionId; } @Override public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @Override public String getCaseInstanceId() { return caseInstanceId; } @Override public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } @Override public String getPlanItemInstanceId() { return planItemInstanceId; } @Override public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } @Override public String getOnPartId() { return onPartId;
} @Override public void setOnPartId(String onPartId) { this.onPartId = onPartId; } @Override public String getIfPartId() { return ifPartId; } @Override public void setIfPartId(String ifPartId) { this.ifPartId = ifPartId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\SentryPartInstanceEntityImpl.java
1
请完成以下Java代码
public ProcessEngineException exceptionWhileResolvingDuedate(String duedate, Exception e) { return new ProcessEngineException(exceptionMessage( "027", "Exception while resolving duedate '{}': {}", duedate, e.getMessage()), e); } public Exception cannotParseDuration(String expressions) { return new ProcessEngineException(exceptionMessage( "028", "Cannot parse duration '{}'.", expressions)); } public void logParsingRetryIntervals(String intervals, Exception e) { logWarn( "029", "Exception while parsing retry intervals '{}'", intervals, e.getMessage(), e); } public void logJsonException(Exception e) { logDebug( "030", "Exception while parsing JSON: {}", e.getMessage(), e); } public void logAccessExternalSchemaNotSupported(Exception e) { logDebug( "031", "Could not restrict external schema access. " + "This indicates that this is not supported by your JAXP implementation: {}", e.getMessage()); } public void logMissingPropertiesFile(String file) { logWarn("032", "Could not find the '{}' file on the classpath. " + "If you have removed it, please restore it.", file); } public ProcessEngineException exceptionDuringFormParsing(String cause, String resourceName) { return new ProcessEngineException(
exceptionMessage("033", "Could not parse Camunda Form resource {}. Cause: {}", resourceName, cause)); } public void debugCouldNotResolveCallableElement( String callingProcessDefinitionId, String activityId, Throwable cause) { logDebug("046", "Could not resolve a callable element for activity {} in process {}. Reason: {}", activityId, callingProcessDefinitionId, cause.getMessage()); } public ProcessEngineException exceptionWhileSettingXxeProcessing(Throwable cause) { return new ProcessEngineException(exceptionMessage( "047", "Exception while configuring XXE processing: {}", cause.getMessage()), cause); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EngineUtilLogger.java
1
请完成以下Java代码
public T getData() { return data; } public void setData(T data) { this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Status getStatus() { return status; }
public void setStatus(Status status) { this.status = status; } public static enum Status { SUCCESS("OK"), ERROR("ERROR"); private String code; private Status(String code) { this.code = code; } public String code() { return this.code; } } }
repos\spring-boot-student-master\spring-boot-student-hystrix\src\main\java\com\xiaolyuh\entity\Result.java
1
请完成以下Java代码
protected void parseChildElements( XMLStreamReader xtr, BaseElement parentElement, BpmnModel model, BaseChildElementParser parser ) throws Exception { boolean readyWithChildElements = false; while (!readyWithChildElements && xtr.hasNext()) { xtr.next(); if (xtr.isStartElement()) { if (parser.getElementName().equals(xtr.getLocalName())) { parser.parseChildElement(xtr, parentElement, model); } } else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) { readyWithChildElements = true; } } } public boolean accepts(BaseElement element) { return element != null; } protected List<ExtensionAttribute> parseExtensionAttributes( XMLStreamReader xtr,
BaseElement parentElement, BpmnModel model ) { List<ExtensionAttribute> attributes = new LinkedList<>(); for (int i = 0; i < xtr.getAttributeCount(); i++) { if (ACTIVITI_EXTENSIONS_NAMESPACE.equals(xtr.getAttributeNamespace(i))) { ExtensionAttribute attr = new ExtensionAttribute( ACTIVITI_EXTENSIONS_NAMESPACE, xtr.getAttributeLocalName(i) ); attr.setValue(xtr.getAttributeValue(i)); attributes.add(attr); } } return unmodifiableList(attributes); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\BaseChildElementParser.java
1
请完成以下Java代码
public class ProducerMain { private static Producer<String, String> createProducer() { // 设置 Producer 的属性 Properties properties = new Properties(); properties.put("bootstrap.servers", "127.0.0.1:9092"); // 设置 Broker 的地址 properties.put("acks", "1"); // 0-不应答。1-leader 应答。all-所有 leader 和 follower 应答。 properties.put("retries", 3); // 发送失败时,重试发送的次数 // properties.put("batch.size", 16384); // properties.put("linger.ms", 1); // properties.put("client.id", "DemoProducer"); // properties.put("buffer.memory", 33554432); properties.put("key.serializer", StringSerializer.class.getName()); // 消息的 key 的序列化方式 properties.put("value.serializer", StringSerializer.class.getName()); // 消息的 value 的序列化方式 // 创建 KafkaProducer 对象 // 因为我们消息的 key 和 value 都使用 String 类型,所以创建的 Producer 是 <String, String> 的泛型。
return new KafkaProducer<>(properties); } public static void main(String[] args) throws ExecutionException, InterruptedException { // 创建 KafkaProducer 对象 Producer<String, String> producer = createProducer(); // 创建消息。传入的三个参数,分别是 Topic ,消息的 key ,消息的 message 。 ProducerRecord<String, String> message = new ProducerRecord<>("TestTopic", "key", "yudaoyuanma"); // 同步发送消息 Future<RecordMetadata> sendResultFuture = producer.send(message); RecordMetadata result = sendResultFuture.get(); System.out.println("message sent to " + result.topic() + ", partition " + result.partition() + ", offset " + result.offset()); } }
repos\SpringBoot-Labs-master\lab-03-kafka\lab-03-kafka-native\src\main\java\cn\iocoder\springboot\lab03\kafkademo\ProducerMain.java
1
请完成以下Java代码
public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final IView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PurchaseView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = newViewId(); final List<PurchaseDemand> demands = getDemands(request); final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList = purchaseDemandWithCandidatesService.getOrCreatePurchaseCandidatesGroups(demands); final PurchaseRowsSupplier rowsSupplier = createRowsSupplier(viewId, purchaseDemandWithCandidatesList); final PurchaseView view = PurchaseView.builder() .viewId(viewId) .rowsSupplier(rowsSupplier) .additionalRelatedProcessDescriptors(getAdditionalProcessDescriptors()) .build(); return view; } protected List<RelatedProcessDescriptor> getAdditionalProcessDescriptors() { return ImmutableList.of(); }
private final PurchaseRowsSupplier createRowsSupplier( final ViewId viewId, final List<PurchaseDemandWithCandidates> purchaseDemandWithCandidatesList) { final PurchaseRowsSupplier rowsSupplier = PurchaseRowsLoader.builder() .purchaseDemandWithCandidatesList(purchaseDemandWithCandidatesList) .viewSupplier(() -> getByIdOrNull(viewId)) // needed for async stuff .purchaseRowFactory(purchaseRowFactory) .availabilityCheckService(availabilityCheckService) .build() .createPurchaseRowsSupplier(); return rowsSupplier; } protected final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final AdProcessId processId = adProcessRepo.retrieveProcessIdByClassIfUnique(processClass); Preconditions.checkArgument(processId != null, "No AD_Process_ID found for %s", processClass); return RelatedProcessDescriptor.builder() .processId(processId) .displayPlace(DisplayPlace.ViewQuickActions) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseViewFactoryTemplate.java
1
请在Spring Boot框架中完成以下Java代码
private void doPost(HttpServletResponse response, Saml2LogoutRequest logoutRequest) throws IOException { String location = logoutRequest.getLocation(); String saml = logoutRequest.getSamlRequest(); String relayState = logoutRequest.getRelayState(); String html = createSamlPostRequestFormData(location, saml, relayState); response.setContentType(MediaType.TEXT_HTML_VALUE); response.getWriter().write(html); } private String createSamlPostRequestFormData(String location, String saml, String relayState) { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(location); html.append("\" method=\"post\">\n"); html.append(" <div>\n");
html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\""); html.append(HtmlUtils.htmlEscape(saml)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); } html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\Saml2RelyingPartyInitiatedLogoutSuccessHandler.java
2
请在Spring Boot框架中完成以下Java代码
public IncludeAttribute getIncludeBindingErrors() { return this.includeBindingErrors; } public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors) { this.includeBindingErrors = includeBindingErrors; } public IncludeAttribute getIncludePath() { return this.includePath; } public void setIncludePath(IncludeAttribute includePath) { this.includePath = includePath; } public Whitelabel getWhitelabel() { return this.whitelabel; } /** * Include error attributes options. */ public enum IncludeAttribute { /** * Never add error attribute. */ NEVER, /** * Always add error attribute.
*/ ALWAYS, /** * Add error attribute when the appropriate request parameter is not "false". */ ON_PARAM } public static class Whitelabel { /** * Whether to enable the default error page displayed in browsers in case of a * server error. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET) public List<User> list(HttpServletRequest request) { return userService.getByMap(null); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User detail(@PathVariable Integer id) { return userService.getById(id); }
@RequestMapping(method = RequestMethod.POST) public User create(@RequestBody User user) { return userService.create(user); } @RequestMapping(method = RequestMethod.PUT) public User update(@RequestBody User user) { return userService.update(user); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public int delete(@PathVariable Integer id) { return userService.delete(id); } }
repos\springBoot-master\springboot-shiro\src\main\java\com\us\controller\UserController.java
2
请完成以下Java代码
public void assertCanCreateOrUpdateRecord(final OrgId orgId, final Class<?> modelClass) { assertPermission(PermissionRequest.builder() .orgId(orgId) .adTableId(getTableId(modelClass)) .build()); } public boolean canRunProcess(@NonNull final AdProcessId processId) { final PermissionRequest permissionRequest = PermissionRequest.builder() .orgId(OrgId.ANY) .processId(processId.getRepoId()) .build(); if (permissionsGranted.contains(permissionRequest)) { return true; } final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey); final boolean canAccessProcess = userPermissions.checkProcessAccessRW(processId.getRepoId()); if (canAccessProcess) { permissionsGranted.add(permissionRequest); } return canAccessProcess; } private void assertPermission(@NonNull final PermissionRequest request) { if (permissionsGranted.contains(request)) { return; } final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey); final BooleanWithReason allowed; if (request.getRecordId() >= 0) { allowed = userPermissions.checkCanUpdate( userPermissions.getClientId(), request.getOrgId(), request.getAdTableId(), request.getRecordId()); } else { allowed = userPermissions.checkCanCreateNewRecord(
userPermissions.getClientId(), request.getOrgId(), AdTableId.ofRepoId(request.getAdTableId())); } if (allowed.isFalse()) { throw new PermissionNotGrantedException(allowed.getReason()); } else { permissionsGranted.add(request); } } @lombok.Value @lombok.Builder private static class PermissionRequest { @lombok.NonNull OrgId orgId; @lombok.Builder.Default int adTableId = -1; @lombok.Builder.Default int recordId = -1; @lombok.Builder.Default int processId = -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions2\PermissionService.java
1
请完成以下Java代码
public void keyReleased(KeyEvent e) { // ESC if (e.getKeyCode() == KeyEvent.VK_ESCAPE && !getText().equals(m_oldText)) { log.debug( "VMemo.keyReleased - ESC"); setText(m_oldText); return; } // Indicate Change if (m_firstChange && !m_oldText.equals(getText())) { log.debug( "VMemo.keyReleased - firstChange"); m_firstChange = false; try { String text = getText(); // fireVetoableChange (m_columnName, text, null); // No data committed - done when focus lost !!! // metas: Korrektur null fuehrt dazu, dass eine aenderung nicht erkannt wird. fireVetoableChange(m_columnName, text, getText()); } catch (PropertyVetoException pve) {} } // firstChange } // keyReleased /** * Focus Gained - Save for Escape * @param e */ @Override public void focusGained (FocusEvent e) { log.info(e.paramString()); if (e.getSource() instanceof VMemo) requestFocus(); else m_oldText = getText(); } // focusGained /** * Data Binding to MTable (via GridController) * @param e */ @Override public void focusLost (FocusEvent e) { //log.info( "VMemo.focusLost " + e.getSource(), e.paramString()); // something changed? return; } // focusLost /*************************************************************************/ // Field for Value Preference private GridField m_mField = null; /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override
public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } private class CInputVerifier extends InputVerifier { @Override public boolean verify(JComponent input) { //NOTE: We return true no matter what since the InputVerifier is only introduced to fireVetoableChange in due time if (getText() == null && m_oldText == null) return true; else if (getText().equals(m_oldText)) return true; // try { String text = getText(); fireVetoableChange(m_columnName, null, text); m_oldText = text; return true; } catch (PropertyVetoException pve) {} return true; } // verify } // CInputVerifier // metas @Override public boolean isAutoCommit() { return true; } } // VMemo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VMemo.java
1
请完成以下Java代码
public class HalIdentityLinkResolver extends HalCachingLinkResolver { protected Class<?> getHalResourceClass() { return HalIdentityLink.class; } @Override public List<HalResource<?>> resolveLinks(String[] linkedIds, ProcessEngine processEngine) { if (linkedIds.length > 1) { throw new InvalidRequestException(Response.Status.INTERNAL_SERVER_ERROR, "The identity link resolver can only handle one task id"); } return super.resolveLinks(linkedIds, processEngine); } protected List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { TaskService taskService = processEngine.getTaskService(); List<IdentityLink> identityLinks = taskService.getIdentityLinksForTask(linkedIds[0]);
List<HalResource<?>> resolvedIdentityLinks = new ArrayList<HalResource<?>>(); for (IdentityLink identityLink : identityLinks) { resolvedIdentityLinks.add(HalIdentityLink.fromIdentityLink(identityLink)); } return resolvedIdentityLinks; } protected void putIntoCache(List<HalResource<?>> notCachedResources) { // this resolver only can handle a single task and resolves a list of hal resources for this task if (notCachedResources != null && !notCachedResources.isEmpty()) { String taskId = getResourceId(notCachedResources.get(0)); getCache().put(taskId, notCachedResources); } } protected String getResourceId(HalResource<?> resource) { return ((HalIdentityLink) resource).getTaskId(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\identitylink\HalIdentityLinkResolver.java
1
请完成以下Java代码
public HuIdsFilterList acceptNone() { return HuIdsFilterList.NONE; } @Override public HuIdsFilterList acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds) { return fixedHUIds; } @Override public HuIdsFilterList huQuery(@NonNull final IHUQueryBuilder initialHUQueryCopy, @NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { return null; // cannot compute } }); } public boolean isPossibleHighVolume(final int highVolumeThreshold) { final Integer estimatedSize = estimateSize(); return estimatedSize == null || estimatedSize > highVolumeThreshold; } @Nullable private Integer estimateSize() { return getFixedHUIds().map(HuIdsFilterList::estimateSize).orElse(null); } interface CaseConverter<T> { T acceptAll(); T acceptAllBut(@NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds); T acceptNone(); T acceptOnly(@NonNull HuIdsFilterList fixedHUIds, @NonNull Set<HuId> alwaysIncludeHUIds); T huQuery(@NonNull IHUQueryBuilder initialHUQueryCopy, @NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds); } public synchronized <T> T convert(@NonNull final CaseConverter<T> converter) { if (initialHUQuery == null) { if (initialHUIds == null) { throw new IllegalStateException("initialHUIds shall not be null for " + this); } else if (initialHUIds.isAll())
{ if (mustHUIds.isEmpty() && shallNotHUIds.isEmpty()) { return converter.acceptAll(); } else { return converter.acceptAllBut(ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } else { final ImmutableSet<HuId> fixedHUIds = Stream.concat( initialHUIds.stream(), mustHUIds.stream()) .distinct() .filter(huId -> !shallNotHUIds.contains(huId)) // not excluded .collect(ImmutableSet.toImmutableSet()); if (fixedHUIds.isEmpty()) { return converter.acceptNone(); } else { return converter.acceptOnly(HuIdsFilterList.of(fixedHUIds), ImmutableSet.copyOf(mustHUIds)); } } } else { return converter.huQuery(initialHUQuery.copy(), ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterData.java
1
请完成以下Java代码
public boolean addTags(String title, List<String> tags) { UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title), Updates.addEachToSet(TAGS_FIELD, tags)); return result.getModifiedCount() == 1; } /** * Removes a list of tags to the blog post with the given title. * * @param title * the title of the blog post * @param tags * a list of tags to remove * @return the outcome of the operation */ public boolean removeTags(String title, List<String> tags) { UpdateResult result = collection.updateOne(new BasicDBObject(DBCollection.ID_FIELD_NAME, title), Updates.pullAll(TAGS_FIELD, tags)); return result.getModifiedCount() == 1; } /** * Utility method used to map a MongoDB document into a {@link Post}. * * @param document * the document to map
* @return a {@link Post} object equivalent to the document passed as * argument */ @SuppressWarnings("unchecked") private static Post documentToPost(Document document) { Post post = new Post(); post.setTitle(document.getString(DBCollection.ID_FIELD_NAME)); post.setAuthor(document.getString("author")); post.setTags((List<String>) document.get(TAGS_FIELD)); return post; } /* * (non-Javadoc) * * @see java.io.Closeable#close() */ @Override public void close() throws IOException { mongoClient.close(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\tagging\TagRepository.java
1
请完成以下Java代码
public final class NullCopyPasteSupportEditor implements ICopyPasteSupportEditor { public static final transient NullCopyPasteSupportEditor instance = new NullCopyPasteSupportEditor(); public static final boolean isNull(final ICopyPasteSupportEditor copyPasteSupport) { return copyPasteSupport == null || copyPasteSupport == instance; } private NullCopyPasteSupportEditor() { super(); } @Override public void executeCopyPasteAction(CopyPasteActionType actionType) { // nothing } @Override public Action getCopyPasteAction(final CopyPasteActionType actionType) { return null; }
/** * @throws IllegalStateException always */ @Override public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke) { throw new IllegalStateException("Setting copy/paste action not supported"); } /** * @return false */ @Override public boolean isCopyPasteActionAllowed(CopyPasteActionType actionType) { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\NullCopyPasteSupportEditor.java
1
请完成以下Java代码
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter) { if (Objects.equals(PARAM_NO_HUs, parameter.getColumnName())) { return getDefaultNrOfHUs(); } else { return super.getParameterDefaultValue(parameter); } } @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final Optional<ProcessPreconditionsResolution> preconditionsResolution = checkValidSelection(); if (preconditionsResolution.isPresent()) { return preconditionsResolution.get(); } if (isForceDelivery()) { return ProcessPreconditionsResolution.rejectWithInternalReason(" Use 'WEBUI_Picking_ForcePickToComputedHU' in case of force shipping! "); } if (noSourceHUAvailable()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_MISSING_SOURCE_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { pickQtyToNewHUs(this::pickQtyToNewHU); invalidatePackablesView(); // left side view invalidatePickingSlotsView(); // right side view return MSG_OK; } protected final void pickQtyToNewHUs(@NonNull final Consumer<Quantity> pickQtyConsumer) { Quantity qtyToPack = getQtyToPack(); if (qtyToPack.signum() <= 0) { throw new AdempiereException("@QtyCU@ > 0"); } final Capacity piipCapacity = getPIIPCapacity(); if (piipCapacity.isInfiniteCapacity()) { pickQtyConsumer.accept(qtyToPack); return; } final Quantity piipQtyCapacity = piipCapacity.toQuantity(); while (qtyToPack.toBigDecimal().signum() > 0) { final Quantity qtyToProcess = piipQtyCapacity.min(qtyToPack); pickQtyConsumer.accept(qtyToProcess); qtyToPack = qtyToPack.subtract(qtyToProcess); }
} @NonNull private QuantityTU getQtyTU() { return getPIIPCapacity().calculateQtyTU(qtyCUsPerTU, getCurrentShipmentScheuduleUOM(), uomConversionBL) .orElseThrow(() -> new AdempiereException("QtyTU cannot be obtained for the current request!") .appendParametersToMessage() .setParameter("QtyCU", qtyCUsPerTU) .setParameter("ShipmentScheduleId", getCurrentShipmentScheduleId())); } @NonNull protected final Capacity getPIIPCapacity() { final I_M_ShipmentSchedule currentShipmentSchedule = getCurrentShipmentSchedule(); final ProductId productId = ProductId.ofRepoId(currentShipmentSchedule.getM_Product_ID()); final I_C_UOM stockUOM = productBL.getStockUOM(productId); return huCapacityBL.getCapacity(huPIItemProduct, productId, stockUOM); } @NonNull private BigDecimal getDefaultNrOfHUs() { if (qtyCUsPerTU == null || huPIItemProduct == null) { return BigDecimal.ONE; } return getQtyTU().toBigDecimal(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_PickQtyToComputedHU.java
1
请在Spring Boot框架中完成以下Java代码
public class Config { // tag::topicBeans[] @Bean public KafkaAdmin admin() { Map<String, Object> configs = new HashMap<>(); configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); return new KafkaAdmin(configs); } @Bean public NewTopic topic1() { return TopicBuilder.name("thing1") .partitions(10) .replicas(3) .compact() .build(); } @Bean public NewTopic topic2() { return TopicBuilder.name("thing2") .partitions(10) .replicas(3) .config(TopicConfig.COMPRESSION_TYPE_CONFIG, "zstd") .build(); } @Bean public NewTopic topic3() { return TopicBuilder.name("thing3") .assignReplicas(0, List.of(0, 1)) .assignReplicas(1, List.of(1, 2)) .assignReplicas(2, List.of(2, 0)) .config(TopicConfig.COMPRESSION_TYPE_CONFIG, "zstd") .build(); } // end::topicBeans[] // tag::brokerProps[] @Bean public NewTopic topic4() { return TopicBuilder.name("defaultBoth") .build(); }
@Bean public NewTopic topic5() { return TopicBuilder.name("defaultPart") .replicas(1) .build(); } @Bean public NewTopic topic6() { return TopicBuilder.name("defaultRepl") .partitions(3) .build(); } // end::brokerProps[] // tag::newTopicsBean[] @Bean public KafkaAdmin.NewTopics topics456() { return new NewTopics( TopicBuilder.name("defaultBoth") .build(), TopicBuilder.name("defaultPart") .replicas(1) .build(), TopicBuilder.name("defaultRepl") .partitions(3) .build()); } // end::newTopicsBean[] }
repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\topics\Config.java
2
请完成以下Java代码
public boolean containsDataStore(String id) { return dataStoreMap.containsKey(id); } public List<Pool> getPools() { return pools; } public void setPools(List<Pool> pools) { this.pools = pools; } public List<Import> getImports() { return imports; } public void setImports(List<Import> imports) { this.imports = imports; } public List<Interface> getInterfaces() { return interfaces; } public void setInterfaces(List<Interface> interfaces) { this.interfaces = interfaces; } public List<Artifact> getGlobalArtifacts() { return globalArtifacts; } public void setGlobalArtifacts(List<Artifact> globalArtifacts) { this.globalArtifacts = globalArtifacts; } public void addNamespace(String prefix, String uri) { namespaceMap.put(prefix, uri); } public boolean containsNamespacePrefix(String prefix) { return namespaceMap.containsKey(prefix); } public String getNamespace(String prefix) { return namespaceMap.get(prefix); } public Map<String, String> getNamespaces() { return namespaceMap; } public String getTargetNamespace() { return targetNamespace; } public void setTargetNamespace(String targetNamespace) {
this.targetNamespace = targetNamespace; } public String getSourceSystemId() { return sourceSystemId; } public void setSourceSystemId(String sourceSystemId) { this.sourceSystemId = sourceSystemId; } public List<String> getUserTaskFormTypes() { return userTaskFormTypes; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public List<String> getStartEventFormTypes() { return startEventFormTypes; } public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } @JsonIgnore public Object getEventSupport() { return eventSupport; } public void setEventSupport(Object eventSupport) { this.eventSupport = eventSupport; } public String getStartFormKey(String processId) { FlowElement initialFlowElement = getProcessById(processId).getInitialFlowElement(); if (initialFlowElement instanceof StartEvent) { StartEvent startEvent = (StartEvent) initialFlowElement; return startEvent.getFormKey(); } return null; } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BpmnModel.java
1