instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public SetRemovalTimeToHistoricDecisionInstancesBuilder byQuery(HistoricDecisionInstanceQuery query) { this.query = query; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder byIds(String... ids) { this.ids = ids != null ? Arrays.asList(ids) : null; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder absoluteRemovalTime(Date removalTime) { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.ABSOLUTE_REMOVAL_TIME; this.removalTime = removalTime; return this; } @Override public SetRemovalTimeToHistoricDecisionInstancesBuilder calculatedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); this.mode = Mode.CALCULATED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder clearedRemovalTime() { ensureNull(BadUserRequestException.class, "The removal time modes are mutually exclusive","mode", mode); mode = Mode.CLEARED_REMOVAL_TIME; return this; } public SetRemovalTimeToHistoricDecisionInstancesBuilder hierarchical() { isHierarchical = true; return this; }
public Batch executeAsync() { return commandExecutor.execute(new SetRemovalTimeToHistoricDecisionInstancesCmd(this)); } public HistoricDecisionInstanceQuery getQuery() { return query; } public List<String> getIds() { return ids; } public Date getRemovalTime() { return removalTime; } public Mode getMode() { return mode; } public enum Mode { CALCULATED_REMOVAL_TIME, ABSOLUTE_REMOVAL_TIME, CLEARED_REMOVAL_TIME; } public boolean isHierarchical() { return isHierarchical; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricDecisionInstancesBuilderImpl.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; }
public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } }
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\multicriteria\Product.java
1
请在Spring Boot框架中完成以下Java代码
public AuthTokenFilter authenticationJwtTokenFilter() { return new AuthTokenFilter(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception { return authConfig.getAuthenticationManager();
} @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable) .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL) .permitAll() .anyRequest() .authenticated()) .exceptionHandling(ex -> ex.authenticationEntryPoint(unauthorizedHandler)) .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) .authenticationProvider(authenticationProvider()) .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\securityconfig\SecurityConfiguration.java
2
请完成以下Java代码
public class ProcessCandidateStarterUserRemovedListenerDelegate implements ActivitiEventListener { private List<ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent>> listeners; private ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter; public ProcessCandidateStarterUserRemovedListenerDelegate( List<ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent>> listeners, ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter ) { this.listeners = listeners; this.processCandidateStarterUserRemovedEventConverter = processCandidateStarterUserRemovedEventConverter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiEntityEvent) {
processCandidateStarterUserRemovedEventConverter .from((ActivitiEntityEvent) event) .ifPresent(convertedEvent -> { for (ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent> listener : listeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ProcessCandidateStarterUserRemovedListenerDelegate.java
1
请完成以下Java代码
protected void terminating(CmmnActivityExecution execution) { TaskEntity task = getTask(execution); // it can happen that a there does not exist // a task, because the given execution was never // active. if (task != null) { task.delete("terminated", false); } } protected void completing(CmmnActivityExecution execution) { TaskEntity task = getTask(execution); if (task != null) { task.caseExecutionCompleted(); } } protected void manualCompleting(CmmnActivityExecution execution) { completing(execution); } protected void suspending(CmmnActivityExecution execution) { String id = execution.getId(); Context .getCommandContext() .getTaskManager() .updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.SUSPENDED); } protected void resuming(CmmnActivityExecution execution) { String id = execution.getId(); Context .getCommandContext() .getTaskManager() .updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.ACTIVE); } protected TaskEntity getTask(CmmnActivityExecution execution) { return Context
.getCommandContext() .getTaskManager() .findTaskByCaseExecutionId(execution.getId()); } protected String getTypeName() { return "human task"; } // getters/setters ///////////////////////////////////////////////// public TaskDecorator getTaskDecorator() { return taskDecorator; } public void setTaskDecorator(TaskDecorator taskDecorator) { this.taskDecorator = taskDecorator; } public TaskDefinition getTaskDefinition() { return taskDecorator.getTaskDefinition(); } public ExpressionManager getExpressionManager() { return taskDecorator.getExpressionManager(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\HumanTaskActivityBehavior.java
1
请完成以下Java代码
public class PMMPurchaseCandidateDAO implements IPMMPurchaseCandidateDAO { @Override public void deletePurchaseCandidateOrderLines(final I_C_Order order) { retrivePurchaseCandidateOrderLines(order) .create() .delete(); } @Override public IQueryBuilder<I_PMM_PurchaseCandidate_OrderLine> retrivePurchaseCandidateOrderLines(final I_C_Order order) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_OrderLine.class, order) .addEqualsFilter(I_C_OrderLine.COLUMN_C_Order_ID, order.getC_Order_ID()) .andCollectChildren(I_PMM_PurchaseCandidate_OrderLine.COLUMN_C_OrderLine_ID, I_PMM_PurchaseCandidate_OrderLine.class); } @Override public I_PMM_PurchaseCandidate retrieveFor(final PMMPurchaseCandidateSegment pmmSegment, final Date day) { return queryFor(pmmSegment, day, NullQueryFilterModifier.instance) .create() .firstOnly(I_PMM_PurchaseCandidate.class); } @Override public boolean hasRecordsForWeek(final PMMPurchaseCandidateSegment pmmSegment, final Date weekDate) { return queryFor(pmmSegment, weekDate, DateTruncQueryFilterModifier.WEEK) .create() .anyMatch(); }
private final IQueryBuilder<I_PMM_PurchaseCandidate> queryFor(final PMMPurchaseCandidateSegment pmmSegment, final Date day, final IQueryFilterModifier dayModifier) { Check.assumeNotNull(pmmSegment, "pmmSegment not null"); Check.assumeNotNull(day, "day not null"); final PlainContextAware context = PlainContextAware.newWithThreadInheritedTrx(); return Services.get(IQueryBL.class) .createQueryBuilder(I_PMM_PurchaseCandidate.class, context) .addOnlyActiveRecordsFilter() // // Segment .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_C_BPartner_ID, pmmSegment.getC_BPartner_ID() > 0 ? pmmSegment.getC_BPartner_ID() : null) .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_Product_ID, pmmSegment.getM_Product_ID() > 0 ? pmmSegment.getM_Product_ID() : null) .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_AttributeSetInstance_ID, pmmSegment.getM_AttributeSetInstance_ID() > 0 ? pmmSegment.getM_AttributeSetInstance_ID() : null) .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_HU_PI_Item_Product_ID, pmmSegment.getM_HU_PI_Item_Product_ID() > 0 ? pmmSegment.getM_HU_PI_Item_Product_ID() : null) .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_C_Flatrate_DataEntry_ID, pmmSegment.getC_Flatrate_DataEntry_ID() > 0 ? pmmSegment.getC_Flatrate_DataEntry_ID() : null) // // Date .addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, day, dayModifier); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPurchaseCandidateDAO.java
1
请完成以下Java代码
public Connection getConnection() throws SQLException { // 获取当前数据源 id Long id = DatasourceConfigContextHolder.getCurrentDatasourceConfig(); // 根据当前id获取数据源 HikariDataSource datasource = DatasourceHolder.INSTANCE.getDatasource(id); if (null == datasource) { datasource = initDatasource(id); } return datasource.getConnection(); } /** * 初始化数据源 * * @param id 数据源id * @return 数据源 */ private HikariDataSource initDatasource(Long id) { HikariDataSource dataSource = new HikariDataSource(); // 判断是否是默认数据源 if (DatasourceHolder.DEFAULT_ID.equals(id)) { // 默认数据源根据 application.yml 配置的生成 DataSourceProperties properties = SpringUtil.getBean(DataSourceProperties.class);
dataSource.setJdbcUrl(properties.getUrl()); dataSource.setUsername(properties.getUsername()); dataSource.setPassword(properties.getPassword()); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); } else { // 不是默认数据源,通过缓存获取对应id的数据源的配置 DatasourceConfig datasourceConfig = DatasourceConfigCache.INSTANCE.getConfig(id); if (datasourceConfig == null) { throw new RuntimeException("无此数据源"); } dataSource.setJdbcUrl(datasourceConfig.buildJdbcUrl()); dataSource.setUsername(datasourceConfig.getUsername()); dataSource.setPassword(datasourceConfig.getPassword()); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); } // 将创建的数据源添加到数据源管理器中,绑定当前线程 DatasourceHolder.INSTANCE.addDatasource(id, dataSource); return dataSource; } }
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\datasource\DynamicDataSource.java
1
请完成以下Java代码
public class ListPodsWithLabelSelectors { private static final Logger log = LoggerFactory.getLogger(ListPodsWithLabelSelectors.class); /** * @param args */ public static void main(String[] args) throws Exception { ApiClient client = Config.defaultClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient newClient = client.getHttpClient() .newBuilder() .addInterceptor(interceptor) .readTimeout(0, TimeUnit.SECONDS) .build(); client.setHttpClient(newClient); CoreV1Api api = new CoreV1Api(client); String selector = createSelector(args); V1PodList items = api.listPodForAllNamespaces(null, null, null, selector, null, null, null, null, 10, false); items.getItems() .stream() .map((pod) -> pod.getMetadata().getName() ) .forEach((name) -> System.out.println("name=" + name));
} private static String createSelector(String[] args) { StringBuilder b = new StringBuilder(); for( int i = 0 ; i < args.length; i++ ) { if( b.length() > 0 ) { b.append(','); } b.append(args[i]); } return b.toString(); } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\ListPodsWithLabelSelectors.java
1
请完成以下Java代码
public DataType getDataType() { return DataType.DOUBLE; } @Override public Optional<Double> getDoubleValue() { return Optional.ofNullable(value); } @Override public Object getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DoubleDataEntry)) return false; if (!super.equals(o)) return false; DoubleDataEntry that = (DoubleDataEntry) o;
return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(super.hashCode(), value); } @Override public String toString() { return "DoubleDataEntry{" + "value=" + value + "} " + super.toString(); } @Override public String getValueAsString() { return Double.toString(value); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\DoubleDataEntry.java
1
请完成以下Java代码
public String getCostUnit() { return costUnit; } /** * Sets the value of the costUnit property. * * @param value * allowed object is * {@link String } * */ public void setCostUnit(String value) { this.costUnit = value; }
/** * Gets the value of the status property. * */ public int getStatus() { return status; } /** * Sets the value of the status property. * */ public void setStatus(int value) { this.status = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ValidationResultType.java
1
请在Spring Boot框架中完成以下Java代码
private static void usingDefaultFactory() { ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingCustomFactory() { CustomThreadFactory myThreadFactory = new CustomThreadFactory("MyCustomThread-"); ExecutorService executorService = Executors.newFixedThreadPool(3, myThreadFactory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingCommonsLang() { BasicThreadFactory factory = new BasicThreadFactory.Builder() .namingPattern("MyCustomThread-%d").priority(Thread.MAX_PRIORITY).build();
ExecutorService executorService = Executors.newFixedThreadPool(3, factory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } private static void usingGuvava() { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("MyCustomThread-%d").build(); ExecutorService executorService = Executors.newFixedThreadPool(3, namedThreadFactory); for (int i = 0; i < 5; i++) { executorService.execute(() -> logger.info(Thread.currentThread().getName())); } executorService.shutdown(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executerservicecustomthreadname\ExecuterServiceCustomThreadName.java
2
请完成以下Java代码
public class PageData<T> implements Serializable { public static final PageData EMPTY_PAGE_DATA = new PageData<>(); private final List<T> data; private final int totalPages; private final long totalElements; private final boolean hasNext; public PageData() { this(Collections.emptyList(), 0, 0, false); } @JsonCreator public PageData(@JsonProperty("data") List<T> data, @JsonProperty("totalPages") int totalPages, @JsonProperty("totalElements") long totalElements, @JsonProperty("hasNext") boolean hasNext) { this.data = data; this.totalPages = totalPages; this.totalElements = totalElements; this.hasNext = hasNext; } @SuppressWarnings("unchecked") public static <T> PageData<T> emptyPageData() { return (PageData<T>) EMPTY_PAGE_DATA; } @Schema(description = "Array of the entities", accessMode = Schema.AccessMode.READ_ONLY) public List<T> getData() { return data; }
@Schema(description = "Total number of available pages. Calculated based on the 'pageSize' request parameter and total number of entities that match search criteria", accessMode = Schema.AccessMode.READ_ONLY) public int getTotalPages() { return totalPages; } @Schema(description = "Total number of elements in all available pages", accessMode = Schema.AccessMode.READ_ONLY) public long getTotalElements() { return totalElements; } @Schema(description = "'false' value indicates the end of the result set", accessMode = Schema.AccessMode.READ_ONLY) @JsonProperty("hasNext") public boolean hasNext() { return hasNext; } public <D> PageData<D> mapData(Function<T, D> mapper) { return new PageData<>(getData().stream().map(mapper).collect(Collectors.toList()), getTotalPages(), getTotalElements(), hasNext()); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\PageData.java
1
请完成以下Java代码
public Object getSingleValueAsObject() { if (noValue) { return null; } else if (singleValue != null) { return singleValue; } else { throw new AdempiereException("Not a single value instance: " + this); } } public ImmutableList<Object> getMultipleValues() { if (multipleValues != null) { return multipleValues; } else { throw new AdempiereException("Not a multiple values instance: " + this); } } @Nullable public Integer getSingleValueAsInteger(@Nullable final Integer defaultValue) { final Object value = getSingleValueAsObject(); if (value == null) { return defaultValue; } else if (value instanceof Number) { return ((Number)value).intValue(); } else { final String valueStr = StringUtils.trimBlankToNull(value.toString()); if (valueStr == null) { return defaultValue; } else { return Integer.parseInt(valueStr); } } } @Nullable public String getSingleValueAsString() { final Object value = getSingleValueAsObject(); return value != null ? value.toString() : null; } public Stream<IdsToFilter> streamSingleValues() { if (noValue) {
return Stream.empty(); } else if (singleValue != null) { return Stream.of(this); } else { Objects.requireNonNull(multipleValues); return multipleValues.stream().map(IdsToFilter::ofSingleValue); } } public ImmutableList<Object> toImmutableList() { if (noValue) { return ImmutableList.of(); } else if (singleValue != null) { return ImmutableList.of(singleValue); } else { Objects.requireNonNull(multipleValues); return multipleValues; } } public IdsToFilter mergeWith(@NonNull final IdsToFilter other) { if (other.isNoValue()) { return this; } else if (isNoValue()) { return other; } else { final ImmutableSet<Object> multipleValues = Stream.concat(toImmutableList().stream(), other.toImmutableList().stream()) .distinct() .collect(ImmutableSet.toImmutableSet()); return ofMultipleValues(multipleValues); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\IdsToFilter.java
1
请在Spring Boot框架中完成以下Java代码
public PageData<OtaPackage> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(otaPackageRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Transactional @Override public PageData<OtaPackage> findByTenantId(UUID tenantId, PageLink pageLink) { return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink); } @Override public PageData<OtaPackageId> findIdsByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.pageToPageData(otaPackageRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink)).map(OtaPackageId::new)); } @Transactional @Override public OtaPackage findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(otaPackageRepository.findByTenantIdAndExternalId(tenantId, externalId)); }
@Override public OtaPackageId getExternalIdByInternal(OtaPackageId internalId) { return DaoUtil.toEntityId(otaPackageRepository.getExternalIdById(internalId.getId()), OtaPackageId::new); } @Override protected Class<OtaPackageEntity> getEntityClass() { return OtaPackageEntity.class; } @Override protected JpaRepository<OtaPackageEntity, UUID> getRepository() { return otaPackageRepository; } @Override public EntityType getEntityType() { return EntityType.OTA_PACKAGE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ota\JpaOtaPackageDao.java
2
请完成以下Java代码
public class RuleEngineException extends Exception { protected static final ObjectMapper mapper = new ObjectMapper(); @Getter private final long ts; public RuleEngineException(String message) { this(message, null); } public RuleEngineException(String message, Throwable t) { super(message != null ? message : "Unknown", t); ts = System.currentTimeMillis(); }
public String toJsonString(int maxMessageLength) { try { return mapper.writeValueAsString(mapper.createObjectNode() .put("message", truncateIfNecessary(getMessage(), maxMessageLength))); } catch (JsonProcessingException e) { log.warn("Failed to serialize exception ", e); throw new RuntimeException(e); } } protected String truncateIfNecessary(String message, int maxMessageLength) { return StringUtils.truncate(message, maxMessageLength); } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\queue\RuleEngineException.java
1
请完成以下Java代码
public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; } protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody); protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception; private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); } throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); } protected String constructFunctionName(UUID scriptId, String scriptHash) {
return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1
请在Spring Boot框架中完成以下Java代码
public final class ReactiveManagementWebSecurityAutoConfiguration { @Bean SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, PreFlightRequestHandler handler) { http.authorizeExchange((exchanges) -> { exchanges.matchers(healthMatcher(), additionalHealthPathsMatcher()).permitAll(); exchanges.anyExchange().authenticated(); }); PreFlightRequestWebFilter filter = new PreFlightRequestWebFilter(handler); http.addFilterAt(filter, SecurityWebFiltersOrder.CORS); http.httpBasic(withDefaults()); http.formLogin(withDefaults()); return http.build(); }
private ServerWebExchangeMatcher healthMatcher() { return EndpointRequest.to(HealthEndpoint.class); } private ServerWebExchangeMatcher additionalHealthPathsMatcher() { return EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, HealthEndpoint.class); } @Bean @ConditionalOnMissingBean({ ReactiveAuthenticationManager.class, ReactiveUserDetailsService.class }) ReactiveAuthenticationManager denyAllAuthenticationManager() { return (authentication) -> Mono.error(new UsernameNotFoundException(authentication.getName())); } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\actuate\web\reactive\ReactiveManagementWebSecurityAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public Region _id(String _id) { this._id = _id; return this; } /** * Id * @return _id **/ @Schema(example = "5ada01a2c3918e1bdcb54612", required = true, description = "Id") public String getId() { return _id; } public void setId(String _id) { this._id = _id; } public Region label(String label) { this.label = label; return this; } /** * Get label * @return label **/ @Schema(example = "Nordost", description = "") public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Region parent(String parent) { this.parent = parent; return this; } /** * Id der übergeordneten Region * @return parent **/ @Schema(example = "5afc1d30b37364c26e9ca501", description = "Id der übergeordneten Region") public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public Region timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; }
public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Region region = (Region) o; return Objects.equals(this._id, region._id) && Objects.equals(this.label, region.label) && Objects.equals(this.parent, region.parent) && Objects.equals(this.timestamp, region.timestamp); } @Override public int hashCode() { return Objects.hash(_id, label, parent, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).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-patient-api\src\main\java\io\swagger\client\model\Region.java
2
请完成以下Java代码
public boolean isImmutable() { return immutable; } @Override public IStringExpression getPrefilterWhereClause() { return whereClause; } @Override public Set<String> getAllParameters() { return ImmutableSet.of(); } public List<Object> getParameterValues(final String searchSQL)
{ final List<Object> params = new ArrayList<>(paramsTemplate); if (immutable) { return params; } for (int i = 0; i < params.size(); i++) { if (params.get(i) == SEARCHSQL_PLACEHOLDER) { params.set(i, searchSQL); } } return params; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VLookupAutoCompleterValidationRule.java
1
请完成以下Java代码
protected JButton createDecreaseButton(final int orientation) { return noButton; } @Override protected JButton createIncreaseButton(final int orientation) { return noButton; } @Override protected TrackListener createTrackListener() { return new MetasTrackListener(); } private class MetasTrackListener extends TrackListener { @Override public void mousePressed(MouseEvent e) { isMouseButtonPressed = true; super.mousePressed(e);
scrollbar.repaint(getThumbBounds()); } @Override public void mouseReleased(MouseEvent e) { isMouseButtonPressed = false; super.mouseReleased(e); scrollbar.repaint(getThumbBounds()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshScrollBarUI.java
1
请完成以下Java代码
public static QtyTU ofNullableString(@Nullable final String stringValue) { final String stringValueNorm = StringUtils.trimBlankToNull(stringValue); return stringValueNorm != null ? ofString(stringValueNorm) : null; } public static final QtyTU ZERO; public static final QtyTU ONE; public static final QtyTU TWO; public static final QtyTU THREE; public static final QtyTU FOUR; private static final QtyTU[] cache = new QtyTU[] { ZERO = new QtyTU(0), ONE = new QtyTU(1), TWO = new QtyTU(2), THREE = new QtyTU(3), FOUR = new QtyTU(4), new QtyTU(5), new QtyTU(6), new QtyTU(7), new QtyTU(8), new QtyTU(9), new QtyTU(10), }; final int intValue; private QtyTU(final int intValue) { Check.assumeGreaterOrEqualToZero(intValue, "QtyTU"); this.intValue = intValue; } @Override @Deprecated public String toString() { return String.valueOf(intValue); } public static boolean equals(@Nullable final QtyTU qtyTU1, @Nullable final QtyTU qtyTU2) {return Objects.equals(qtyTU1, qtyTU2);} @JsonValue public int toInt() { return intValue; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(intValue); } @Override public int compareTo(@NonNull final QtyTU other) { return this.intValue - other.intValue; } public int compareTo(@NonNull final BigDecimal other) { return this.intValue - other.intValueExact(); } public boolean isGreaterThan(@NonNull final QtyTU other) {return compareTo(other) > 0;}
public boolean isZero() {return intValue == 0;} public boolean isPositive() {return intValue > 0;} public boolean isOne() {return intValue == 1;} public QtyTU add(@NonNull final QtyTU toAdd) { if (this.intValue == 0) { return toAdd; } else if (toAdd.intValue == 0) { return this; } else { return ofInt(this.intValue + toAdd.intValue); } } public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract) { if (toSubtract.intValue == 0) { return this; } else { return ofInt(Math.max(this.intValue - toSubtract.intValue, 0)); } } public QtyTU min(@NonNull final QtyTU other) { return this.intValue <= other.intValue ? this : other; } public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal) { if (isZero()) { throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal); } else if (isOne()) { return qtyCUsTotal; } else { return qtyCUsTotal.divide(toInt()); } } public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU) { return qtyCUsPerTU.multiply(toInt()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java
1
请完成以下Java代码
public class SetRetriesForExternalTasksDto { protected List<String> externalTaskIds; protected List<String> processInstanceIds; protected ExternalTaskQueryDto externalTaskQuery; protected ProcessInstanceQueryDto processInstanceQuery; protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; protected Integer retries; public List<String> getExternalTaskIds() { return externalTaskIds; } public void setExternalTaskIds(List<String> externalTaskIds) { this.externalTaskIds = externalTaskIds; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ExternalTaskQueryDto getExternalTaskQuery() { return externalTaskQuery; } public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQueryDto) { this.processInstanceQuery = processInstanceQueryDto;
} public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto) { this.historicProcessInstanceQuery = historicProcessInstanceQueryDto; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\SetRetriesForExternalTasksDto.java
1
请完成以下Java代码
public MSV3AvailiabilityClient newAvailabilityClient(@NonNull final MSV3ClientConfig config) { config.assertVersion(getVersionId()); return MSV3AvailiabilityClientImpl.builder() .connectionFactory(connectionFactory) .config(config) .jaxbConverters(StockAvailabilityJAXBConvertersV2.instance) .build(); } @Override public MSV3PurchaseOrderClient newPurchaseOrderClient(@NonNull final MSV3ClientConfig config) { config.assertVersion(getVersionId()); return MSV3PurchaseOrderClientImpl.builder() .connectionFactory(connectionFactory) .config(config) .supportIdProvider(supportIdProvider) .jaxbConverters(OrderJAXBConvertersV2.instance) .build();
} @VisibleForTesting public static FaultInfo extractFaultInfoOrNull(final Object value) { if (value instanceof Msv3FaultInfo) { final Msv3FaultInfo msv3FaultInfo = (Msv3FaultInfo)value; return MiscJAXBConvertersV2.fromJAXB(msv3FaultInfo); } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3ClientFactoryV2.java
1
请完成以下Java代码
public void assertCanCreateOrUpdate(final Object record) { final OrgId orgId = getOrgId(record).orElse(OrgId.ANY); final int adTableId = getModelTableId(record); final int recordId; if (isNew(record)) { recordId = -1; } else { recordId = getId(record); } assertPermission(PermissionRequest.builder() .orgId(orgId) .adTableId(adTableId) .recordId(recordId) .build()); } 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
请在Spring Boot框架中完成以下Java代码
public Job multiFileItemReaderJob() { return jobBuilderFactory.get("multiFileItemReaderJob") .start(step()) .build(); } private Step step() { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(multiFileItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> multiFileItemReader() { MultiResourceItemReader<TestData> reader = new MultiResourceItemReader<>(); reader.setDelegate(fileItemReader()); // 设置文件读取代理,方法可以使用前面文件读取中的例子 Resource[] resources = new Resource[]{ new ClassPathResource("file1"), new ClassPathResource("file2") }; reader.setResources(resources); // 设置多文件源 return reader; } private FlatFileItemReader<TestData> fileItemReader() { FlatFileItemReader<TestData> reader = new FlatFileItemReader<>(); reader.setLinesToSkip(1); // 忽略第一行 // AbstractLineTokenizer的三个实现类之一,以固定分隔符处理行数据读取, // 使用默认构造器的时候,使用逗号作为分隔符,也可以通过有参构造器来指定分隔符 DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
// 设置属姓名,类似于表头 tokenizer.setNames("id", "field1", "field2", "field3"); // 将每行数据转换为TestData对象 DefaultLineMapper<TestData> mapper = new DefaultLineMapper<>(); mapper.setLineTokenizer(tokenizer); // 设置映射方式 mapper.setFieldSetMapper(fieldSet -> { TestData data = new TestData(); data.setId(fieldSet.readInt("id")); data.setField1(fieldSet.readString("field1")); data.setField2(fieldSet.readString("field2")); data.setField3(fieldSet.readString("field3")); return data; }); reader.setLineMapper(mapper); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\MultiFileIteamReaderDemo.java
2
请完成以下Java代码
public String getXmlEncoding() { return xmlEncoding; } public ProcessEngineConfiguration setXmlEncoding(String xmlEncoding) { this.xmlEncoding = xmlEncoding; return this; } public Clock getClock() { return clock; } public ProcessEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } public ProcessDiagramGenerator getProcessDiagramGenerator() { return this.processDiagramGenerator; } public ProcessEngineConfiguration setProcessDiagramGenerator(ProcessDiagramGenerator processDiagramGenerator) { this.processDiagramGenerator = processDiagramGenerator; return this; } public AsyncExecutor getAsyncExecutor() { return asyncExecutor; } public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) { this.asyncExecutor = asyncExecutor; return this; } public int getLockTimeAsyncJobWaitTime() { return lockTimeAsyncJobWaitTime; } public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) { this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this; } public int getDefaultFailedJobWaitTime() { return defaultFailedJobWaitTime; } public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) { this.defaultFailedJobWaitTime = defaultFailedJobWaitTime; return this; } public int getAsyncFailedJobWaitTime() { return asyncFailedJobWaitTime; } public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) { this.asyncFailedJobWaitTime = asyncFailedJobWaitTime; return this; } public boolean isEnableProcessDefinitionInfoCache() { return enableProcessDefinitionInfoCache; } public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) { this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache; return this; } public List<JobProcessor> getJobProcessors() { return jobProcessors; } public ProcessEngineConfiguration setJobProcessors(List<JobProcessor> jobProcessors) { this.jobProcessors = jobProcessors; return this; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java
1
请完成以下Java代码
public void validate(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, MigrationInstructionValidationReportImpl report) { ActivityImpl sourceActivity = instruction.getSourceActivity(); ActivityImpl targetActivity = instruction.getTargetActivity(); Class<?> sourceBehaviorClass = sourceActivity.getActivityBehavior().getClass(); Class<?> targetBehaviorClass = targetActivity.getActivityBehavior().getClass(); if (!sameBehavior(sourceBehaviorClass, targetBehaviorClass)) { report.addFailure("Activities have incompatible types " + "(" + sourceBehaviorClass.getSimpleName() + " is not compatible with " + targetBehaviorClass.getSimpleName() + ")"); } } protected boolean sameBehavior(Class<?> sourceBehavior, Class<?> targetBehavior) {
if (sourceBehavior == targetBehavior) { return true; } else { Set<Class<?>> equivalentBehaviors = this.equivalentBehaviors.get(sourceBehavior); if (equivalentBehaviors != null) { return equivalentBehaviors.contains(targetBehavior); } else { return false; } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\SameBehaviorInstructionValidator.java
1
请完成以下Java代码
void updateStorageAttributesKey(@NonNull final I_PP_Product_Planning record) { final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(record.getM_AttributeSetInstance_ID()); final AttributesKey attributesKey = AttributesKeys.createAttributesKeyFromASIStorageAttributes(asiId).orElse(AttributesKey.NONE); record.setStorageAttributesKey(attributesKey.getAsString()); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_PP_Product_Planning.COLUMNNAME_M_Product_ID, I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID }) public void validateBOMVersionsAndProductId(final I_PP_Product_Planning record) { final ProductPlanning productPlanning = ProductPlanningDAO.fromRecord(record); final ProductId productId = productPlanning.getProductId(); if (productId == null) { return; } Optional.ofNullable(productPlanning.getBomVersionsId()) .map(bomVersionsDAO::getBOMVersions) .ifPresent(bomVersions -> { if (bomVersions.getM_Product_ID() != productId.getRepoId()) { throw new AdempiereException(AdMessageKey.of("PP_Product_Planning_BOM_Doesnt_Match")) .appendParametersToMessage() .setParameter("bomVersion", bomVersions) .setParameter("productPlanning", productPlanning) .markAsUserValidationError(); } }); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = {I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID}) public void updateProductFromBomVersions(final I_PP_Product_Planning planning) { final ProductBOMVersionsId bomVersionsId = ProductBOMVersionsId.ofRepoIdOrNull(planning.getPP_Product_BOMVersions_ID()); if (bomVersionsId == null) { return; // nothing to do } final I_PP_Product_BOMVersions bomVersions = bomVersionsDAO.getBOMVersions(bomVersionsId);
planning.setM_Product_ID(bomVersions.getM_Product_ID()); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_PP_Product_Planning.COLUMNNAME_PP_Product_BOMVersions_ID, I_PP_Product_Planning.COLUMNNAME_IsAttributeDependant, I_PP_Product_Planning.COLUMNNAME_M_AttributeSetInstance_ID, }) public void validateProductBOMASI(@NonNull final I_PP_Product_Planning record) { final ProductPlanning productPlanning = ProductPlanningDAO.fromRecord(record); if (!productPlanning.isAttributeDependant()) { return; } if (productPlanning.getBomVersionsId() == null) { return; } final I_PP_Product_BOM bom = bomDAO.getLatestBOMRecordByVersionId(productPlanning.getBomVersionsId()).orElse(null); if (bom == null) { return; } productBOMService.verifyBOMAssignment(productPlanning, bom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Product_Planning.java
1
请完成以下Java代码
public ASILayout build() { return new ASILayout(this); } private List<DocumentLayoutElementDescriptor> buildElements() { return elementBuilders .stream() .map(elementBuilder -> elementBuilder.build()) .collect(GuavaCollectors.toImmutableList()); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("asiDescriptorId", asiDescriptorId) .add("caption", caption) .add("elements-count", elementBuilders.size()) .toString(); } public Builder setASIDescriptorId(final DocumentId asiDescriptorId) {
this.asiDescriptorId = asiDescriptorId; return this; } public Builder setCaption(final ITranslatableString caption) { this.caption = caption; return this; } public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) { Check.assumeNotNull(elementBuilder, "Parameter elementBuilder is not null"); elementBuilders.add(elementBuilder); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILayout.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthParamVo implements Serializable { private static final long serialVersionUID = -428316450503841861L; /** * 支付Key */ @Size(max = 32, message = "支付Key[payKey]长度最大32位") @NotNull(message = "支付Key[payKey]不能为空") private String payKey; /** * 订单号 */ @Size(max = 32, message = "订单号[orderNo]长度最大32位") @NotNull(message = "订单号[orderNo]不能为空") private String orderNo; /** * 用户姓名 */ @Size(max = 50, message = "用户姓名[userName]长度最大50位") @NotNull(message = "用户姓名[userName]不能为空") private String userName; /** * 手机号 */ @Size(max = 11, message = "手机号码[phone]长度最大11位") @NotNull(message = "手机号码[phone]不能为空") private String phone; /** * 身份证号 */ @Size(max = 18, message = "身份证号[idNo]长度最大18位") @NotNull(message = "身份证号[idNo]不能为空") private String idNo; /** * 银行卡号 */ @Size(max = 20, message = "银行卡号[bankAccountNo]长度最大20位") @NotNull(message = "银行卡号[bankAccountNo]不能为空") private String bankAccountNo; /** * 备注 */ private String remark; /** * 签名 */ @NotNull(message = "数据签名[sign]不能为空") private String sign; public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthParamVo.java
2
请完成以下Java代码
public class Article { Integer id; String title; public Article() {} public Article(Integer id, String title) { this.id = id; this.title = title; } public Integer getId() { return id; } public String getTitle() { return title; } public void setId(Integer id) {
this.id = id; } public void setTitle(String title) { this.title = title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Article article = (Article) o; return Objects.equals(id, article.id) && Objects.equals(title, article.title); } @Override public int hashCode() { return Objects.hash(id, title); } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\restclient\Article.java
1
请在Spring Boot框架中完成以下Java代码
public class AppConfig implements WebMvcConfigurer { @Autowired private Environment env; @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("driverClassName")); dataSource.setUrl(env.getProperty("url")); dataSource.setUsername(env.getProperty("user")); dataSource.setPassword(env.getProperty("password")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.baeldung.relationships.models"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; }
final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); if (env.getProperty("hibernate.hbm2ddl.auto") != null) { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); } if (env.getProperty("hibernate.dialect") != null) { hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); } if (env.getProperty("hibernate.show_sql") != null) { hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); } return hibernateProperties; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\AppConfig.java
2
请完成以下Java代码
private Timestamp parseDate(final String valueStr) { if (Check.isEmpty(valueStr, true)) { return null; } try { final DateFormat dateFormat = getDateFormat(); final Date date = dateFormat.parse(valueStr.trim()); return TimeUtil.asTimestamp(date); } catch (final ParseException ex) { throw new AdempiereException("@Invalid@ @Date@: " + valueStr, ex); } } /** * Return String. - clean ' and backslash - check max length * * @param info data * @return info with in SQL format */ private String parseString(final String info) { if (info == null || info.isEmpty()) { return null; } String retValue = info; // Length restriction if (maxLength > 0 && retValue.length() > maxLength) { retValue = retValue.substring(0, maxLength); } // copy characters (we need to look through anyway) final StringBuilder out = new StringBuilder(retValue.length()); for (int i = 0; i < retValue.length(); i++) { char c = retValue.charAt(i); if (c == '\'') { out.append("''"); } else if (c == '\\') { out.append("\\\\"); } else { out.append(c); } } return out.toString(); } private BigDecimal parseNumber(@Nullable final String valueStr) { if (valueStr == null || valueStr.isEmpty()) { return null; } try { final String numberStringNormalized = normalizeNumberString(valueStr); BigDecimal bd = new BigDecimal(numberStringNormalized); if (divideBy100) { // NOTE: assumed two decimal scale bd = bd.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP); }
return bd; } catch (final NumberFormatException ex) { throw new AdempiereException("@Invalid@ @Number@: " + valueStr, ex); } } private boolean parseYesNo(String valueStr) { return StringUtils.toBoolean(valueStr, false); } private String normalizeNumberString(String info) { if (Check.isEmpty(info, true)) { return "0"; } final boolean hasPoint = info.indexOf('.') != -1; boolean hasComma = info.indexOf(',') != -1; // delete thousands if (hasComma && decimalSeparator.isDot()) { info = info.replace(',', ' '); } if (hasPoint && decimalSeparator.isComma()) { info = info.replace('.', ' '); } hasComma = info.indexOf(',') != -1; // replace decimal if (hasComma && decimalSeparator.isComma()) { info = info.replace(',', '.'); } // remove everything but digits & '.' & '-' char[] charArray = info.toCharArray(); final StringBuilder sb = new StringBuilder(); for (char element : charArray) { if (Character.isDigit(element) || element == '.' || element == '-') { sb.append(element); } } final String numberStringNormalized = sb.toString().trim(); if (numberStringNormalized.isEmpty()) { return "0"; } return numberStringNormalized; } } // ImpFormatFow
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatColumn.java
1
请完成以下Java代码
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) { if (classLoader == null) { return ImportCandidates.class.getClassLoader(); } return classLoader; } private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) { try { return classLoader.getResources(location); } catch (IOException ex) { throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex); } } private static List<String> readCandidateConfigurations(URL url) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) { List<String> candidates = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { line = stripComment(line); line = line.trim(); if (line.isEmpty()) { continue; } candidates.add(line);
} return candidates; } catch (IOException ex) { throw new IllegalArgumentException("Unable to load configurations from location [" + url + "]", ex); } } private static String stripComment(String line) { int commentStart = line.indexOf(COMMENT_START); if (commentStart == -1) { return line; } return line.substring(0, commentStart); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\ImportCandidates.java
1
请在Spring Boot框架中完成以下Java代码
public Duration determineTimeout(Supplier<Duration> fallbackTimeout) { return (this.timeout != null) ? this.timeout : fallbackTimeout.get(); } /** * Servlet-related properties. */ public static class Servlet { /** * Session repository filter order. */ private int filterOrder = SessionRepositoryFilter.DEFAULT_ORDER; /** * Session repository filter dispatcher types. */ private Set<DispatcherType> filterDispatcherTypes = new HashSet<>( Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST));
public int getFilterOrder() { return this.filterOrder; } public void setFilterOrder(int filterOrder) { this.filterOrder = filterOrder; } public Set<DispatcherType> getFilterDispatcherTypes() { return this.filterDispatcherTypes; } public void setFilterDispatcherTypes(Set<DispatcherType> filterDispatcherTypes) { this.filterDispatcherTypes = filterDispatcherTypes; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionProperties.java
2
请完成以下Java代码
public void reset() { priceToReturn = priceToReturnInitial; productId2price.clear(); } public void setC_UOM(final I_M_Product product, final I_C_UOM uom) { productId2priceUOM.put(ProductId.ofRepoId(product.getM_Product_ID()), uom); } public void setPrecision(CurrencyPrecision precision) { this.precision = precision; } public void setProductPrice(final I_M_Product product, final BigDecimal price) { productId2price.put(ProductId.ofRepoId(product.getM_Product_ID()), price); } @Override public boolean applies(IPricingContext pricingCtx, IPricingResult result) { return true; } @Override public void calculate(IPricingContext pricingCtx, IPricingResult result) { // // Check product price final ProductId productId = pricingCtx.getProductId(); BigDecimal price = productId2price.get(productId); if (price == null) {
price = priceToReturn; } result.setPriceLimit(price); result.setPriceList(price); result.setPriceStd(price); result.setPrecision(precision); result.setTaxCategoryId(TaxCategoryId.ofRepoId(100)); final I_C_UOM priceUOM = productId2priceUOM.get(productId); if (priceUOM != null) { result.setPriceUomId(UomId.ofRepoId(priceUOM.getC_UOM_ID())); } result.setCalculated(true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\MockedPricingRule.java
1
请完成以下Java代码
public MobileAppBundle findMobileAppBundleByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) { log.trace("Executing findMobileAppBundleByPkgNameAndPlatform, tenantId [{}], pkgName [{}], platform [{}]", tenantId, pkgName, platform); checkNotNull(platform, PLATFORM_TYPE_IS_REQUIRED); return mobileAppBundleDao.findByPkgNameAndPlatform(tenantId, pkgName, platform); } @Override public void deleteMobileAppBundleById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) { log.trace("Executing deleteMobileAppBundleById [{}]", mobileAppBundleId.getId()); mobileAppBundleDao.removeById(tenantId, mobileAppBundleId.getId()); eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(mobileAppBundleId).build()); } @Override public void deleteByTenantId(TenantId tenantId) { log.trace("Executing deleteMobileAppsByTenantId, tenantId [{}]", tenantId); mobileAppBundleDao.deleteByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findMobileAppBundleById(tenantId, new MobileAppBundleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(mobileAppBundleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteMobileAppBundleById(tenantId, (MobileAppBundleId) id); }
@Override public EntityType getEntityType() { return EntityType.MOBILE_APP_BUNDLE; } private void fetchOauth2Clients(MobileAppBundleInfo mobileAppBundleInfo) { List<OAuth2ClientInfo> clients = oauth2ClientDao.findByMobileAppBundleId(mobileAppBundleInfo.getUuidId()).stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); mobileAppBundleInfo.setOauth2ClientInfos(clients); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppBundleServiceImpl.java
1
请完成以下Java代码
public boolean seeksAfterHandling() { // We don't actually do any seeks here, but stopping the container has the same effect. return true; } @Override public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer, MessageListenerContainer container, boolean batchListener) { stopContainer(container, thrownException); } @Override public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, MessageListenerContainer container) { stopContainer(container, thrownException); } @Override public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { stopContainer(container, thrownException); }
private void stopContainer(MessageListenerContainer container, Exception thrownException) { this.executor.execute(() -> { if (this.stopContainerAbnormally) { container.stopAbnormally(() -> { }); } else { container.stop(() -> { }); } }); // isRunning is false before the container.stop() waits for listener thread try { ListenerUtils.stoppableSleep(container, 10_000); // NOSONAR } catch (InterruptedException e) { Thread.currentThread().interrupt(); } throw new KafkaException("Stopped container", getLogLevel(), thrownException); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonContainerStoppingErrorHandler.java
1
请完成以下Java代码
public String getTextValue2() { return node.path("textValues").stringValue(null); } @Override public void setTextValue2(String textValue2) { throw new UnsupportedOperationException("Not supported to set text value2"); } @Override public Long getLongValue() { JsonNode longNode = node.path("longValue"); if (longNode.isNumber()) { return longNode.longValue(); } return null; } @Override public void setLongValue(Long longValue) { throw new UnsupportedOperationException("Not supported to set long value"); } @Override public Double getDoubleValue() { JsonNode doubleNode = node.path("doubleValue"); if (doubleNode.isNumber()) { return doubleNode.doubleValue(); } return null; } @Override public void setDoubleValue(Double doubleValue) { throw new UnsupportedOperationException("Not supported to set double value");
} @Override public byte[] getBytes() { throw new UnsupportedOperationException("Not supported to get bytes"); } @Override public void setBytes(byte[] bytes) { throw new UnsupportedOperationException("Not supported to set bytes"); } @Override public Object getCachedValue() { throw new UnsupportedOperationException("Not supported to set get cached value"); } @Override public void setCachedValue(Object cachedValue) { throw new UnsupportedOperationException("Not supported to set cached value"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java
1
请完成以下Java代码
public String toString() { return "-"; } @Override public @NonNull String getColumnSql(@NonNull String columnName) { return columnName; } /** * @return Column Name if value is {@link ModelColumnNameValue} or "?" else. */ @Override public String getValueSql(Object value, List<Object> params) {
if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; return modelValue.getColumnName(); } params.add(value); return "?"; } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable Object value, final @Nullable Object model) { return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\NullQueryFilterModifier.java
1
请在Spring Boot框架中完成以下Java代码
public JsonExternalSystemLeichMehlConfigProductMapping getProductMapping(@NonNull final Map<String, String> params) { final String productMapping = params.get(ExternalSystemConstants.PARAM_CONFIG_MAPPINGS); if (Check.isBlank(productMapping)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_CONFIG_MAPPINGS); } final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); try { return mapper.readValue(productMapping, JsonExternalSystemLeichMehlConfigProductMapping.class); } catch (final JsonProcessingException e) { throw new RuntimeException(e); } } @NonNull public JsonExternalSystemLeichMehlPluFileConfigs getPluFileConfigs(@NonNull final Map<String, String> params) { final String pluFileConfigs = params.get(ExternalSystemConstants.PARAM_PLU_FILE_CONFIG); if (Check.isBlank(pluFileConfigs)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_PLU_FILE_CONFIG); } final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); try { return mapper.readValue(pluFileConfigs, JsonExternalSystemLeichMehlPluFileConfigs.class); } catch (final JsonProcessingException e) { throw new RuntimeException(e); }
} @NonNull public Predicate isStoreFileOnDisk() { return exchange -> { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); return context.getDestinationDetails().isStoreFileOnDisk(); }; } @NonNull public Predicate isPluFileExportAuditEnabled() { return exchange -> { final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class); return context.isPluFileExportAuditEnabled(); }; } public static Integer getPPOrderMetasfreshId(@NonNull final Map<String, String> parameters) { final String ppOrderStr = parameters.get(ExternalSystemConstants.PARAM_PP_ORDER_ID); if (Check.isBlank(ppOrderStr)) { throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_PP_ORDER_ID); } try { return Integer.parseInt(ppOrderStr); } catch (final NumberFormatException e) { throw new RuntimeException("Unable to parse PP_Order_ID from string=" + ppOrderStr); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderHelper.java
2
请完成以下Java代码
public class PostStream { public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain"); final String postBody = "Hello World"; RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return MEDIA_TYPE_TEXT; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.writeUtf8(postBody); } @Override public long contentLength() throws IOException { return postBody.length(); }
}; Request request = new Request.Builder() .url("http://www.baidu.com") .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("服务器端错误: " + response); } System.out.println(response.body().string()); } }
repos\spring-boot-quick-master\quick-okhttp\src\main\java\com\quick\okhttp\PostStream.java
1
请完成以下Java代码
public void setBinaryData(@NonNull final I_AD_Archive archive, @NonNull final byte[] uncompressedData) { if (uncompressedData.length == 0) { throw new AdempiereException("uncompressedData may not be empty") .appendParametersToMessage() .setParameter("AD_Archive", archive); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(out); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(Deflater.BEST_COMPRESSION); zip.setComment("adempiere"); // byte[] compressedData = null; try { final ZipEntry entry = new ZipEntry("AdempiereArchive"); entry.setTime(System.currentTimeMillis()); entry.setMethod(ZipEntry.DEFLATED); zip.putNextEntry(entry); zip.write(uncompressedData, 0, uncompressedData.length); zip.closeEntry();
logger.debug(entry.getCompressedSize() + " (" + entry.getSize() + ") " + (entry.getCompressedSize() * 100 / entry.getSize()) + "%"); // // zip.finish(); zip.close(); compressedData = out.toByteArray(); logger.debug("Length=" + uncompressedData.length); // m_deflated = new Integer(compressedData.length); } catch (Exception e) { // log.error("saveLOBData", e); // compressedData = null; // m_deflated = null; throw AdempiereException.wrapIfNeeded(e); } archive.setBinaryData(compressedData); archive.setIsFileSystem(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\spi\impl\DBArchiveStorage.java
1
请完成以下Java代码
public void registerApplier(@NonNull final ValRuleAutoApplier valRuleAutoApplier) { tableName2Applier.put(valRuleAutoApplier.getTableName(), valRuleAutoApplier); } public void invokeApplierFor(@NonNull final Object recordModel) { final String tableName = InterfaceWrapperHelper.getModelTableName(recordModel); final ValRuleAutoApplier applier = tableName2Applier.get(tableName); if (applier == null) { return; // no applier registered; nothing to do } try { applier.handleRecord(recordModel);
} catch (final RuntimeException e) { throw AdempiereException.wrapIfNeeded(e) .appendParametersToMessage() .setParameter("valRuleAutoApplier", applier) .setParameter("recordModel", recordModel); } } public void unregisterForTableName(@NonNull final String tableName) { tableName2Applier.remove(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\ValRuleAutoApplierService.java
1
请完成以下Java代码
public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory) { set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory); } @Override public boolean isExcludeProductCategory() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); } @Override public BigDecimal getPercentOfBasePoints()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
1
请完成以下Java代码
public void remove() { this.i.remove(); } }; } @Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); }
@Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请完成以下Java代码
public int getM_AttributeSetExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_AttributeSet getM_AttributeSet() throws RuntimeException { return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name) .getPO(getM_AttributeSet_ID(), get_TrxName()); } /** Set Attribute Set. @param M_AttributeSet_ID Product Attribute Set */ public void setM_AttributeSet_ID (int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID)); } /** Get Attribute Set. @return Product Attribute Set */ public int getM_AttributeSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_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_M_AttributeSetExclude.java
1
请在Spring Boot框架中完成以下Java代码
public void removeMobileSession(@RequestHeader(MOBILE_TOKEN_HEADER) String mobileToken, @AuthenticationPrincipal SecurityUser user) { userService.removeMobileSession(user.getTenantId(), mobileToken); } @ApiOperation(value = "Get Users By Ids (getUsersByIds)", notes = "Requested users must be owned by tenant or assigned to customer which user is performing the request. ") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @GetMapping(value = "/users", params = {"userIds"}) public List<User> getUsersByIds( @Parameter(description = "A list of user ids, separated by comma ','", array = @ArraySchema(schema = @Schema(type = "string")), required = true) @RequestParam("userIds") Set<UUID> userUUIDs) throws ThingsboardException { TenantId tenantId = getCurrentUser().getTenantId(); List<UserId> userIds = new ArrayList<>(); for (UUID userUUID : userUUIDs) { userIds.add(new UserId(userUUID)); } List<User> users = userService.findUsersByTenantIdAndIds(tenantId, userIds); return filterUsersByReadPermission(users);
} private List<User> filterUsersByReadPermission(List<User> users) { return users.stream().filter(user -> { try { return accessControlService.hasPermission(getCurrentUser(), Resource.USER, Operation.READ, user.getId(), user); } catch (ThingsboardException e) { return false; } }).collect(Collectors.toList()); } private void checkNotReserved(String strType, UserSettingsType type) throws ThingsboardException { if (type.isReserved()) { throw new ThingsboardException("Settings with type: " + strType + " are reserved for internal use!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\UserController.java
2
请完成以下Java代码
public void setIsOfferQty (boolean IsOfferQty) { set_Value (COLUMNNAME_IsOfferQty, Boolean.valueOf(IsOfferQty)); } /** Get Offer Quantity. @return This quantity is used in the Offer to the Customer */ @Override public boolean isOfferQty () { Object oo = get_Value(COLUMNNAME_IsOfferQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Purchase Quantity. @param IsPurchaseQty This quantity is used in the Purchase Order to the Supplier */ @Override public void setIsPurchaseQty (boolean IsPurchaseQty) { set_Value (COLUMNNAME_IsPurchaseQty, Boolean.valueOf(IsPurchaseQty)); } /** Get Purchase Quantity. @return This quantity is used in the Purchase Order to the Supplier */ @Override public boolean isPurchaseQty () { Object oo = get_Value(COLUMNNAME_IsPurchaseQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set RfQ Quantity. @param IsRfQQty The quantity is used when generating RfQ Responses */ @Override public void setIsRfQQty (boolean IsRfQQty) { set_Value (COLUMNNAME_IsRfQQty, Boolean.valueOf(IsRfQQty)); } /** Get RfQ Quantity. @return The quantity is used when generating RfQ Responses */ @Override public boolean isRfQQty () { Object oo = get_Value(COLUMNNAME_IsRfQQty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Margin %. @param Margin Margin for a product as a percentage */ @Override public void setMargin (java.math.BigDecimal Margin) { set_Value (COLUMNNAME_Margin, Margin); } /** Get Margin %. @return Margin for a product as a percentage
*/ @Override public java.math.BigDecimal getMargin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Offer Amount. @param OfferAmt Amount of the Offer */ @Override public void setOfferAmt (java.math.BigDecimal OfferAmt) { set_Value (COLUMNNAME_OfferAmt, OfferAmt); } /** Get Offer Amount. @return Amount of the Offer */ @Override public java.math.BigDecimal getOfferAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Menge. @param Qty Quantity */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Quantity */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java
1
请完成以下Java代码
public void setLineNo (int LineNo) { set_Value (COLUMNNAME_LineNo, Integer.valueOf(LineNo)); } /** Get Position. @return Zeile Nr. */ @Override public int getLineNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LineNo); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override
public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_C_Customs_Invoice_Line.java
1
请在Spring Boot框架中完成以下Java代码
class PhotoService { private final RuntimeService runtimeService; private final TaskService taskService; private final PhotoRepository photoRepository; @Autowired public PhotoService(RuntimeService runtimeService, TaskService taskService, PhotoRepository photoRepository) { this.runtimeService = runtimeService; this.taskService = taskService; this.photoRepository = photoRepository; } public void processPhoto(Long photoId) { System.out.println("processing photo#" + photoId); } public void launchPhotoProcess(String... photoLabels) { List<Photo> photos = new ArrayList<>(); for (String l : photoLabels) { Photo x = this.photoRepository.save(new Photo(l)); photos.add(x); } Map<String, Object> procVars = new HashMap<>(); procVars.put("photos", photos); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dogeProcess", procVars); List<Execution> waitingExecutions = runtimeService.createExecutionQuery().activityId("wait").list(); System.out.println("--> # executions = " + waitingExecutions.size()); for (Execution execution : waitingExecutions) { runtimeService.trigger(execution.getId()); } Task reviewTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(reviewTask.getId(), Collections.singletonMap("approved", (Object) true)); long count = runtimeService.createProcessInstanceQuery().count(); System.out.println("Proc count " + count); } } interface PhotoRepository extends JpaRepository<Photo, Long> { }
@Entity class Photo { @Id @GeneratedValue private Long id; Photo() { } Photo(String username) { this.username = username; } private String username; public Long getId() { return id; } public String getUsername() { return username; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-jpa\src\main\java\flowable\Application.java
2
请完成以下Java代码
protected final ProductsToPickView getView() { return ProductsToPickView.cast(super.getView()); } protected final List<ProductsToPickRow> getSelectedRows() { final DocumentIdsSelection rowIds = getSelectedRowIds(); return getView() .streamByIds(rowIds) .collect(ImmutableList.toImmutableList()); } protected final List<ProductsToPickRow> getAllRows() { return streamAllRows() .collect(ImmutableList.toImmutableList()); }
protected Stream<ProductsToPickRow> streamAllRows() { return getView() .streamByIds(DocumentIdsSelection.ALL); } protected void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate) { getView().updateViewRowFromPickingCandidate(rowId, pickingCandidate); } protected void updateViewRowFromPickingCandidate(@NonNull final ImmutableList<WebuiPickHUResult> pickHUResults) { pickHUResults.forEach(r -> updateViewRowFromPickingCandidate(r.getDocumentId(), r.getPickingCandidate())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPickViewBasedProcess.java
1
请完成以下Java代码
public String getCaseExecutionId() { return caseExecutionId; } public String getCaseInstanceId() { return caseInstanceId; } public String getTenantId() { return tenantId; } public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) { VariableInstanceDto dto = new VariableInstanceDto(); dto.id = variableInstance.getId(); dto.name = variableInstance.getName(); dto.processDefinitionId = variableInstance.getProcessDefinitionId(); dto.processInstanceId = variableInstance.getProcessInstanceId(); dto.executionId = variableInstance.getExecutionId(); dto.caseExecutionId = variableInstance.getCaseExecutionId(); dto.caseInstanceId = variableInstance.getCaseInstanceId();
dto.taskId = variableInstance.getTaskId(); dto.batchId = variableInstance.getBatchId(); dto.activityInstanceId = variableInstance.getActivityInstanceId(); dto.tenantId = variableInstance.getTenantId(); if(variableInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue()); } else { dto.errorMessage = variableInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableInstanceDto.java
1
请完成以下Java代码
public String exampleOfIF(String animal) { String result; if (animal.equals("DOG") || animal.equals("CAT")) { result = "domestic animal"; } else if (animal.equals("TIGER")) { result = "wild animal"; } else { result = "unknown animal"; } return result; } public String exampleOfSwitch(String animal) { String result; switch (animal) { case "DOG": case "CAT": result = "domestic animal"; break; case "TIGER": result = "wild animal"; break; default: result = "unknown animal"; break; } return result; } public String forgetBreakInSwitch(String animal) {
String result; switch (animal) { case "DOG": LOGGER.debug("domestic animal"); result = "domestic animal"; default: LOGGER.debug("unknown animal"); result = "unknown animal"; } return result; } public String constantCaseValue(String animal) { String result = ""; final String dog = "DOG"; switch (animal) { case dog: result = "domestic animal"; } return result; } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\switchstatement\SwitchStatement.java
1
请在Spring Boot框架中完成以下Java代码
public String getSubScopeId() { return subScopeId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getScopeDefinitionKey() { return scopeDefinitionKey;
} @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String getConfiguration() { return configuration; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionBuilderImpl.java
2
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容,对应 DataSourceProperties 配置属性类 datasource: url: jdbc:mysql://127.0.0.1:3306/lab-20-flyway?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root # 数据库账号 password: # 数据库密码 # flyway 配置内容,对应 FlywayAutoConfiguration.FlywayConfiguration 配置项 flyway: enabled: true # 开启 Flyway 功能 cleanDisabled: true # 禁用 Flyway 所有的 drop 相关的逻辑,避免出现跑路的情况。 locations: # 迁移脚本目录 - classpath:db/migration # 配置 SQL-based 的 SQL 脚本在该目录下 - classpath:cn.iocoder.springboot.lab20.databaseversioncontrol.migration # 配置 Java-based 的 Ja
va 文件在该目录下 check-location: false # 是否校验迁移脚本目录下。如果配置为 true ,代表需要校验。此时,如果目录下没有迁移脚本,会抛出 IllegalStateException 异常 url: jdbc:mysql://127.0.0.1:3306/lab-20-flyway?useSSL=false&useUnicode=true&characterEncoding=UTF-8 # 数据库地址 user: root # 数据库账号 password: # 数据库密码
repos\SpringBoot-Labs-master\lab-20\lab-20-database-version-control-flyway\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class CatalogueController { @Autowired private GoodsRepository goodsRepository; @Autowired private UserRepository userRepository; @Autowired private RetailerRepository retailerRepository; @Autowired private CataloguesService cataloguesService; @GetMapping("/getCataloguesOfGoods") public PagedResponse<GoodResponseForRetailer> getCatalogueOfGoods( @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page, @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size, @RequestParam(defaultValue = "updatedAt") String sortBy, @RequestParam(defaultValue = "descend") String sortOrder) { return cataloguesService.getCatalogueOfGoods(page, size, sortBy, sortOrder); }
@GetMapping("/getGoodById") public Good getGoodById(@RequestParam(value = "goodId") String goodId){ return goodsRepository.findGoodById(Long.valueOf(goodId)); } @GetMapping("/getGoodsByRetailers") public PagedResponse<GoodResponseForRetailer> getGoodsByRetailers ( @CurrentUser UserPrincipal userPrincipal, @RequestParam(value = "retailersId") Long id, @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page, @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size, @RequestParam(defaultValue = "updatedAt") String sortBy, @RequestParam(defaultValue = "descend") String sortOrder, @RequestParam String filteredValue) { return cataloguesService.getGoodsByRetailers(userPrincipal, id, page, size, sortBy, sortOrder, filteredValue); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\CatalogueController.java
2
请完成以下Java代码
public Optional<IDocumentBillLocationAdapter> getDocumentBillLocationAdapterIfHandled(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::billLocationAdapter); } @Override public Optional<IDocumentDeliveryLocationAdapter> getDocumentDeliveryLocationAdapter(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::deliveryLocationAdapter); } @Override public Optional<IDocumentHandOverLocationAdapter> getDocumentHandOverLocationAdapter(final Object record) { return toOrder(record).map(OrderDocumentLocationAdapterFactory::handOverLocationAdapter); } private static Optional<I_C_Order> toOrder(final Object record) { return InterfaceWrapperHelper.isInstanceOf(record, I_C_Order.class) ? Optional.of(InterfaceWrapperHelper.create(record, I_C_Order.class)) : Optional.empty(); }
public static OrderMainLocationAdapter locationAdapter(@NonNull final I_C_Order delegate) { return new OrderMainLocationAdapter(delegate); } public static OrderBillLocationAdapter billLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderBillLocationAdapter(delegate); } public static OrderDropShipLocationAdapter deliveryLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderDropShipLocationAdapter(delegate); } public static OrderHandOverLocationAdapter handOverLocationAdapter(@NonNull final I_C_Order delegate) { return new OrderHandOverLocationAdapter(delegate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderDocumentLocationAdapterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class AutoConfigurationImportEvent extends EventObject { private final List<String> candidateConfigurations; private final Set<String> exclusions; public AutoConfigurationImportEvent(Object source, List<String> candidateConfigurations, Set<String> exclusions) { super(source); this.candidateConfigurations = Collections.unmodifiableList(candidateConfigurations); this.exclusions = Collections.unmodifiableSet(exclusions); } /** * Return the auto-configuration candidate configurations that are going to be * imported.
* @return the auto-configuration candidates */ public List<String> getCandidateConfigurations() { return this.candidateConfigurations; } /** * Return the exclusions that were applied. * @return the exclusions applied */ public Set<String> getExclusions() { return this.exclusions; } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationImportEvent.java
2
请完成以下Java代码
public Integer getPort() { return port; } public AbstractRuleEntity<T> setPort(Integer port) { this.port = port; return this; } public T getRule() { return rule; } public AbstractRuleEntity<T> setRule(T rule) { this.rule = rule; return this; } @Override public Date getGmtCreate() { return gmtCreate; } public AbstractRuleEntity<T> setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; return this;
} public Date getGmtModified() { return gmtModified; } public AbstractRuleEntity<T> setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; return this; } @Override public T toRule() { return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\AbstractRuleEntity.java
1
请完成以下Java代码
public String getSummary() { return getDocumentInfo(); } @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getCreated()); } @Override public boolean invalidateIt() { log.info(toString()); setDocAction(DOCACTION_Prepare); return true; } // invalidateIt /** * Prepare Document * * @return new status (In Progress or Invalid) */ @Override public String prepareIt() { log.info(toString()); m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_PREPARE); if (m_processMsg != null) return IDocument.STATUS_Invalid; m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_PREPARE); if (m_processMsg != null) return IDocument.STATUS_Invalid; // m_justPrepared = true; if (!DOCACTION_Complete.equals(getDocAction())) setDocAction(DOCACTION_Complete); return IDocument.STATUS_InProgress; } // prepareIt @Override public boolean processIt(final String processAction) { m_processMsg = null; return Services.get(IDocumentBL.class).processIt(this, processAction); } @Override public boolean reActivateIt() { log.info(toString()); // Before reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE); if (m_processMsg != null) return false; setProcessed(false); setDocAction(DOCACTION_Complete); // After reActivate m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE); if (m_processMsg != null) return false; return true; } // reActivateIt @Override public boolean rejectIt() { return true; } @Override public boolean reverseAccrualIt() { log.info(toString()); // Before reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; // After reverseAccrual m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return true;
} // reverseAccrualIt @Override public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return true; } /** * Unlock Document. * * @return true if success */ @Override public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt @Override public boolean voidIt() { return false; } @Override public int getC_Currency_ID() { return 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateConditions.java
1
请完成以下Java代码
default IAllocationRequestBuilder setQuantity(final BigDecimal qty, final I_C_UOM uom) { setQuantity(Quantity.of(qty, uom)); return this; } IAllocationRequestBuilder setDate(final ZonedDateTime date); IAllocationRequestBuilder setDateAsToday(); /** * @param forceQtyAllocation if null, the actual value will be fetched from base allocation request (if any) * @return this */ IAllocationRequestBuilder setForceQtyAllocation(final Boolean forceQtyAllocation); /** * Sets referenced model to be set to {@link IAllocationRequest} which will be created. * * @param referenceModel model, {@link ITableRecordReference} or null * @return this */ IAllocationRequestBuilder setFromReferencedModel(@Nullable Object referenceModel); /** * Sets referenced model to be set to {@link IAllocationRequest} which will be created.
* * @param fromReferencedTableRecord {@link ITableRecordReference} or null * @return this */ IAllocationRequestBuilder setFromReferencedTableRecord(@Nullable TableRecordReference fromReferencedTableRecord); IAllocationRequestBuilder addEmptyHUListener(EmptyHUListener emptyHUListener); IAllocationRequestBuilder setClearanceStatusInfo(@Nullable ClearanceStatusInfo clearanceStatusInfo); @Nullable ClearanceStatusInfo getClearanceStatusInfo(); IAllocationRequestBuilder setDeleteEmptyAndJustCreatedAggregatedTUs(@Nullable Boolean deleteEmptyAndJustCreatedAggregatedTUs); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\IAllocationRequestBuilder.java
1
请完成以下Java代码
public void start(Properties ctx, IReplicationProcessor replicationProcessor, String trxName) throws Exception { final I_IMP_Processor impProcessor = replicationProcessor.getMImportProcessor(); final List<I_IMP_ProcessorParameter> processorParameters = Services.get(IIMPProcessorDAO.class).retrieveParameters(impProcessor, trxName); String fileName = null; String folder = ""; for (final I_IMP_ProcessorParameter processorParameter : processorParameters) { log.info("ProcesParameter Value = " + processorParameter.getValue()); log.info("ProcesParameter ParameterValue = " + processorParameter.getParameterValue()); if (processorParameter.getValue().equals("fileName")) { fileName = processorParameter.getParameterValue(); } else if (processorParameter.getValue().equals("folder")) { folder = processorParameter.getParameterValue(); } } if (fileName == null || fileName.length() == 0) { throw new Exception("Missing IMP_ProcessorParameter with key 'fileName'!"); } Document documentToBeImported = XMLHelper.createDocumentFromFile(folder + fileName); StringBuilder result = new StringBuilder(); final IImportHelper impHelper = Services.get(IIMPProcessorBL.class).createImportHelper(ctx); impHelper.importXMLDocument(result, documentToBeImported, trxName );
// addLog(0, null, null, Msg.getMsg(ctx, "ImportModelProcessResult") + "\n" + result.toString()); } public void stop() throws Exception { // do nothing! } @Override public void createInitialParameters(I_IMP_Processor processor) { final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class); impProcessorBL.createParameter(processor, "fileName", "Name of file from where xml will be imported", "Import Processor Parameter Description", "HDD Import Processor Parameter Help", "C_Order"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\server\rpl\imp\FileImportProcessor.java
1
请完成以下Java代码
public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } @Override public String getCaseDefinitionKey() { return caseDefinitionKey; } @Override public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } @Override public String getCaseDefinitionName() { return caseDefinitionName; } @Override public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName; } @Override public Integer getCaseDefinitionVersion() { return caseDefinitionVersion; }
@Override public void setCaseDefinitionVersion(Integer caseDefinitionVersion) { this.caseDefinitionVersion = caseDefinitionVersion; } @Override public String getCaseDefinitionDeploymentId() { return caseDefinitionDeploymentId; } @Override public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) { this.caseDefinitionDeploymentId = caseDefinitionDeploymentId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("CaseInstance[id=").append(id) .append(", caseDefinitionId=").append(caseDefinitionId) .append(", caseDefinitionKey=").append(caseDefinitionKey) .append(", parentId=").append(parentId) .append(", name=").append(name); if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseInstanceEntityImpl.java
1
请完成以下Java代码
public class GlobalExceptionHandler { /** * 处理所有不可知的异常 */ @ExceptionHandler(Throwable.class) public ResponseEntity<ApiError> handleException(Throwable e){ // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getMessage())); } /** * BadCredentialsException */ @ExceptionHandler(BadCredentialsException.class) public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){ // 打印堆栈信息 String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage(); log.error(message); return buildResponseEntity(ApiError.error(message)); } /** * 处理自定义异常 */ @ExceptionHandler(value = BadRequestException.class) public ResponseEntity<ApiError> badRequestException(BadRequestException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage())); } /** * 处理 EntityExist */ @ExceptionHandler(value = EntityExistException.class) public ResponseEntity<ApiError> entityExistException(EntityExistException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getMessage())); }
/** * 处理 EntityNotFound */ @ExceptionHandler(value = EntityNotFoundException.class) public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage())); } /** * 处理所有接口数据验证异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); ObjectError objectError = e.getBindingResult().getAllErrors().get(0); String message = objectError.getDefaultMessage(); if (objectError instanceof FieldError) { message = ((FieldError) objectError).getField() + ": " + message; } return buildResponseEntity(ApiError.error(message)); } /** * 统一返回 */ private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) { return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\exception\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
private CreateProductTaxCategoryRequest getCreateProductTaxCategoryRequest( @NonNull final JsonRequestProductTaxCategoryUpsert jsonRequestProductTaxCategoryUpsert, @NonNull final ProductId productId, @NonNull final CountryId countryId) { final TaxCategoryId taxCategoryId = Optional.ofNullable(jsonRequestProductTaxCategoryUpsert.getTaxCategory()) .map(taxCategoryInternalName -> productPriceRestService.getTaxCategoryId(TaxCategory.ofInternalName(taxCategoryInternalName))) .orElseThrow(() -> new MissingPropertyException("taxCategory", jsonRequestProductTaxCategoryUpsert)); return CreateProductTaxCategoryRequest.builder() .productId(productId) .taxCategoryId(taxCategoryId) .validFrom(jsonRequestProductTaxCategoryUpsert.getValidFrom()) .countryId(countryId) .active(Optional.ofNullable(jsonRequestProductTaxCategoryUpsert.getActive()).orElse(true)) .build(); } @NonNull private String getType(final @NonNull JsonRequestProduct jsonRequestProductUpsertItem) { final String productType; switch (jsonRequestProductUpsertItem.getType()) {
case SERVICE: productType = X_M_Product.PRODUCTTYPE_Service; break; case ITEM: productType = X_M_Product.PRODUCTTYPE_Item; break; default: throw Check.fail("Unexpected type={}; jsonRequestProductUpsertItem={}", jsonRequestProductUpsertItem.getType(), jsonRequestProductUpsertItem); } return productType; } private static void validateJsonRequestProductTaxCategoryUpsert(@NonNull final JsonRequestProductTaxCategoryUpsert jsonRequestProductTaxCategoryUpsert) { if (jsonRequestProductTaxCategoryUpsert.getCountryCode() == null) { throw new MissingPropertyException("countryCode", jsonRequestProductTaxCategoryUpsert); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductRestService.java
1
请完成以下Java代码
public class User { private String name; private String surname; private String emailAddress; public User(String name, String surname, String emailAddress) { this.name = name; this.surname = surname; this.emailAddress = emailAddress; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
repos\tutorials-master\spring-boot-modules\spring-boot-aws\src\main\java\com\baeldung\aws\data\User.java
1
请完成以下Java代码
/* package */final class ModelContextAware implements IContextAware { private final Object model; public ModelContextAware(final Object model) { // we allow null values because we want that InterfaceWrapperHelper.getContextAware // ... to not return null for nulls // Check.assumeNotNull(model, "model not null"); this.model = model; } @Override public Properties getCtx() {
return InterfaceWrapperHelper.getCtx(model); } public Properties getCtx(boolean useClientOrgFromModel) { return InterfaceWrapperHelper.getCtx(model, useClientOrgFromModel); } @Override public String getTrxName() { return InterfaceWrapperHelper.getTrxName(model); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\ModelContextAware.java
1
请在Spring Boot框架中完成以下Java代码
public String getOrderTime() { return orderTime; } public void setOrderTime(String orderTime) { this.orderTime = orderTime; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public String getAuthCode() { return authCode; } public void setAuthCode(String authCode) { this.authCode = authCode; }
@Override public String toString() { return "F2FPayRequestBo{" + "payKey='" + payKey + '\'' + ", authCode='" + authCode + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\F2FPayRequestBo.java
2
请完成以下Java代码
public class ListenerContainerNoLongerIdleEvent extends KafkaEvent { private static final long serialVersionUID = 1L; private final long idleTime; private final String listenerId; private transient final @Nullable List<TopicPartition> topicPartitions; private transient final @Nullable Consumer<?, ?> consumer; /** * Construct an instance with the provided arguments. * @param source the container instance that generated the event. * @param container the container or the parent container if the container is a child. * @param idleTime how long the container was idle. * @param id the container id. * @param topicPartitions the topics/partitions currently assigned. * @param consumer the consumer. */ public ListenerContainerNoLongerIdleEvent(Object source, Object container, long idleTime, String id, @Nullable Collection<TopicPartition> topicPartitions, Consumer<?, ?> consumer) { super(source, container); this.idleTime = idleTime; this.listenerId = id; this.topicPartitions = topicPartitions == null ? null : new ArrayList<>(topicPartitions); this.consumer = consumer; } /** * The TopicPartitions the container is listening to. * @return the TopicPartition list. */ public @Nullable Collection<TopicPartition> getTopicPartitions() { return this.topicPartitions == null ? null : Collections.unmodifiableList(this.topicPartitions);
} /** * How long the container was idle. * @return the time in milliseconds. */ public long getIdleTime() { return this.idleTime; } /** * The id of the listener (if {@code @KafkaListener}) or the container bean name. * @return the id. */ public String getListenerId() { return this.listenerId; } /** * Retrieve the consumer. Only populated if the listener is consumer-aware. * Allows the listener to resume a paused consumer. * @return the consumer. */ public @Nullable Consumer<?, ?> getConsumer() { return this.consumer; } @Override public String toString() { return "ListenerContainerNoLongerIdleEvent [idleTime=" + ((float) this.idleTime / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic # + ", container=" + getSource() + ", topicPartitions=" + this.topicPartitions + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ListenerContainerNoLongerIdleEvent.java
1
请完成以下Java代码
public void setErrorMsg (final @Nullable java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return get_ValueAsString(COLUMNNAME_ErrorMsg); } @Override public void setIsProcessing (final boolean IsProcessing) { set_Value (COLUMNNAME_IsProcessing, IsProcessing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_IsProcessing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); }
@Override public void setResult (final int Result) { set_Value (COLUMNNAME_Result, Result); } @Override public int getResult() { return get_ValueAsInt(COLUMNNAME_Result); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
1
请完成以下Java代码
public Properties getCtx() { return m_vo.getCtx(); } public int getAD_Table_ID() { return m_vo.getAD_Table_ID(); } @Override public String getTableName() { final int adTableId = getAD_Table_ID(); return adTableId <= 0 ? null : Services.get(IADTableDAO.class).retrieveTableName(adTableId); } @Override public ICalloutExecutor getCurrentCalloutExecutor() { final GridTab gridTab = getGridTab(); if (gridTab == null) { return null; } return gridTab.getCalloutExecutor(); } public int getTabNo() { return m_vo.TabNo; } /** * Enable events delaying. * So, from now on, all events will be enqueued instead of directly fired. * Later, when {@link #releaseDelayedEvents()} is called, all enqueued events will be fired. */ public void delayEvents() { m_propertyChangeListeners.blockEvents(); } /** * Fire all enqueued events (if any) and disable events delaying. * * @see #delayEvents(). */ public void releaseDelayedEvents() { m_propertyChangeListeners.releaseEvents(); } @Override public boolean isRecordCopyingMode() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.isDataNewCopy(); } @Override public boolean isRecordCopyingModeIncludingDetails() { final GridTab gridTab = getGridTab(); // If there was no GridTab set for this field, consider as we are not copying the record if (gridTab == null) { return false; } return gridTab.getTableModel().isCopyWithDetails(); } @Override public void fireDataStatusEEvent(final String AD_Message, final String info, final boolean isError) {
final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: AD_Message={}, info={}, isError={}", this, AD_Message, info, isError); return; } gridTab.fireDataStatusEEvent(AD_Message, info, isError); } @Override public void fireDataStatusEEvent(final ValueNamePair errorLog) { final GridTab gridTab = getGridTab(); if(gridTab == null) { log.warn("Could not fire EEvent on {} because gridTab is not set. The event was: errorLog={}", this, errorLog); return; } gridTab.fireDataStatusEEvent(errorLog); } @Override public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { throw new UnsupportedOperationException(); } @Override public ICalloutRecord getCalloutRecord() { final GridTab gridTab = getGridTab(); Check.assumeNotNull(gridTab, "gridTab not null"); return gridTab; } @Override public int getContextAsInt(String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridField.java
1
请完成以下Java代码
public ILoggable addTableRecordReferenceLog(final @NonNull ITableRecordReference recordRef, final @NonNull String type, final @Nullable String trxName) { if (SKIP_LOGGING_FOR_TABLES.contains(recordRef.getTableName())) { return this; } final ApiRequestAuditLog logEntry = createLogEntry(recordRef, type, trxName); addToBuffer(logEntry); return this; } @Override public void flush() { final List<ApiRequestAuditLog> logEntries = buffer; this.buffer = null; if (logEntries == null || logEntries.isEmpty()) { return; } try { apiAuditRequestLogDAO.insertLogs(logEntries); } catch (final Exception ex) { // make sure the flush never fails logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries.size(), logEntries, ex); } } private ApiRequestAuditLog createLogEntry(@NonNull final String msg, final Object... msgParameters) { final LoggableWithThrowableUtil.FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters); return ApiRequestAuditLog.builder() .message(msgAndAdIssueId.getFormattedMessage()) .adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null)) .timestamp(SystemTime.asInstant()) .apiRequestAuditId(apiRequestAuditId) .adClientId(clientId) .userId(userId) .build();
} private ApiRequestAuditLog createLogEntry(final @NonNull ITableRecordReference recordRef, final @NonNull String type, final @Nullable String trxName) { return ApiRequestAuditLog.builder() .timestamp(SystemTime.asInstant()) .apiRequestAuditId(apiRequestAuditId) .adClientId(clientId) .userId(userId) .recordReference(recordRef) .type(StateType.ofCode(type)) .trxName(trxName) .build(); } private void addToBuffer(final ApiRequestAuditLog logEntry) { List<ApiRequestAuditLog> buffer = this.buffer; if (buffer == null) { buffer = this.buffer = new ArrayList<>(bufferSize); } buffer.add(logEntry); if (buffer.size() >= bufferSize) { flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\ApiAuditLoggable.java
1
请完成以下Java代码
public void setTtlChrgsAndTaxAmt(ActiveOrHistoricCurrencyAndAmount value) { this.ttlChrgsAndTaxAmt = value; } /** * Gets the value of the rcrd 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 rcrd property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRcrd().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link ChargesRecord2 } * * */ public List<ChargesRecord2> getRcrd() { if (rcrd == null) { rcrd = new ArrayList<ChargesRecord2>(); } return this.rcrd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Charges4.java
1
请完成以下Java代码
protected String getPlanItemDefinitionXmlElementValue(ProcessTask planItemDefinition) { return ELEMENT_PROCESS_TASK; } @Override protected void writePlanItemDefinitionSpecificAttributes(ProcessTask processTask, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(processTask, xtw); TaskExport.writeCommonTaskAttributes(processTask, xtw); // fallback to default tenant if (processTask.getFallbackToDefaultTenant() != null) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FALLBACK_TO_DEFAULT_TENANT, String.valueOf(processTask.getFallbackToDefaultTenant())); } if (processTask.isSameDeployment()) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_SAME_DEPLOYMENT, String.valueOf(processTask.isSameDeployment())); } if (StringUtils.isNotEmpty(processTask.getProcessInstanceIdVariableName())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_ID_VARIABLE_NAME, processTask.getProcessInstanceIdVariableName()); } }
@Override protected void writePlanItemDefinitionBody(CmmnModel model, ProcessTask processTask, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { super.writePlanItemDefinitionBody(model, processTask, xtw, options); if (StringUtils.isNotEmpty(processTask.getProcessRef()) || StringUtils.isNotEmpty(processTask.getProcessRefExpression())) { xtw.writeStartElement(ELEMENT_PROCESS_REF_EXPRESSION); xtw.writeCData( StringUtils.isNotEmpty(processTask.getProcessRef()) ? processTask.getProcessRef() : processTask.getProcessRefExpression() ); xtw.writeEndElement(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\ProcessTaskExport.java
1
请在Spring Boot框架中完成以下Java代码
private Set<EndpointExposure> getExposures(MergedAnnotation<ConditionalOnAvailableEndpoint> conditionAnnotation) { EndpointExposure[] exposures = conditionAnnotation.getEnumArray("exposure", EndpointExposure.class); return (exposures.length == 0) ? EnumSet.allOf(EndpointExposure.class) : EnumSet.copyOf(Arrays.asList(exposures)); } private Set<EndpointExposureOutcomeContributor> getExposureOutcomeContributors(ConditionContext context) { Environment environment = context.getEnvironment(); Set<EndpointExposureOutcomeContributor> contributors = exposureOutcomeContributorsCache.get(environment); if (contributors == null) { contributors = new LinkedHashSet<>(); contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.WEB)); if (environment.getProperty(JMX_ENABLED_KEY, Boolean.class, false)) { contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.JMX)); } contributors.addAll(loadExposureOutcomeContributors(context.getClassLoader(), environment)); exposureOutcomeContributorsCache.put(environment, contributors); } return contributors; } private List<EndpointExposureOutcomeContributor> loadExposureOutcomeContributors(@Nullable ClassLoader classLoader, Environment environment) { ArgumentResolver argumentResolver = ArgumentResolver.of(Environment.class, environment); return SpringFactoriesLoader.forDefaultResourceLocation(classLoader) .load(EndpointExposureOutcomeContributor.class, argumentResolver); } /** * Standard {@link EndpointExposureOutcomeContributor}.
*/ private static class StandardExposureOutcomeContributor implements EndpointExposureOutcomeContributor { private final EndpointExposure exposure; private final String property; private final IncludeExcludeEndpointFilter<?> filter; StandardExposureOutcomeContributor(Environment environment, EndpointExposure exposure) { this.exposure = exposure; String name = exposure.name().toLowerCase(Locale.ROOT).replace('_', '-'); this.property = "management.endpoints." + name + ".exposure"; this.filter = new IncludeExcludeEndpointFilter<>(ExposableEndpoint.class, environment, this.property, exposure.getDefaultIncludes()); } @Override public @Nullable ConditionOutcome getExposureOutcome(EndpointId endpointId, Set<EndpointExposure> exposures, ConditionMessage.Builder message) { if (exposures.contains(this.exposure) && this.filter.match(endpointId)) { return ConditionOutcome .match(message.because("marked as exposed by a '" + this.property + "' property")); } return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\condition\OnAvailableEndpointCondition.java
2
请完成以下Java代码
public class CasClientController { @Autowired private ISysUserService sysUserService; @Autowired private ISysDepartService sysDepartService; @Autowired private RedisUtil redisUtil; @Value("${cas.prefixUrl}") private String prefixUrl; @GetMapping("/validateLogin") public Object validateLogin(@RequestParam(name="ticket") String ticket, @RequestParam(name="service") String service, HttpServletRequest request, HttpServletResponse response) throws Exception { Result<JSONObject> result = new Result<JSONObject>(); log.info("Rest api login."); try { String validateUrl = prefixUrl+"/p3/serviceValidate"; String res = CasServiceUtil.getStValidate(validateUrl, ticket, service); log.info("res."+res); final String error = XmlUtils.getTextForElement(res, "authenticationFailure"); if(StringUtils.isNotEmpty(error)) { throw new Exception(error); } final String principal = XmlUtils.getTextForElement(res, "user"); if (StringUtils.isEmpty(principal)) { throw new Exception("No principal was found in the response from the CAS server."); } log.info("-------token----username---"+principal); //1. 校验用户是否有效 SysUser sysUser = sysUserService.getUserByName(principal); result = sysUserService.checkUserIsEffective(sysUser);
if(!result.isSuccess()) { return result; } String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword(), CommonConstant.CLIENT_TYPE_PC); // 设置超时时间 redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token); redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000); //获取用户部门信息 JSONObject obj = new JSONObject(); List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId()); obj.put("departs", departs); if (departs == null || departs.size() == 0) { obj.put("multi_depart", 0); } else if (departs.size() == 1) { sysUserService.updateUserDepart(principal, departs.get(0).getOrgCode(),null); obj.put("multi_depart", 1); } else { obj.put("multi_depart", 2); } obj.put("token", token); obj.put("userInfo", sysUser); result.setResult(obj); result.success("登录成功"); } catch (Exception e) { //e.printStackTrace(); result.error500(e.getMessage()); } return new HttpEntity<>(result); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\controller\CasClientController.java
1
请在Spring Boot框架中完成以下Java代码
public static SupplyRequiredDescriptor createSupplyRequiredDescriptor( @NonNull final Candidate demandCandidate, @NonNull final BigDecimal requiredAdditionalQty, @Nullable final CandidateId supplyCandidateId) { final SupplyRequiredDescriptorBuilder descriptorBuilder = createAndInitSupplyRequiredDescriptor( demandCandidate, requiredAdditionalQty); if (supplyCandidateId != null) { descriptorBuilder.supplyCandidateId(supplyCandidateId.getRepoId()); } if (demandCandidate.getDemandDetail() != null) { final DemandDetail demandDetail = demandCandidate.getDemandDetail(); descriptorBuilder .shipmentScheduleId(IdConstants.toRepoId(demandDetail.getShipmentScheduleId())) .forecastId(IdConstants.toRepoId(demandDetail.getForecastId())) .forecastLineId(IdConstants.toRepoId(demandDetail.getForecastLineId())) .orderId(IdConstants.toRepoId(demandDetail.getOrderId())) .orderLineId(IdConstants.toRepoId(demandDetail.getOrderLineId())) .subscriptionProgressId(IdConstants.toRepoId(demandDetail.getSubscriptionProgressId())); } return descriptorBuilder.build();
} @NonNull private static SupplyRequiredDescriptorBuilder createAndInitSupplyRequiredDescriptor( @NonNull final Candidate candidate, @NonNull final BigDecimal qty) { final PPOrderRef ppOrderRef = candidate.getBusinessCaseDetail(ProductionDetail.class) .map(ProductionDetail::getPpOrderRef) .orElse(null); return SupplyRequiredDescriptor.builder() .demandCandidateId(candidate.getId().getRepoId()) .eventDescriptor(EventDescriptor.ofClientOrgAndTraceId(candidate.getClientAndOrgId(), candidate.getTraceId())) .materialDescriptor(candidate.getMaterialDescriptor().withQuantity(qty)) .fullDemandQty(candidate.getQuantity()) .ppOrderRef(ppOrderRef) .simulated(candidate.isSimulated()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\SupplyRequiredEventCreator.java
2
请完成以下Java代码
public boolean addQualityNotice(final String qualityNote) { if (Check.isEmpty(qualityNote, true)) { return false; } return qualityNoticesSet.add(qualityNote.trim()); } public void addQualityNotices(final QualityNoticesCollection notices) { addQualityNotices(notices.qualityNoticesSet); } public void addQualityNotices(final Set<String> notices) { Check.assumeNotNull(notices, "notices not null"); qualityNoticesSet.addAll(notices); } /** * Parses quality notices string (which we assume it was built with {@link #asQualityNoticesString()}) and then adds them to current collection. * * @param qualityNoticesStr */ public void parseAndAddQualityNoticesString(final String qualityNoticesStr) { if (Check.isEmpty(qualityNoticesStr, true)) { return; } String qualityNoticesStrPrepared = qualityNoticesStr.trim(); // If our string ends with our separator (trimmed), we need to take it out because splitter will not detect it if (qualityNoticesStrPrepared.endsWith(SEPARATOR_String_Trimmed)) { qualityNoticesStrPrepared = qualityNoticesStrPrepared.substring(0, qualityNoticesStrPrepared.length() - SEPARATOR_String_Trimmed.length()); } final String[] qualityNoticesArray = SEPARATOR_Pattern.split(qualityNoticesStrPrepared.trim()); if (qualityNoticesArray == null || qualityNoticesArray.length == 0) { return; }
for (final String qualityNote : qualityNoticesArray) { addQualityNotice(qualityNote); } } /** * * @return string representation of quality notices from this collection */ public String asQualityNoticesString() { if (qualityNoticesSet == null || qualityNoticesSet.isEmpty()) { return ""; } final StringBuilder qualityNoticesStr = new StringBuilder(); for (final String qualityNotice : qualityNoticesSet) { // skip empty notes if (Check.isEmpty(qualityNotice, true)) { continue; } if (qualityNoticesStr.length() > 0) { qualityNoticesStr.append(SEPARATOR_String); } qualityNoticesStr.append(qualityNotice.trim()); } return qualityNoticesStr.toString(); } public Set<String> getQualityNoticesSet() { // always return a copy!!! return new TreeSet<>(this.qualityNoticesSet); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\QualityNoticesCollection.java
1
请完成以下Spring Boot application配置
server.port=8762 spring.application.name=zuul-server eureka.instance.preferIpAddress=true eureka.client.registerWithEureka=true eureka.client.fetchRegistry=true eureka.
client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul-eureka-integration\zuul-server\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public void removeVariables(Collection<String> variableNames) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeVariablesLocal(Collection<String> variableNames) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void setTransientVariablesLocal(Map<String, Object> transientVariables) { throw new UnsupportedOperationException("Empty object, no variables can be set"); } @Override public void setTransientVariableLocal(String variableName, Object variableValue) { throw new UnsupportedOperationException("Empty object, no variables can be set"); } @Override public void setTransientVariables(Map<String, Object> transientVariables) { throw new UnsupportedOperationException("Empty object, no variables can be set"); } @Override public void setTransientVariable(String variableName, Object variableValue) { throw new UnsupportedOperationException("Empty object, no variables can be set"); } @Override public Object getTransientVariableLocal(String variableName) { return null; } @Override public Map<String, Object> getTransientVariablesLocal() { return null; } @Override public Object getTransientVariable(String variableName) { return null; } @Override public Map<String, Object> getTransientVariables() { return null; }
@Override public void removeTransientVariableLocal(String variableName) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeTransientVariablesLocal() { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeTransientVariable(String variableName) { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public void removeTransientVariables() { throw new UnsupportedOperationException("Empty object, no variables can be removed"); } @Override public String getTenantId() { return null; } }
repos\flowable-engine-main\modules\flowable-variable-service-api\src\main\java\org\flowable\variable\api\delegate\EmptyVariableScope.java
2
请在Spring Boot框架中完成以下Java代码
public class Comment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String text; private String articleSlug; private String commentAuthor; public Comment(String text, String articleSlug, String commentAuthor) { this.text = text; this.articleSlug = articleSlug; this.commentAuthor = commentAuthor; } Comment() { } public Long getId() {
return id; } public String getText() { return text; } public String getArticleSlug() { return articleSlug; } public String getCommentAuthor() { return commentAuthor; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-3\src\main\java\com\baeldung\eventuate\tram\domain\Comment.java
2
请完成以下Java代码
public final class JSONNotification implements Serializable { public static JSONNotification of(final UserNotification notification, final JSONOptions jsonOpts) { return new JSONNotification(notification, jsonOpts); } @JsonProperty("id") private final String id; @JsonProperty("message") private final String message; @JsonProperty("timestamp") private final String timestamp; @JsonProperty("important") private final boolean important; @JsonProperty("read") private final boolean read; @JsonProperty("target") private final JSONNotificationTarget target; private JSONNotification( final UserNotification notification, final JSONOptions jsonOpts) { id = String.valueOf(notification.getId()); message = notification.getMessage(jsonOpts.getAdLanguage()); timestamp = DateTimeConverters.toJson(notification.getTimestamp(), jsonOpts.getZoneId()); important = notification.isImportant(); read = notification.isRead(); target = JSONNotificationTarget.of(notification); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("id", id) .add("message", message) .add("timestamp", timestamp)
.add("important", important) .add("read", read) .add("target", target) .toString(); } public String getId() { return id; } public String getMessage() { return message; } public String getTimestamp() { return timestamp; } public boolean isImportant() { return important; } public boolean isRead() { return read; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\json\JSONNotification.java
1
请完成以下Java代码
public CustomizersConfigurer customizeListenerContainer(Consumer<ConcurrentMessageListenerContainer<?, ?>> listenerContainerCustomizer) { this.listenerContainerCustomizer = listenerContainerCustomizer; return this; } /** * Customize the {@link DeadLetterPublishingRecoverer} that will be used to * forward the records to the retry topics and DLT. * @param dlprCustomizer the customizer. * @return the configurer. */ public CustomizersConfigurer customizeDeadLetterPublishingRecoverer(Consumer<DeadLetterPublishingRecoverer> dlprCustomizer) { this.deadLetterPublishingRecovererCustomizer = dlprCustomizer; return this; } @Nullable Consumer<DefaultErrorHandler> getErrorHandlerCustomizer() { return this.errorHandlerCustomizer;
} @Nullable Consumer<ConcurrentMessageListenerContainer<?, ?>> getListenerContainerCustomizer() { return this.listenerContainerCustomizer; } @Nullable Consumer<DeadLetterPublishingRecoverer> getDeadLetterPublishingRecovererCustomizer() { return this.deadLetterPublishingRecovererCustomizer; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfigurationSupport.java
1
请在Spring Boot框架中完成以下Java代码
public class GatewayResource { private final RouteLocator routeLocator; private final DiscoveryClient discoveryClient; @Value("${spring.application.name}") private String appName; public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) { this.routeLocator = routeLocator; this.discoveryClient = discoveryClient; } /** * {@code GET /routes} : get the active routes. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes. */ @GetMapping("/routes")
@Secured(AuthoritiesConstants.ADMIN) public ResponseEntity<List<RouteVM>> activeRoutes() { Flux<Route> routes = routeLocator.getRoutes(); List<RouteVM> routeVMs = new ArrayList<>(); routes.subscribe(route -> { RouteVM routeVM = new RouteVM(); // Manipulate strings to make Gateway routes look like Zuul's String predicate = route.getPredicate().toString(); String path = predicate.substring(predicate.indexOf("[") + 1, predicate.indexOf("]")); routeVM.setPath(path); String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase(); routeVM.setServiceId(serviceId); // Exclude gateway app from routes if (!serviceId.equalsIgnoreCase(appName)) { routeVM.setServiceInstances(discoveryClient.getInstances(serviceId)); routeVMs.add(routeVM); } }); return ResponseEntity.ok(routeVMs); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\GatewayResource.java
2
请完成以下Java代码
public static NamePattern any() { return ANY; } private static final NamePattern ANY = new NamePattern(); @Getter private final boolean any; private final String pattern; private NamePattern(@NonNull final String patternNormalized) { this.any = false; this.pattern = patternNormalized; } private static final String normalizeString(final String str) { if (str == null) { return null; } final String strNorm = str.trim(); if (strNorm.isEmpty()) { return null; } return strNorm; } private NamePattern() { this.any = true; this.pattern = null; } @Override public String toString() { if (any) { return MoreObjects.toStringHelper(this).addValue("ANY").toString(); } else { return MoreObjects.toStringHelper(this).add("pattern", pattern).toString(); } } public boolean isMatching(@NonNull final DataEntryTab tab) { return isMatching(tab.getInternalName()) || isMatching(tab.getCaption()); } public boolean isMatching(@NonNull final DataEntrySubTab subTab) { return isMatching(subTab.getInternalName()) || isMatching(subTab.getCaption()); } public boolean isMatching(@NonNull final DataEntrySection section) { return isMatching(section.getInternalName()) || isMatching(section.getCaption()); } public boolean isMatching(@NonNull final DataEntryLine line) { return isMatching(String.valueOf(line.getSeqNo())); } public boolean isMatching(@NonNull final DataEntryField field) { return isAny() || isMatching(field.getCaption()); } private boolean isMatching(final ITranslatableString trl) {
if (isAny()) { return true; } if (isMatching(trl.getDefaultValue())) { return true; } for (final String adLanguage : trl.getAD_Languages()) { if (isMatching(trl.translate(adLanguage))) { return true; } } return false; } @VisibleForTesting boolean isMatching(final String name) { if (isAny()) { return true; } final String nameNorm = normalizeString(name); if (nameNorm == null) { return false; } return pattern.equalsIgnoreCase(nameNorm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java
1
请完成以下Java代码
public boolean isAllCurrencies () { Object oo = get_Value(COLUMNNAME_IsAllCurrencies); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Open Amount. @param OpenAmt Open item amount */ public void setOpenAmt (BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Open Amount. @return Open item amount */ public BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Percent. @param Percent
Percentage */ public void setPercent (BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } /** Get Percent. @return Percentage */ public BigDecimal getPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_InvoiceGL.java
1
请在Spring Boot框架中完成以下Java代码
public class RSocketApplication { public static void main(String[] args) { SpringApplication.run(RSocketApplication.class, args); } @Bean public RSocketServiceProxyFactory getRSocketServiceProxyFactory(RSocketRequester.Builder requestBuilder) { RSocketRequester requester = requestBuilder.tcp("localhost", 7000); return RSocketServiceProxyFactory.builder(requester) .build(); } @Bean public MessageClient getClient(RSocketServiceProxyFactory factory) { return factory.createClient(MessageClient.class); } @Bean public ApplicationRunner runRequestResponseModel(MessageClient client) { return args -> { client.sendMessage(Mono.just("Request-Response test ")) .doOnNext(message -> { System.out.println("Response is :" + message); }) .subscribe(); }; } @Bean public ApplicationRunner runStreamModel(MessageClient client) { return args -> { client.Counter() .doOnNext(t -> { System.out.println("message is :" + t); }) .subscribe();
}; } @Bean public ApplicationRunner runFireAndForget(MessageClient client) { return args -> { client.Warning(Mono.just("Important Warning")) .subscribe(); }; } @Bean public ApplicationRunner runChannel(MessageClient client) { return args -> { client.channel(Flux.just("a", "b", "c", "d", "e")) .doOnNext(i -> { System.out.println(i); }) .subscribe(); }; } }
repos\tutorials-master\spring-reactive-modules\spring-6-rsocket\src\main\java\com\baeldung\rsocket\responder\RSocketApplication.java
2
请在Spring Boot框架中完成以下Java代码
public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 //rcm.setDefaultExpiration(60);//秒 return rcm;
} @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\config\RedisConfig.java
2
请完成以下Java代码
public java.math.BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return Env.ZERO; return bd; } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) {
set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_ProductScalePrice.java
1
请在Spring Boot框架中完成以下Java代码
public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); templateEngine.setTemplateEngineMessageSource(emailMessageSource()); return templateEngine; } @Bean public ITemplateResolver thymeleafClassLoaderTemplateResolver() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix(mailTemplatesPath + "/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML"); templateResolver.setCharacterEncoding("UTF-8"); return templateResolver; } // @Bean // public ITemplateResolver thymeleafFilesystemTemplateResolver() { // FileTemplateResolver templateResolver = new FileTemplateResolver(); // templateResolver.setPrefix(mailTemplatesPath + "/"); // templateResolver.setSuffix(".html"); // templateResolver.setTemplateMode("HTML"); // templateResolver.setCharacterEncoding("UTF-8"); // return templateResolver; // } @Bean public FreeMarkerConfigurer freemarkerClassLoaderConfig() { Configuration configuration = new Configuration(Configuration.VERSION_2_3_27); TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), "/" + mailTemplatesPath); configuration.setTemplateLoader(templateLoader); FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setConfiguration(configuration); return freeMarkerConfigurer; } // @Bean // public FreeMarkerConfigurer freemarkerFilesystemConfig() throws IOException { // Configuration configuration = new Configuration(Configuration.VERSION_2_3_27); // TemplateLoader templateLoader = new FileTemplateLoader(new File(mailTemplatesPath)); // configuration.setTemplateLoader(templateLoader); // FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); // freeMarkerConfigurer.setConfiguration(configuration); // return freeMarkerConfigurer; // } @Bean public ResourceBundleMessageSource emailMessageSource() { final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("mailMessages"); return messageSource; } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\configuration\EmailConfiguration.java
2
请完成以下Java代码
private final void assertConfigurable() { Check.assume(!executed, "producer shall not be executed"); Check.assume(!inoutRef.isInitialized(), "inout not created yet"); } @Override public IReturnsInOutProducer setC_BPartner(final I_C_BPartner bpartner) { assertConfigurable(); _bpartner = bpartner; return this; } private int getC_BPartner_ID_ToUse() { if (_bpartner != null) { return _bpartner.getC_BPartner_ID(); } return -1; } @Override public IReturnsInOutProducer setC_BPartner_Location(final I_C_BPartner_Location bpLocation) { assertConfigurable(); Check.assumeNotNull(bpLocation, "bpLocation not null"); _bpartnerLocationId = bpLocation.getC_BPartner_Location_ID(); return this; } private int getC_BPartner_Location_ID_ToUse() { if (_bpartnerLocationId > 0) { return _bpartnerLocationId; } final I_C_BPartner bpartner = _bpartner; if (bpartner != null) { final I_C_BPartner_Location bpLocation = bpartnerDAO.retrieveShipToLocation(getCtx(), bpartner.getC_BPartner_ID(), ITrx.TRXNAME_None); if (bpLocation != null) { return bpLocation.getC_BPartner_Location_ID(); } } return -1; } @Override public IReturnsInOutProducer setMovementType(final String movementType) { assertConfigurable(); _movementType = movementType; return this; } public IReturnsInOutProducer setManualReturnInOut(final I_M_InOut manualReturnInOut) { assertConfigurable(); _manualReturnInOut = manualReturnInOut; return this; } private String getMovementTypeToUse() { Check.assumeNotNull(_movementType, "movementType not null"); return _movementType; } @Override public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse) { assertConfigurable(); _warehouse = warehouse; return this; } private final int getM_Warehouse_ID_ToUse() { if (_warehouse != null)
{ return _warehouse.getM_Warehouse_ID(); } return -1; } @Override public IReturnsInOutProducer setMovementDate(final Date movementDate) { Check.assumeNotNull(movementDate, "movementDate not null"); _movementDate = movementDate; return this; } protected final Timestamp getMovementDateToUse() { if (_movementDate != null) { return TimeUtil.asTimestamp(_movementDate); } final Properties ctx = getCtx(); final Timestamp movementDate = Env.getDate(ctx); // use Login date (08306) return movementDate; } @Override public IReturnsInOutProducer setC_Order(final I_C_Order order) { assertConfigurable(); _order = order; return this; } protected I_C_Order getC_Order() { return _order; } @Override public IReturnsInOutProducer dontComplete() { _complete = false; return this; } protected boolean isComplete() { return _complete; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractReturnsInOutProducer.java
1
请完成以下Java代码
public final class KeyGenerators { private KeyGenerators() { } /** * Create a {@link BytesKeyGenerator} that uses a {@link SecureRandom} to generate * keys of 8 bytes in length. */ public static BytesKeyGenerator secureRandom() { return new SecureRandomBytesKeyGenerator(); } /** * Create a {@link BytesKeyGenerator} that uses a {@link SecureRandom} to generate * keys of a custom length. * @param keyLength the key length in bytes, e.g. 16, for a 16 byte key. */ public static BytesKeyGenerator secureRandom(int keyLength) { return new SecureRandomBytesKeyGenerator(keyLength); }
/** * Create a {@link BytesKeyGenerator} that returns a single, shared * {@link SecureRandom} key of a custom length. * @param keyLength the key length in bytes, e.g. 16, for a 16 byte key. */ public static BytesKeyGenerator shared(int keyLength) { return new SharedKeyGenerator(secureRandom(keyLength).generateKey()); } /** * Creates a {@link StringKeyGenerator} that hex-encodes {@link SecureRandom} keys of * 8 bytes in length. The hex-encoded string is keyLength * 2 characters in length. */ public static StringKeyGenerator string() { return new HexEncodingStringKeyGenerator(secureRandom()); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\keygen\KeyGenerators.java
1
请完成以下Java代码
public static ManufacturingOrderReportAudit newInstance(@NonNull final APITransactionId transactionId) { return ManufacturingOrderReportAudit.builder() .transactionId(transactionId) .build(); } @Builder private ManufacturingOrderReportAudit( final APITransactionId transactionId, final String jsonRequest, final String jsonResponse, final ImportStatus importStatus, final String errorMsg, final AdIssueId adIssueId, @Singular final List<ManufacturingOrderReportAuditItem> items) { this.transactionId = transactionId; this.jsonRequest = jsonRequest; this.jsonResponse = jsonResponse; this.importStatus = importStatus; this.errorMsg = errorMsg; this.adIssueId = adIssueId; this.items = items != null ? new ArrayList<>(items) : new ArrayList<>(); } public void addItem(@NonNull final ManufacturingOrderReportAuditItem item)
{ items.add(item); } public ImmutableList<ManufacturingOrderReportAuditItem> getItems() { return ImmutableList.copyOf(items); } public void markAsSuccess() { this.importStatus = ImportStatus.SUCCESS; this.errorMsg = null; this.adIssueId = null; } public void markAsFailure(@NonNull final String errorMsg, @NonNull final AdIssueId adIssueId) { this.importStatus = ImportStatus.FAILED; this.errorMsg = errorMsg; this.adIssueId = adIssueId; items.forEach(ManufacturingOrderReportAuditItem::markAsRolledBackIfSuccess); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\importaudit\ManufacturingOrderReportAudit.java
1
请完成以下Java代码
public List<String> getUserGroups(String username) { return userDetailsService .loadUserByUsername(username) .getAuthorities() .stream() .filter((GrantedAuthority a) -> a.getAuthority().startsWith("GROUP_")) .map((GrantedAuthority a) -> a.getAuthority().substring(6)) .collect(Collectors.toList()); } @Override public List<String> getUserRoles(String username) { return userDetailsService .loadUserByUsername(username) .getAuthorities()
.stream() .filter((GrantedAuthority a) -> a.getAuthority().startsWith("ROLE_")) .map((GrantedAuthority a) -> a.getAuthority().substring(5)) .collect(Collectors.toList()); } @Override public List<String> getGroups() { return ((ExtendedInMemoryUserDetailsManager) userDetailsService).getGroups(); } @Override public List<String> getUsers() { return ((ExtendedInMemoryUserDetailsManager) userDetailsService).getUsers(); } }
repos\Activiti-develop\activiti-core-common\activiti-spring-identity\src\main\java\org\activiti\core\common\spring\identity\ActivitiUserGroupManagerImpl.java
1
请完成以下Java代码
public void registerAsyncBatchNoticeListener(final IAsyncBatchListener l, final String asyncBatchType) { if (listenersList.containsKey(asyncBatchType)) { throw new IllegalStateException(l + " has already been added"); } else { listenersList.put(asyncBatchType, l); } } @Override public void applyListener(@NonNull final I_C_Async_Batch asyncBatch) { final String internalName = asyncBatchBL.getAsyncBatchTypeInternalName(asyncBatch).orElse(null); if(internalName != null) { final IAsyncBatchListener listener = getListener(internalName); listener.createNotice(asyncBatch); } } private IAsyncBatchListener getListener(final String ascyncBatchType) { IAsyncBatchListener l = listenersList.get(ascyncBatchType); // retrieve default implementation if (l == null) { l = listenersList.get(AsyncBatchDAO.ASYNC_BATCH_TYPE_DEFAULT); }
return l; } private final List<INotifyAsyncBatch> asycnBatchNotifiers = new ArrayList<>(); @Override public void registerAsyncBatchNotifier(INotifyAsyncBatch notifyAsyncBatch) { Check.assume(!asycnBatchNotifiers.contains(notifyAsyncBatch), "Every notifier is added only once"); asycnBatchNotifiers.add(notifyAsyncBatch); } @Override public void notify(I_C_Async_Batch asyncBatch) { for (INotifyAsyncBatch notifier : asycnBatchNotifiers) { notifier.sendNotifications(asyncBatch); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchListeners.java
1
请完成以下Java代码
public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Boolean getAvailable() { return available; }
public void setAvailable(Boolean available) { this.available = available; } public List<SysPermission> getPermissions() { return permissions; } public void setPermissions(List<SysPermission> permissions) { this.permissions = permissions; } public List<UserInfo> getUserInfos() { return userInfos; } public void setUserInfos(List<UserInfo> userInfos) { this.userInfos = userInfos; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysRole.java
1
请完成以下Java代码
public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public org.compiere.model.I_S_Resource getS_Resource() { return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class); } @Override public void setS_Resource(org.compiere.model.I_S_Resource S_Resource) { set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
} @Override public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } @Override public int getS_Resource_ID() { return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PostSaleAuthenticationProgram postSaleAuthenticationProgram = (PostSaleAuthenticationProgram)o; return Objects.equals(this.outcomeReason, postSaleAuthenticationProgram.outcomeReason) && Objects.equals(this.status, postSaleAuthenticationProgram.status); } @Override public int hashCode() { return Objects.hash(outcomeReason, status); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PostSaleAuthenticationProgram {\n");
sb.append(" outcomeReason: ").append(toIndentedString(outcomeReason)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PostSaleAuthenticationProgram.java
2
请完成以下Java代码
public String toString() { return "PrinterHW [name=" + name + ", printerHWMediaSizes=" + printerHWMediaSizes + ", printerHWMediaTrays=" + printerHWMediaTrays + "]"; } /** * Printer HW Media Size Object * * @author al */ public static class PrinterHWMediaSize implements Serializable { /** * */ private static final long serialVersionUID = 5962990173434911764L; private String name; private String isDefault; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaSize [name=" + name + ", isDefault=" + isDefault + "]"; } } /** * Printer HW Media Tray Object * * @author al */ public static class PrinterHWMediaTray implements Serializable { /** * */ private static final long serialVersionUID = -1833627999553124042L; private String name; private String trayNumber; private String isDefault; public String getName()
{ return name; } public void setName(String name) { this.name = name; } public String getTrayNumber() { return trayNumber; } public void setTrayNumber(String trayNumber) { this.trayNumber = trayNumber; } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } @Override public String toString() { return "PrinterHWMediaTray [name=" + name + ", trayNumber=" + trayNumber + ", isDefault=" + isDefault + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrinterHW.java
1