instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class HUsToIssueView_IssueHUs extends HUEditorProcessTemplate implements IProcessDefaultParametersProvider { private final ServiceRepairProjectService projectService = SpringContextHolder.instance.getBean(ServiceRepairProjectService.class); private static final String PARAM_Qty = "Qty"; @Param(parameterName = PARAM_Qty, mandatory = true) private BigDecimal qty; private static final String PARAM_C_UOM_ID = "C_UOM_ID"; @Param(parameterName = PARAM_C_UOM_ID, mandatory = true) private UomId uomId; private final HashMap<ServiceRepairProjectTaskId, ServiceRepairProjectTask> tasksCache = new HashMap<>(); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return super.checkPreconditionsApplicable(); } @Nullable @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_Qty.equals(parameter.getColumnName())) { return getTask().getQtyToReserve().toZeroIfNegative().toBigDecimal(); } if (PARAM_C_UOM_ID.equals(parameter.getColumnName())) { return getTask().getQtyToReserve().getUomId(); } else { return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected String doIt() { final Quantity qtyToReserve = getQtyToReserveParam(); final ImmutableSet<HuId> huIds = getSelectedTopLevelHUIds(); final ServiceRepairProjectTaskId taskId = getTaskId();
projectService.reserveSparePartsFromHUs(taskId, qtyToReserve, huIds); tasksCache.clear(); return MSG_OK; } private Quantity getQtyToReserveParam() { final Quantity qtyToReserve = Quantitys.of(qty, uomId); if (qtyToReserve.signum() <= 0) { throw new FillMandatoryException(PARAM_Qty); } return qtyToReserve; } private ServiceRepairProjectTask getTask() { return tasksCache.computeIfAbsent(getTaskId(), projectService::getTaskById); } private ServiceRepairProjectTaskId getTaskId() { final HUsToIssueViewContext husToIssueViewContext = getHusToIssueViewContext(); return husToIssueViewContext.getTaskId(); } private ImmutableSet<HuId> getSelectedTopLevelHUIds() { return streamSelectedHUIds(HUEditorRowFilter.Select.ONLY_TOPLEVEL).collect(ImmutableSet.toImmutableSet()); } private HUsToIssueViewContext getHusToIssueViewContext() { return getView() .getParameter(HUsToIssueViewFactory.PARAM_HUsToIssueViewContext, HUsToIssueViewContext.class) .orElseThrow(() -> new AdempiereException("No view context")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\HUsToIssueView_IssueHUs.java
2
请完成以下Java代码
public Response validExceptionHandler(BindException e) { StringBuilder message = new StringBuilder(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); for (FieldError error : fieldErrors) { message.append(error.getField()).append(error.getDefaultMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return new Response().message(message.toString()); } /** * 统一处理请求参数校验(普通传参) * * @param e ConstraintViolationException * @return FebsResponse */ @ExceptionHandler(value = ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Response handleConstraintViolationException(ConstraintViolationException e) { StringBuilder message = new StringBuilder();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); for (ConstraintViolation<?> violation : violations) { Path path = violation.getPropertyPath(); String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), "."); message.append(pathArr[1]).append(violation.getMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return new Response().message(message.toString()); } @ExceptionHandler(value = UnauthorizedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public void handleUnauthorizedException(Exception e) { log.error("权限不足,{}", e.getMessage()); } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
public Timestamp getDateFrom () { return (Timestamp)get_Value(COLUMNNAME_DateFrom); } /** Set Date To. @param DateTo End date of a date range */ public void setDateTo (Timestamp DateTo) { set_Value (COLUMNNAME_DateTo, DateTo); } /** Get Date To. @return End date of a date range */ public Timestamp getDateTo () { return (Timestamp)get_Value(COLUMNNAME_DateTo); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set GL Fund. @param GL_Fund_ID General Ledger Funds Control */ public void setGL_Fund_ID (int GL_Fund_ID) { if (GL_Fund_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID)); } /** Get GL Fund. @return General Ledger Funds Control */ public int getGL_Fund_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Fund.java
1
请完成以下Java代码
public String anotherGet() { return "get.html"; } @Route(value = "/allmatch-route-example") public String allmatch() { return "allmatch.html"; } @Route(value = "/triggerInternalServerError") public void triggerInternalServerError() { int x = 1 / 0; } @Route(value = "/triggerBaeldungException") public void triggerBaeldungException() throws BaeldungException { throw new BaeldungException("Foobar Exception to threat differently"); } @Route(value = "/user/foo") public void urlCoveredByNarrowedWebhook(Response response) { response.text("Check out for the WebHook covering '/user/*' in the logs"); }
@GetRoute("/load-configuration-in-a-route") public void loadConfigurationInARoute(Response response) { String authors = WebContext.blade() .env("app.authors", "Unknown authors"); log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors); response.render("index.html"); } @GetRoute("/template-output-test") public void templateOutputTest(Request request, Response response) { request.attribute("name", "Blade"); response.render("template-output-test.html"); } }
repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\RouteExampleController.java
1
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQtyReject (final @Nullable BigDecimal QtyReject) { set_Value (COLUMNNAME_QtyReject, QtyReject); } @Override public BigDecimal getQtyReject() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReject); return bd != null ? bd : BigDecimal.ZERO; } @Override public org.eevolution.model.I_PP_Cost_Collector getReversal() { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.eevolution.model.I_PP_Cost_Collector.class); } @Override public void setReversal(final org.eevolution.model.I_PP_Cost_Collector Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.eevolution.model.I_PP_Cost_Collector.class, Reversal); } @Override public void setReversal_ID (final int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Reversal_ID); } @Override public int getReversal_ID() { return get_ValueAsInt(COLUMNNAME_Reversal_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(final 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 (final int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, S_Resource_ID); } @Override public int getS_Resource_ID() {
return get_ValueAsInt(COLUMNNAME_S_Resource_ID); } @Override public void setScrappedQty (final @Nullable BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } @Override public BigDecimal getScrappedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ScrappedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSetupTimeReal (final @Nullable BigDecimal SetupTimeReal) { set_Value (COLUMNNAME_SetupTimeReal, SetupTimeReal); } @Override public BigDecimal getSetupTimeReal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SetupTimeReal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector.java
1
请完成以下Java代码
private static RouterFunction<?> routingFunction() { return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) .map(MultiValueMap::toSingleValueMap) .map(formData -> { System.out.println("form data: " + formData.toString()); if ("baeldung".equals(formData.get("user")) && "you_know_what_to_do".equals(formData.get("token"))) { return ok().body(Mono.just("welcome back!"), String.class) .block(); } return ServerResponse.badRequest() .build() .block(); })) .andRoute(POST("/upload"), serverRequest -> serverRequest.body(toDataBuffers()) .collectList() .map(dataBuffers -> { AtomicLong atomicLong = new AtomicLong(0); dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer()
.array().length)); System.out.println("data length:" + atomicLong.get()); return ok().body(fromValue(atomicLong.toString())) .block(); })) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), route(GET("/"), serverRequest -> ok().body(Flux.fromIterable(actors), Actor.class)).andRoute(POST("/"), serverRequest -> serverRequest.bodyToMono(Actor.class) .doOnNext(actors::add) .then(ok().build()))) .filter((request, next) -> { System.out.println("Before handler invocation: " + request.path()); return next.handle(request); }); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\functional\RootServlet.java
1
请完成以下Java代码
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MKTG_ContactPerson_With_Campaign_ID. @param MKTG_ContactPerson_With_Campaign_ID MKTG_ContactPerson_With_Campaign_ID */ @Override public void setMKTG_ContactPerson_With_Campaign_ID (int MKTG_ContactPerson_With_Campaign_ID) { if (MKTG_ContactPerson_With_Campaign_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID, Integer.valueOf(MKTG_ContactPerson_With_Campaign_ID)); } /** Get MKTG_ContactPerson_With_Campaign_ID. @return MKTG_ContactPerson_With_Campaign_ID */ @Override
public int getMKTG_ContactPerson_With_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_With_Campaign_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_With_Campaign_V.java
1
请完成以下Spring Boot application配置
log4jdbc.dump.sql.addsemicolon=true log4jdbc.dump.sql.maxlinelength=0 log4jdbc.trim.sql.extrablanklines=false logging.level.jdbc.audit=fatal logging.level.jdbc.connection=fatal logging.level.jdbc.resultset=fatal logging.level.jdbc.resultsettable=info logging.level.jdbc.sqlonly=fatal logging.level.jdbc.sqltiming=info spring.datasource.url=jdbc:mysql://localhost:53306/hibernate_types?serverTimezone=UTC&useSSL=false spring.datasource.use
rname=root spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=create spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public Collection<DataMessageAsyncEvent> getMessages() { return Collections.unmodifiableCollection(this.messages.values()); } public void resetMessages() { this.messages.clear(); } @KafkaListener(topics = "prod-con-test-topic") public void consume(EventWrapper<? extends AsyncEvent> message) throws IOException { LOGGER.info("#### Consumed message -> {} {}", message.getType()); if (message.getType().equals(DataMessageAsyncEvent.class)) { EventWrapper<DataMessageAsyncEvent> wrapper = (EventWrapper<DataMessageAsyncEvent>)message; messages.put(wrapper.getEvent().getId(), wrapper.getEvent()); } else if (message.getType().equals(CreateAccountAsyncEvent.class)) { EventWrapper<CreateAccountAsyncEvent> wrapper = (EventWrapper<CreateAccountAsyncEvent>)message; accountService.createAccount(wrapper.getEvent());
} else if (message.getType().equals(DeleteAccountAsyncEvent.class)) { EventWrapper<DeleteAccountAsyncEvent> wrapper = (EventWrapper<DeleteAccountAsyncEvent>)message; accountService.deleteAccount(wrapper.getEvent()); } else if (message.getType().equals(TransferFundsAsyncEvent.class)) { EventWrapper<TransferFundsAsyncEvent> wrapper = (EventWrapper<TransferFundsAsyncEvent>)message; accountService.transferFunds(wrapper.getEvent()); } else if (message.getType().equals(DepositAccountAsyncEvent.class)) { EventWrapper<DepositAccountAsyncEvent> wrapper = (EventWrapper<DepositAccountAsyncEvent>)message; accountService.depositFunds(wrapper.getEvent()); } else { LOGGER.error("ERROR: unsupported message type {}", message.getType()); } } }
repos\spring-examples-java-17\spring-kafka\kafka-consumer\src\main\java\itx\examples\spring\kafka\consumer\service\EventConsumer.java
2
请完成以下Java代码
public Map<String, org.activiti.engine.impl.persistence.entity.VariableInstance> getInternalTaskVariables( String taskId ) { return taskService.getVariableInstancesLocal(taskId); } public void createVariable(boolean isAdmin, CreateTaskVariablePayload createTaskVariablePayload) { if (!isAdmin) { assertCanModifyTask(getInternalTask(createTaskVariablePayload.getTaskId())); } taskVariablesValidator.handleCreateTaskVariablePayload(createTaskVariablePayload); assertVariableDoesNotExist(createTaskVariablePayload); taskService.setVariableLocal( createTaskVariablePayload.getTaskId(), createTaskVariablePayload.getName(), createTaskVariablePayload.getValue() ); } private void assertVariableDoesNotExist(CreateTaskVariablePayload createTaskVariablePayload) { Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal( createTaskVariablePayload.getTaskId() ); if (variables != null && variables.containsKey(createTaskVariablePayload.getName())) { throw new IllegalStateException("Variable already exists"); } } public void updateVariable(boolean isAdmin, UpdateTaskVariablePayload updateTaskVariablePayload) { if (!isAdmin) { assertCanModifyTask(getInternalTask(updateTaskVariablePayload.getTaskId())); } taskVariablesValidator.handleUpdateTaskVariablePayload(updateTaskVariablePayload); assertVariableExists(updateTaskVariablePayload); taskService.setVariableLocal( updateTaskVariablePayload.getTaskId(), updateTaskVariablePayload.getName(), updateTaskVariablePayload.getValue() );
} private void assertVariableExists(UpdateTaskVariablePayload updateTaskVariablePayload) { Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal( updateTaskVariablePayload.getTaskId() ); if (variables == null) { throw new IllegalStateException("Variable does not exist"); } if (!variables.containsKey(updateTaskVariablePayload.getName())) { throw new IllegalStateException("Variable does not exist"); } } public void handleCompleteTaskPayload(CompleteTaskPayload completeTaskPayload) { completeTaskPayload.setVariables( taskVariablesValidator.handlePayloadVariables(completeTaskPayload.getVariables()) ); } public void handleSaveTaskPayload(SaveTaskPayload saveTaskPayload) { saveTaskPayload.setVariables(taskVariablesValidator.handlePayloadVariables(saveTaskPayload.getVariables())); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskRuntimeHelper.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Number of Inventory counts. @param NoInventoryCount Frequency of inventory counts per year */ public void setNoInventoryCount (int NoInventoryCount) { set_Value (COLUMNNAME_NoInventoryCount, Integer.valueOf(NoInventoryCount)); } /** Get Number of Inventory counts. @return Frequency of inventory counts per year */ public int getNoInventoryCount () { Integer ii = (Integer)get_Value(COLUMNNAME_NoInventoryCount); if (ii == null) return 0; return ii.intValue(); } /** Set Number of Product counts. @param NoProductCount Frequency of product counts per year */ public void setNoProductCount (int NoProductCount) { set_Value (COLUMNNAME_NoProductCount, Integer.valueOf(NoProductCount)); } /** Get Number of Product counts. @return Frequency of product counts per year */ public int getNoProductCount () { Integer ii = (Integer)get_Value(COLUMNNAME_NoProductCount); if (ii == null) return 0; return ii.intValue(); } /** Set Number of runs. @param NumberOfRuns Frequency of processing Perpetual Inventory */ public void setNumberOfRuns (int NumberOfRuns) { set_Value (COLUMNNAME_NumberOfRuns, Integer.valueOf(NumberOfRuns)); }
/** Get Number of runs. @return Frequency of processing Perpetual Inventory */ public int getNumberOfRuns () { Integer ii = (Integer)get_Value(COLUMNNAME_NumberOfRuns); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PerpetualInv.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { @Bean public HttpFirewall allowHttpMethod() { List<String> allowedMethods = new ArrayList<>(); allowedMethods.add("GET"); allowedMethods.add("POST"); StrictHttpFirewall firewall = new StrictHttpFirewall(); firewall.setAllowedHttpMethods(allowedMethods); return firewall; } @Bean public WebSecurityCustomizer fireWall() { return (web) -> web.httpFirewall(allowHttpMethod()); } @Bean public WebSecurityCustomizer ignoringCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**", "/static/**"); } @Bean public WebSecurityCustomizer debugSecurity() { return (web) -> web.debug(true); } @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user") .password(encoder().encode("userPass"))
.roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user); } @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((authorize) -> authorize.requestMatchers("/admin/**") .hasRole("ADMIN") .anyRequest() .permitAll()) .httpBasic(withDefaults()) .formLogin(withDefaults()) .csrf(AbstractHttpConfigurer::disable); return http.build(); } }
repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\httpsecurityvswebsecurity\SecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringBatchRetryConfig { private static final String[] tokens = { "username", "userid", "transactiondate", "amount" }; private static final int TWO_SECONDS = 2000; @Value("input/recordRetry.csv") private Resource inputCsv; @Value("file:xml/retryOutput.xml") private WritableResource outputXml; public ItemReader<Transaction> itemReader(Resource inputData) { DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(tokens); DefaultLineMapper<Transaction> lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); FlatFileItemReader<Transaction> reader = new FlatFileItemReader<>(); reader.setResource(inputData); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper); return reader; } @Bean public CloseableHttpClient closeableHttpClient() { final RequestConfig config = RequestConfig.custom() .setConnectTimeout(TWO_SECONDS) .build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } @Bean public ItemProcessor<Transaction, Transaction> retryItemProcessor() { return new RetryItemProcessor(); } @Bean public ItemWriter<Transaction> itemWriter(Marshaller marshaller) { StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<>();
itemWriter.setMarshaller(marshaller); itemWriter.setRootTagName("transactionRecord"); itemWriter.setResource(outputXml); return itemWriter; } @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean public Step retryStep( JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("retryItemProcessor") ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) { return new StepBuilder("retryStep", jobRepository) .<Transaction, Transaction>chunk(10, transactionManager) .reader(itemReader(inputCsv)) .processor(processor) .writer(writer) .faultTolerant() .retryLimit(3) .retry(ConnectTimeoutException.class) .retry(DeadlockLoserDataAccessException.class) .build(); } @Bean(name = "retryBatchJob") public Job retryJob(JobRepository jobRepository, @Qualifier("retryStep") Step retryStep) { return new JobBuilder("retryBatchJob", jobRepository) .start(retryStep) .build(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\batch\SpringBatchRetryConfig.java
2
请完成以下Java代码
public class OAuth2ClientMetadataClaimNames { /** * {@code client_id} - the Client Identifier */ public static final String CLIENT_ID = "client_id"; /** * {@code client_id_issued_at} - the time at which the Client Identifier was issued */ public static final String CLIENT_ID_ISSUED_AT = "client_id_issued_at"; /** * {@code client_secret} - the Client Secret */ public static final String CLIENT_SECRET = "client_secret"; /** * {@code client_secret_expires_at} - the time at which the {@code client_secret} will * expire or 0 if it will not expire */ public static final String CLIENT_SECRET_EXPIRES_AT = "client_secret_expires_at"; /** * {@code client_name} - the name of the Client to be presented to the End-User */ public static final String CLIENT_NAME = "client_name"; /** * {@code redirect_uris} - the redirection {@code URI} values used by the Client */ public static final String REDIRECT_URIS = "redirect_uris"; /** * {@code token_endpoint_auth_method} - the authentication method used by the Client
* for the Token Endpoint */ public static final String TOKEN_ENDPOINT_AUTH_METHOD = "token_endpoint_auth_method"; /** * {@code grant_types} - the OAuth 2.0 {@code grant_type} values that the Client will * restrict itself to using */ public static final String GRANT_TYPES = "grant_types"; /** * {@code response_types} - the OAuth 2.0 {@code response_type} values that the Client * will restrict itself to using */ public static final String RESPONSE_TYPES = "response_types"; /** * {@code scope} - a space-separated list of OAuth 2.0 {@code scope} values that the * Client will restrict itself to using */ public static final String SCOPE = "scope"; /** * {@code jwks_uri} - the {@code URL} for the Client's JSON Web Key Set */ public static final String JWKS_URI = "jwks_uri"; protected OAuth2ClientMetadataClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2ClientMetadataClaimNames.java
1
请在Spring Boot框架中完成以下Java代码
public SecuritySettings getSecuritySettings() { AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "securitySettings"); SecuritySettings securitySettings; if (adminSettings != null) { try { securitySettings = JacksonUtil.convertValue(adminSettings.getJsonValue(), SecuritySettings.class); } catch (Exception e) { throw new RuntimeException("Failed to load security settings!", e); } } else { securitySettings = new SecuritySettings(); securitySettings.setPasswordPolicy(new UserPasswordPolicy()); securitySettings.getPasswordPolicy().setMinimumLength(6); securitySettings.getPasswordPolicy().setMaximumLength(72); securitySettings.setMobileSecretKeyLength(DEFAULT_MOBILE_SECRET_KEY_LENGTH); securitySettings.setPasswordResetTokenTtl(24); securitySettings.setUserActivationTokenTtl(24); } return securitySettings; }
@CacheEvict(cacheNames = SECURITY_SETTINGS_CACHE, key = "'securitySettings'") @Override public SecuritySettings saveSecuritySettings(SecuritySettings securitySettings) { ConstraintValidator.validateFields(securitySettings); AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "securitySettings"); if (adminSettings == null) { adminSettings = new AdminSettings(); adminSettings.setTenantId(TenantId.SYS_TENANT_ID); adminSettings.setKey("securitySettings"); } adminSettings.setJsonValue(JacksonUtil.valueToTree(securitySettings)); AdminSettings savedAdminSettings = adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminSettings); try { return JacksonUtil.convertValue(savedAdminSettings.getJsonValue(), SecuritySettings.class); } catch (Exception e) { throw new RuntimeException("Failed to load security settings!", e); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\settings\DefaultSecuritySettingsService.java
2
请完成以下Java代码
public class ReactiveRegistrationClient implements RegistrationClient { private static final ParameterizedTypeReference<Map<String, Object>> RESPONSE_TYPE = new ParameterizedTypeReference<>() { }; private final WebClient webclient; private final Duration timeout; public ReactiveRegistrationClient(WebClient webclient, Duration timeout) { this.webclient = webclient; this.timeout = timeout; } @Override public String register(String adminUrl, Application application) { Map<String, Object> response = this.webclient.post() .uri(adminUrl) .headers(this::setRequestHeaders) .bodyValue(application) .retrieve() .bodyToMono(RESPONSE_TYPE)
.timeout(this.timeout) .block(); return response.get("id").toString(); } @Override public void deregister(String adminUrl, String id) { this.webclient.delete().uri(adminUrl + '/' + id).retrieve().toBodilessEntity().timeout(this.timeout).block(); } protected void setRequestHeaders(HttpHeaders headers) { headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\ReactiveRegistrationClient.java
1
请完成以下Java代码
public List<UOMConversionsMap> getProductUOMConversions(final Set<ProductId> productIds) { if (productIds.isEmpty()) { return ImmutableList.of(); } return productIds.stream().map(uomConversionDAO::getProductConversions).collect(ImmutableList.toImmutableList()); } public Stream<I_M_Product_Category> streamAllProductCategories() { return productsRepo.streamAllProductCategories(); } public List<I_C_BPartner> getPartnerRecords(@NonNull final ImmutableSet<BPartnerId> manufacturerIds) { return queryBL.createQueryBuilder(I_C_BPartner.class) .addInArrayFilter(I_C_BPartner.COLUMN_C_BPartner_ID, manufacturerIds) .create()
.list(); } @NonNull public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(@NonNull final I_M_Product_Category record) { final ZoneId orgZoneId = orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID())); return JsonCreatedUpdatedInfo.builder() .created(TimeUtil.asZonedDateTime(record.getCreated(), orgZoneId)) .createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM)) .updated(TimeUtil.asZonedDateTime(record.getUpdated(), orgZoneId)) .updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductsServicesFacade.java
1
请完成以下Java代码
public class InterfaceImpl extends RootElementImpl implements Interface { protected static Attribute<String> nameAttribute; protected static Attribute<String> implementationRefAttribute; protected static ChildElementCollection<Operation> operationCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Interface.class, BPMN_ELEMENT_INTERFACE) .namespaceUri(BPMN20_NS) .extendsType(RootElement.class) .instanceProvider(new ModelTypeInstanceProvider<Interface>() { public Interface newInstance(ModelTypeInstanceContext instanceContext) { return new InterfaceImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .required() .build(); implementationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION_REF) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); operationCollection = sequenceBuilder.elementCollection(Operation.class) .required() .build(); typeBuilder.build(); } public InterfaceImpl(ModelTypeInstanceContext context) {
super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public String getImplementationRef() { return implementationRefAttribute.getValue(this); } public void setImplementationRef(String implementationRef) { implementationRefAttribute.setValue(this, implementationRef); } public Collection<Operation> getOperations() { return operationCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\InterfaceImpl.java
1
请完成以下Java代码
public String registration(Model model) { model.addAttribute("userForm", new User()); return "registration"; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) { userValidator.validate(userForm, bindingResult); if (bindingResult.hasErrors()) { return "registration"; } userService.save(userForm); return "redirect:/welcome"; } @RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) { if (error != null) model.addAttribute("error", "Your username and password is invalid."); if (logout != null) model.addAttribute("message", "You have been logged out successfully."); return "login"; } @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET) public String welcome(Model model) { return "welcome"; } }
repos\Spring-Boot-Advanced-Projects-main\login-registration-springboot-hibernate-jsp-auth\src\main\java\net\alanbinu\springboot\loginregistrationspringbootauthjsp\web\UserController.java
1
请在Spring Boot框架中完成以下Java代码
public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities;
} public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } @Override public String toString() { return "UserDTO{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
2
请完成以下Java代码
private List<PickingCandidateIssueToBOMLine> getIssuesToPickingOrder() { if (issuesToPickingOrderRequests == null || issuesToPickingOrderRequests.isEmpty()) { return ImmutableList.of(); } return issuesToPickingOrderRequests.stream() .map(this::toPickingCandidateIssueToBOMLine) .collect(ImmutableList.toImmutableList()); } private PickingCandidateIssueToBOMLine toPickingCandidateIssueToBOMLine(final IssueToPickingOrderRequest request) { return PickingCandidateIssueToBOMLine.builder() .issueToOrderBOMLineId(request.getIssueToOrderBOMLineId()) .issueFromHUId(request.getIssueFromHUId()) .productId(request.getProductId()) .qtyToIssue(request.getQtyToIssue()) .build(); } private Quantity getQtyToPick() { if (qtyToPick != null) { return qtyToPick; } else { return getQtyFromHU(); } } private Quantity getQtyFromHU() { final I_M_HU pickFromHU = handlingUnitsDAO.getById(pickFrom.getHuId()); final ProductId productId = getProductId(); final IHUProductStorage productStorage = huContextFactory .createMutableHUContext() .getHUStorageFactory() .getStorage(pickFromHU) .getProductStorageOrNull(productId);
// Allow empty storage. That's the case when we are adding a newly created HU if (productStorage == null) { final I_C_UOM uom = getShipmentScheduleUOM(); return Quantity.zero(uom); } return productStorage.getQty(); } private I_M_ShipmentSchedule getShipmentSchedule() { if (_shipmentSchedule == null) { _shipmentSchedule = shipmentSchedulesRepo.getById(shipmentScheduleId, I_M_ShipmentSchedule.class); } return _shipmentSchedule; } private I_C_UOM getShipmentScheduleUOM() { return shipmentScheduleBL.getUomOfProduct(getShipmentSchedule()); } private void allocatePickingSlotIfPossible() { if (pickingSlotId == null) { return; } final I_M_ShipmentSchedule shipmentSchedule = getShipmentSchedule(); final BPartnerLocationId bpartnerAndLocationId = shipmentScheduleEffectiveBL.getBPartnerLocationId(shipmentSchedule); huPickingSlotBL.allocatePickingSlotIfPossible(PickingSlotAllocateRequest.builder() .pickingSlotId(pickingSlotId) .bpartnerAndLocationId(bpartnerAndLocationId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PickHUCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultQueueConfiguration implements IEventBusQueueConfiguration { public static final String QUEUE_BEAN_NAME = "metasfreshEventsQueue"; static final String QUEUE_NAME_SPEL = "#{metasfreshEventsQueue.name}"; private static final String EXCHANGE_NAME_PREFIX = "metasfresh-events"; @Value(RabbitMQEventBusConfiguration.APPLICATION_NAME_SPEL) private String appName; @Bean(QUEUE_BEAN_NAME) public AnonymousQueue eventsQueue() { final NamingStrategy eventQueueNamingStrategy = new Base64UrlNamingStrategy("metasfresh.events." + appName + "-"); return new AnonymousQueue(eventQueueNamingStrategy); } @Bean public DirectExchange eventsExchange() { return new DirectExchange(EXCHANGE_NAME_PREFIX); } @Bean public Binding eventsBinding() {
return BindingBuilder.bind(eventsQueue()) .to(eventsExchange()).with(EXCHANGE_NAME_PREFIX); } @Override public String getQueueName() { return eventsQueue().getName(); } @Override public Optional<String> getTopicName() { return Optional.empty(); } @Override public String getExchangeName() { return eventsExchange().getName(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\queues\default_queue\DefaultQueueConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public <T> T execute(final Callable<T> callable) { Callable<T> callableEffective = callable; // // First(important). Run in transaction if (inTransaction) { final Callable<T> beforeCall = callableEffective; callableEffective = () -> { final ITrxManager trxManager = Services.get(ITrxManager.class); try { return trxManager.callInNewTrx(beforeCall); } catch (final Exception ex) { logger.info("Changes that will be discarded: {}", getCurrentDocumentChangesCollectorOrNull()); throw AdempiereException.wrapIfNeeded(ex); } }; } // // Retry on version error if (versionErrorRetryCount > 0) { final Callable<T> beforeCall = callableEffective; callableEffective = () -> { InvalidDocumentVersionException versionException = null; for (int retry = 0; retry < versionErrorRetryCount; retry++) { try { return beforeCall.call(); } catch (final InvalidDocumentVersionException ex) { versionException = ex; logger.info("Version error on run {}/{}", retry + 1, versionErrorRetryCount, versionException); } } Check.assumeNotNull(versionException, "VersionException must not be null"); throw versionException; }; } // // Last, measure and log { final Callable<T> beforeCall = callableEffective; callableEffective = () -> { boolean error = true; final Stopwatch stopwatch = Stopwatch.createStarted(); try { final T result = beforeCall.call(); error = false; return result; }
finally { if (!error) { logger.debug("Executed {} in {} ({})", name, stopwatch, callable); } else { logger.warn("Failed executing {} (took {}) ({})", name, stopwatch, callable); } } }; } // // Run the effective callable in a new execution try (final Execution ignored = startExecution()) { return callableEffective.call(); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex); } } public ExecutionBuilder name(final String name) { this.name = name; return this; } public ExecutionBuilder retryOnVersionError(final int retryCount) { Preconditions.checkArgument(retryCount > 0); versionErrorRetryCount = retryCount; return this; } public ExecutionBuilder outOfTransaction() { inTransaction = false; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\Execution.java
2
请完成以下Java代码
public class HaveIBeenPwnedRestApiReactivePasswordChecker implements ReactiveCompromisedPasswordChecker { private static final String API_URL = "https://api.pwnedpasswords.com/range/"; private static final int PREFIX_LENGTH = 5; private final Log logger = LogFactory.getLog(getClass()); private WebClient webClient = WebClient.builder().baseUrl(API_URL).build(); private final MessageDigest sha1Digest; public HaveIBeenPwnedRestApiReactivePasswordChecker() { this.sha1Digest = getSha1Digest(); } @Override public Mono<CompromisedPasswordDecision> check(@Nullable String password) { return getHash(password).map((hash) -> new String(Hex.encode(hash))) .flatMap(this::findLeakedPassword) .defaultIfEmpty(Boolean.FALSE) .map(CompromisedPasswordDecision::new); } private Mono<Boolean> findLeakedPassword(String encodedPassword) { String prefix = encodedPassword.substring(0, PREFIX_LENGTH).toUpperCase(Locale.ROOT); String suffix = encodedPassword.substring(PREFIX_LENGTH).toUpperCase(Locale.ROOT); return getLeakedPasswordsForPrefix(prefix).any((leakedPw) -> leakedPw.startsWith(suffix)); } private Flux<String> getLeakedPasswordsForPrefix(String prefix) { return this.webClient.get().uri(prefix).retrieve().bodyToMono(String.class).flatMapMany((body) -> { if (StringUtils.hasText(body)) { return Flux.fromStream(body.lines()); } return Flux.empty(); }) .doOnError((ex) -> this.logger.error("Request for leaked passwords failed", ex)) .onErrorResume(WebClientResponseException.class, (ex) -> Flux.empty()); } /** * Sets the {@link WebClient} to use when making requests to Have I Been Pwned REST * API. By default, a {@link WebClient} with a base URL of {@link #API_URL} is used. * @param webClient the {@link WebClient} to use */
public void setWebClient(WebClient webClient) { Assert.notNull(webClient, "webClient cannot be null"); this.webClient = webClient; } private Mono<byte[]> getHash(@Nullable String rawPassword) { return Mono.justOrEmpty(rawPassword) .map((password) -> this.sha1Digest.digest(password.getBytes(StandardCharsets.UTF_8))) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()); } private static MessageDigest getSha1Digest() { try { return MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex.getMessage()); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\password\HaveIBeenPwnedRestApiReactivePasswordChecker.java
1
请完成以下Java代码
public void setAD_ClientShare_ID (int AD_ClientShare_ID) { if (AD_ClientShare_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_ClientShare_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_ClientShare_ID, Integer.valueOf(AD_ClientShare_ID)); } /** Get Client Share. @return Force (not) sharing of client/org entities */ public int getAD_ClientShare_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_ClientShare_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Table getAD_Table() throws RuntimeException { return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name) .getPO(getAD_Table_ID(), get_TrxName()); } /** Set Table. @param AD_Table_ID Database Table information */ public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get Table. @return Database Table information */ public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () {
return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** ShareType AD_Reference_ID=365 */ public static final int SHARETYPE_AD_Reference_ID=365; /** Client (all shared) = C */ public static final String SHARETYPE_ClientAllShared = "C"; /** Org (not shared) = O */ public static final String SHARETYPE_OrgNotShared = "O"; /** Client or Org = x */ public static final String SHARETYPE_ClientOrOrg = "x"; /** Set Share Type. @param ShareType Type of sharing */ public void setShareType (String ShareType) { set_Value (COLUMNNAME_ShareType, ShareType); } /** Get Share Type. @return Type of sharing */ public String getShareType () { return (String)get_Value(COLUMNNAME_ShareType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ClientShare.java
1
请完成以下Java代码
protected ActiveMQConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new ActiveMQDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link ActiveMQConnectionDetails} backed by an {@code activemq} * {@link RunningService}. */ static class ActiveMQDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements ActiveMQConnectionDetails { private final ActiveMQClassicEnvironment environment; private final String brokerUrl; protected ActiveMQDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new ActiveMQClassicEnvironment(service.env()); this.brokerUrl = "tcp://" + service.host() + ":" + service.ports().get(ACTIVEMQ_PORT); } @Override public String getBrokerUrl() {
return this.brokerUrl; } @Override public @Nullable String getUser() { return this.environment.getUser(); } @Override public @Nullable String getPassword() { return this.environment.getPassword(); } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\docker\compose\ActiveMQClassicDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public void doFinally() { trxRunnable.doFinally(); } }; } public static <T> TrxCallable<T> wrapIfNeeded(final Callable<T> callable) { if (callable == null) { return null; } if (callable instanceof TrxCallable) { final TrxCallable<T> trxCallable = (TrxCallable<T>)callable; return trxCallable; } return new TrxCallableAdapter<T>() { @Override public String toString() { return "TrxCallableWrappers[" + callable + "]"; } @Override public T call() throws Exception { return callable.call(); } }; } public static <T> TrxCallableWithTrxName<T> wrapAsTrxCallableWithTrxNameIfNeeded(final TrxCallable<T> callable) { if (callable == null) { return null; } if (callable instanceof TrxCallableWithTrxName) { final TrxCallableWithTrxName<T> callableWithTrxName = (TrxCallableWithTrxName<T>)callable; return callableWithTrxName; } return new TrxCallableWithTrxName<T>()
{ @Override public String toString() { return "TrxCallableWithTrxName-wrapper[" + callable + "]"; } @Override public T call(final String localTrxName) throws Exception { return callable.call(); } @Override public T call() throws Exception { throw new IllegalStateException("This method shall not be called"); } @Override public boolean doCatch(final Throwable e) throws Throwable { return callable.doCatch(e); } @Override public void doFinally() { callable.doFinally(); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxCallableWrappers.java
1
请在Spring Boot框架中完成以下Java代码
public class OssEndpoint { private QiniuTemplate qiniuTemplate; /** * 创建存储桶 * * @param bucketName 存储桶名称 * @return Bucket */ @SneakyThrows @PostMapping("/make-bucket") public R makeBucket(@RequestParam String bucketName) { qiniuTemplate.makeBucket(bucketName); return R.success("创建成功"); } /** * 创建存储桶 * * @param bucketName 存储桶名称 * @return R */ @SneakyThrows @PostMapping("/remove-bucket") public R removeBucket(@RequestParam String bucketName) { qiniuTemplate.removeBucket(bucketName); return R.success("删除成功"); } /** * 拷贝文件 * * @param fileName 存储桶对象名称 * @param destBucketName 目标存储桶名称 * @param destFileName 目标存储桶对象名称 * @return R */ @SneakyThrows @PostMapping("/copy-file") public R copyFile(@RequestParam String fileName, @RequestParam String destBucketName, String destFileName) { qiniuTemplate.copyFile(fileName, destBucketName, destFileName); return R.success("操作成功"); } /** * 获取文件信息 * * @param fileName 存储桶对象名称 * @return InputStream */ @SneakyThrows @GetMapping("/stat-file") public R<OssFile> statFile(@RequestParam String fileName) { return R.data(qiniuTemplate.statFile(fileName)); } /** * 获取文件相对路径 * * @param fileName 存储桶对象名称 * @return String */ @SneakyThrows @GetMapping("/file-path") public R<String> filePath(@RequestParam String fileName) { return R.data(qiniuTemplate.filePath(fileName)); }
/** * 获取文件外链 * * @param fileName 存储桶对象名称 * @return String */ @SneakyThrows @GetMapping("/file-link") public R<String> fileLink(@RequestParam String fileName) { return R.data(qiniuTemplate.fileLink(fileName)); } /** * 上传文件 * * @param file 文件 * @return ObjectStat */ @SneakyThrows @PostMapping("/put-file") public R<BladeFile> putFile(@RequestParam MultipartFile file) { BladeFile bladeFile = qiniuTemplate.putFile(file.getOriginalFilename(), file.getInputStream()); return R.data(bladeFile); } /** * 上传文件 * * @param fileName 存储桶对象名称 * @param file 文件 * @return ObjectStat */ @SneakyThrows @PostMapping("/put-file-by-name") public R<BladeFile> putFile(@RequestParam String fileName, @RequestParam MultipartFile file) { BladeFile bladeFile = qiniuTemplate.putFile(fileName, file.getInputStream()); return R.data(bladeFile); } /** * 删除文件 * * @param fileName 存储桶对象名称 * @return R */ @SneakyThrows @PostMapping("/remove-file") public R removeFile(@RequestParam String fileName) { qiniuTemplate.removeFile(fileName); return R.success("操作成功"); } /** * 批量删除文件 * * @param fileNames 存储桶对象名称集合 * @return R */ @SneakyThrows @PostMapping("/remove-files") public R removeFiles(@RequestParam String fileNames) { qiniuTemplate.removeFiles(Func.toStrList(fileNames)); return R.success("操作成功"); } }
repos\SpringBlade-master\blade-ops\blade-resource\src\main\java\org\springblade\resource\endpoint\OssEndpoint.java
2
请完成以下Java代码
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; if (!this.explicitSecurityContextProvided) { this.delegateSecurityContext = this.securityContextHolderStrategy.getContext(); } } @Override public String toString() { return this.delegate.toString(); } /** * Factory method for creating a {@link DelegatingSecurityContextRunnable}. * @param delegate the original {@link Runnable} that will be delegated to after * establishing a {@link SecurityContext} on the {@link SecurityContextHolder}. Cannot * have null. * @param securityContext the {@link SecurityContext} to establish before invoking the * delegate {@link Runnable}. If null, the current {@link SecurityContext} from the
* {@link SecurityContextHolder} will be used. * @return */ public static Runnable create(Runnable delegate, @Nullable SecurityContext securityContext) { Assert.notNull(delegate, "delegate cannot be null"); return (securityContext != null) ? new DelegatingSecurityContextRunnable(delegate, securityContext) : new DelegatingSecurityContextRunnable(delegate); } static Runnable create(Runnable delegate, @Nullable SecurityContext securityContext, SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(delegate, "delegate cannot be null"); Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); DelegatingSecurityContextRunnable runnable = (securityContext != null) ? new DelegatingSecurityContextRunnable(delegate, securityContext) : new DelegatingSecurityContextRunnable(delegate); runnable.setSecurityContextHolderStrategy(securityContextHolderStrategy); return runnable; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextRunnable.java
1
请完成以下Java代码
class EmptyVariableContainer implements VariableContainer { static final EmptyVariableContainer INSTANCE = new EmptyVariableContainer(); @Override public boolean hasVariable(String variableName) { return false; } @Override public Object getVariable(String variableName) { return null; } @Override public void setVariable(String variableName, Object variableValue) { 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 String getTenantId() { return null; } @Override public Set<String> getVariableNames() { return Collections.emptySet(); } }
repos\flowable-engine-main\modules\flowable-engine-common-api\src\main\java\org\flowable\common\engine\api\variable\EmptyVariableContainer.java
1
请完成以下Java代码
public static Set<Integer> toRepoIds(@NonNull final Collection<HuId> huIds) { return huIds.stream().map(HuId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static Set<HuId> fromRepoIds(@Nullable final Collection<Integer> huRepoIds) { if (huRepoIds == null || huRepoIds.isEmpty()) { return ImmutableSet.of(); } return huRepoIds.stream().map(HuId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } public static HuId ofHUValue(@NonNull final String huValue) { try { return ofRepoId(Integer.parseInt(huValue)); } catch (final Exception ex) { final AdempiereException metasfreshException = new AdempiereException("Invalid HUValue `" + huValue + "`. It cannot be converted to M_HU_ID."); metasfreshException.addSuppressed(ex); throw metasfreshException; } } public static HuId ofHUValueOrNull(@Nullable final String huValue) { final String huValueNorm = StringUtils.trimBlankToNull(huValue); if (huValueNorm == null) {return null;} try
{ return ofRepoIdOrNull(NumberUtils.asIntOrZero(huValueNorm)); } catch (final Exception ex) { return null; } } public String toHUValue() {return String.valueOf(repoId);} int repoId; private HuId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final HuId o1, @Nullable final HuId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuId.java
1
请完成以下Java代码
private boolean matchesFilter(final LookupValue region, final String filterUC) { final String displayName = region.getDisplayName(); if (Check.isEmpty(displayName)) { return false; } final String displayNameUC = displayName.trim().toUpperCase(); return displayNameUC.contains(filterUC); } private LookupValuesList getRegionLookupValues(final int countryId) { return regionsByCountryId.getOrLoad(countryId, () -> retrieveRegionLookupValues(countryId)); } private LookupValuesList retrieveRegionLookupValues(final int countryId) { return Services.get(ICountryDAO.class) .retrieveRegions(Env.getCtx(), countryId) .stream()
.map(this::createLookupValue) .collect(LookupValuesList.collect()); } private IntegerLookupValue createLookupValue(final I_C_Region regionRecord) { return IntegerLookupValue.of(regionRecord.getC_Region_ID(), regionRecord.getName()); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRegionLookupDescriptor.java
1
请完成以下Java代码
public void setWorkingTime (java.math.BigDecimal WorkingTime) { set_Value (COLUMNNAME_WorkingTime, WorkingTime); } /** Get Working Time. @return Workflow Simulation Execution Time */ @Override public java.math.BigDecimal getWorkingTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WorkingTime); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield () {
Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } @Override public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID) { if (C_Manufacturing_Aggregation_ID < 1) set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null); else set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID); } @Override public int getC_Manufacturing_Aggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\product\model\X_M_Product_PlanningSchema.java
1
请完成以下Java代码
private final int getM_ShipmentSchedule_ID(final ShipmentScheduleWithHU schedWithHU) { if (schedWithHU == null) { return -1; } final I_M_ShipmentSchedule shipmentSchedule = schedWithHU.getM_ShipmentSchedule(); if (shipmentSchedule == null) { // shall not happen return -1; } final int shipmentScheduleId = shipmentSchedule.getM_ShipmentSchedule_ID(); if (shipmentScheduleId <= 0) { return -1; } return shipmentScheduleId; } private final String getAggregationKey(final ShipmentScheduleWithHU schedWithHU) { if (schedWithHU == null) { return ""; } final I_M_ShipmentSchedule shipmentSchedule = schedWithHU.getM_ShipmentSchedule(); if (shipmentSchedule == null) { // shall not happen return ""; } final StringBuilder aggregationKey = new StringBuilder(); // // Shipment header aggregation key (from M_ShipmentSchedule) final String shipmentScheduleAggregationKey = shipmentScheduleKeyBuilder.buildKey(shipmentSchedule); if (shipmentScheduleAggregationKey != null) { aggregationKey.append(shipmentScheduleAggregationKey); } // // Shipment header aggregation key (the HU related part) final String huShipmentScheduleAggregationKey = huShipmentScheduleKeyBuilder.buildKey(schedWithHU); if (huShipmentScheduleAggregationKey != null) { if (aggregationKey.length() > 0) { aggregationKey.append("#"); } aggregationKey.append(huShipmentScheduleAggregationKey); } // // Shipment line aggregation key {
final Object attributesAggregationKey = schedWithHU.getAttributesAggregationKey(); if (aggregationKey.length() > 0) { aggregationKey.append("#"); } aggregationKey.append(attributesAggregationKey); } return aggregationKey.toString(); } private final int getM_HU_ID(@NonNull final ShipmentScheduleWithHU schedWithHU) { final I_M_HU huRecord = coalesce(schedWithHU.getM_LU_HU(), schedWithHU.getM_TU_HU(), schedWithHU.getVHU()); if (huRecord == null) { return Integer.MAX_VALUE; } final int huId = huRecord.getM_HU_ID(); if (huId <= 0) { return Integer.MAX_VALUE; } return huId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleWithHUComparator.java
1
请完成以下Java代码
public final class ObservationAuthenticationManager implements AuthenticationManager { private final ObservationRegistry registry; private final AuthenticationManager delegate; private ObservationConvention<AuthenticationObservationContext> convention = new AuthenticationObservationConvention(); public ObservationAuthenticationManager(ObservationRegistry registry, AuthenticationManager delegate) { Assert.notNull(registry, "observationRegistry cannot be null"); Assert.notNull(delegate, "authenticationManager cannot be null"); this.registry = registry; this.delegate = delegate; } @Override @SuppressWarnings("NullAway") // Dataflow analysis limitation public Authentication authenticate(Authentication authentication) throws AuthenticationException { AuthenticationObservationContext context = new AuthenticationObservationContext(); context.setAuthenticationRequest(authentication); context.setAuthenticationManagerClass(this.delegate.getClass());
return Observation.createNotStarted(this.convention, () -> context, this.registry).observe(() -> { Authentication result = this.delegate.authenticate(authentication); context.setAuthenticationResult(result); return result; }); } /** * Use the provided convention for reporting observation data * @param convention The provided convention * * @since 6.1 */ public void setObservationConvention(ObservationConvention<AuthenticationObservationContext> convention) { Assert.notNull(convention, "The observation convention cannot be null"); this.convention = convention; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ObservationAuthenticationManager.java
1
请完成以下Java代码
public void setCM_WebProject_ID (int CM_WebProject_ID) { if (CM_WebProject_ID < 1) set_Value (COLUMNNAME_CM_WebProject_ID, null); else set_Value (COLUMNNAME_CM_WebProject_ID, Integer.valueOf(CM_WebProject_ID)); } /** Get Web Project. @return A web project is the main data container for Containers, URLs, Ads, Media etc. */ public int getCM_WebProject_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); }
/** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad_Cat.java
1
请在Spring Boot框架中完成以下Java代码
public MediaType getMediaType() { return mediaType; } public void setMediaType(MediaType mediaType) { this.mediaType = mediaType; } public String getMediaTypeParamName() { return mediaTypeParamName; } public void setMediaTypeParamName(String mediaTypeParamName) { this.mediaTypeParamName = mediaTypeParamName; } public Integer getPathSegment() { return pathSegment; } public void setPathSegment(Integer pathSegment) { this.pathSegment = pathSegment; } public String getRequestParamName() { return requestParamName; } public void setRequestParamName(String requestParamName) { this.requestParamName = requestParamName; } public boolean isRequired() { return required;
} public void setRequired(boolean required) { this.required = required; } public List<String> getSupportedVersions() { return supportedVersions; } public void setSupportedVersions(List<String> supportedVersions) { this.supportedVersions = supportedVersions; } @Override public String toString() { // @formatter:off return new ToStringCreator(this) .append("defaultVersion", defaultVersion) .append("detectSupportedVersions", detectSupportedVersions) .append("headerName", headerName) .append("mediaType", mediaType) .append("mediaTypeParamName", mediaTypeParamName) .append("pathSegment", pathSegment) .append("requestParamName", requestParamName) .append("required", required) .append("supportedVersions", supportedVersions) .toString(); // @formatter:on } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\VersionProperties.java
2
请在Spring Boot框架中完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseInstanceUrl() { return caseInstanceUrl; } public void setCaseInstanceUrl(String caseInstanceUrl) { this.caseInstanceUrl = caseInstanceUrl; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType;
} public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceResponse.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Replication_Run[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_Replication getAD_Replication() throws RuntimeException { return (I_AD_Replication)MTable.get(getCtx(), I_AD_Replication.Table_Name) .getPO(getAD_Replication_ID(), get_TrxName()); } /** Set Replication. @param AD_Replication_ID Data Replication Target */ public void setAD_Replication_ID (int AD_Replication_ID) { if (AD_Replication_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Replication_ID, Integer.valueOf(AD_Replication_ID)); } /** Get Replication. @return Data Replication Target */ public int getAD_Replication_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Replication Run. @param AD_Replication_Run_ID Data Replication Run */ public void setAD_Replication_Run_ID (int AD_Replication_Run_ID) { if (AD_Replication_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Replication_Run_ID, Integer.valueOf(AD_Replication_Run_ID)); } /** Get Replication Run. @return Data Replication Run */ public int getAD_Replication_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description.
@return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Replicated. @param IsReplicated The data is successfully replicated */ public void setIsReplicated (boolean IsReplicated) { set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated)); } /** Get Replicated. @return The data is successfully replicated */ public boolean isReplicated () { Object oo = get_Value(COLUMNNAME_IsReplicated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Run.java
1
请完成以下Java代码
public Timestamp getDateNextRun (boolean requery) { if (requery) load(get_TrxName()); return getDateNextRun(); } // getDateNextRun /** * Get Logs * @return logs */ @Override public AdempiereProcessorLog[] getLogs () { ArrayList<MAlertProcessorLog> list = new ArrayList<>(); String sql = "SELECT * " + "FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=? " + "ORDER BY Created DESC"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlertProcessorLog (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } MAlertProcessorLog[] retValue = new MAlertProcessorLog[list.size ()]; list.toArray (retValue); return retValue; } // getLogs /** * Delete old Request Log * @return number of records */ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=" + getAD_AlertProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog /** * Get Alerts * @param reload reload data
* @return array of alerts */ public MAlert[] getAlerts (boolean reload) { MAlert[] alerts = s_cacheAlerts.get(get_ID()); if (alerts != null && !reload) return alerts; String sql = "SELECT * FROM AD_Alert " + "WHERE AD_AlertProcessor_ID=? AND IsActive='Y' "; ArrayList<MAlert> list = new ArrayList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlert (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } // alerts = new MAlert[list.size ()]; list.toArray (alerts); s_cacheAlerts.put(get_ID(), alerts); return alerts; } // getAlerts @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MAlertProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessor.java
1
请在Spring Boot框架中完成以下Java代码
ProjectGenerationController<ProjectRequest> projectGenerationController( InitializrMetadataProvider metadataProvider, ObjectProvider<ProjectRequestPlatformVersionTransformer> platformVersionTransformer, ApplicationContext applicationContext) { ProjectGenerationInvoker<ProjectRequest> projectGenerationInvoker = new ProjectGenerationInvoker<>( applicationContext, new DefaultProjectRequestToDescriptionConverter(platformVersionTransformer .getIfAvailable(DefaultProjectRequestPlatformVersionTransformer::new))); return new DefaultProjectGenerationController(metadataProvider, projectGenerationInvoker); } @Bean @ConditionalOnMissingBean ProjectMetadataController projectMetadataController(InitializrMetadataProvider metadataProvider, DependencyMetadataProvider dependencyMetadataProvider) { return new ProjectMetadataController(metadataProvider, dependencyMetadataProvider); } @Bean @ConditionalOnMissingBean CommandLineMetadataController commandLineMetadataController(InitializrMetadataProvider metadataProvider, TemplateRenderer templateRenderer) { return new CommandLineMetadataController(metadataProvider, templateRenderer); } @Bean @ConditionalOnMissingBean SpringCliDistributionController cliDistributionController(InitializrMetadataProvider metadataProvider) { return new SpringCliDistributionController(metadataProvider); } @Bean InitializrModule InitializrJacksonModule() { return new InitializrModule(); } } /** * Initializr cache configuration. */ @Configuration @ConditionalOnClass(javax.cache.CacheManager.class) static class InitializrCacheConfiguration { @Bean JCacheManagerCustomizer initializrCacheManagerCustomizer() { return new InitializrJCacheManagerCustomizer(); } } @Order(0) private static final class InitializrJCacheManagerCustomizer implements JCacheManagerCustomizer {
@Override public void customize(javax.cache.CacheManager cacheManager) { createMissingCache(cacheManager, "initializr.metadata", () -> config().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES))); createMissingCache(cacheManager, "initializr.dependency-metadata", this::config); createMissingCache(cacheManager, "initializr.project-resources", this::config); createMissingCache(cacheManager, "initializr.templates", this::config); } private void createMissingCache(javax.cache.CacheManager cacheManager, String cacheName, Supplier<MutableConfiguration<Object, Object>> config) { boolean cacheExist = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch((name) -> name.equals(cacheName)); if (!cacheExist) { cacheManager.createCache(cacheName, config.get()); } } private MutableConfiguration<Object, Object> config() { return new MutableConfiguration<>().setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrAutoConfiguration.java
2
请完成以下Java代码
private static KPIField extractGroupByField(final @NonNull List<KPIField> fields) { final List<KPIField> groupByFieldsList = fields.stream() .filter(KPIField::isGroupBy) .collect(GuavaCollectors.toImmutableList()); if (groupByFieldsList.isEmpty()) { return null; } else if (groupByFieldsList.size() == 1) { return groupByFieldsList.get(0); } else { throw new AdempiereException("Only one group by field allowed but we found: " + groupByFieldsList); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("id", id) .add("caption", caption.getDefaultValue()) .toString(); } public String getCaption(final String adLanguage) { return caption.translate(adLanguage); } public String getDescription(final String adLanguage) { return description.translate(adLanguage); } public KPIField getGroupByField() { final KPIField groupByField = getGroupByFieldOrNull(); if (groupByField == null) { throw new IllegalStateException("KPI has no group by field defined"); } return groupByField; } @Nullable public KPIField getGroupByFieldOrNull() { return groupByField; } public boolean hasCompareOffset() {
return compareOffset != null; } public Set<CtxName> getRequiredContextParameters() { if (elasticsearchDatasource != null) { return elasticsearchDatasource.getRequiredContextParameters(); } else if (sqlDatasource != null) { return sqlDatasource.getRequiredContextParameters(); } else { throw new AdempiereException("Unknown datasource type: " + datasourceType); } } public boolean isZoomToDetailsAvailable() { return sqlDatasource != null; } @NonNull public SQLDatasourceDescriptor getSqlDatasourceNotNull() { return Check.assumeNotNull(getSqlDatasource(), "Not an SQL data source: {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPI.java
1
请完成以下Java代码
protected String getDispatcherWebApplicationContextSuffix() { return null; } /** * Invoked before the springSessionRepositoryFilter is added. * @param servletContext the {@link ServletContext} */ protected void beforeSessionRepositoryFilter(ServletContext servletContext) { } /** * Invoked after the springSessionRepositoryFilter is added. * @param servletContext the {@link ServletContext} */ protected void afterSessionRepositoryFilter(ServletContext servletContext) { }
/** * Get the {@link DispatcherType} for the springSessionRepositoryFilter. * @return the {@link DispatcherType} for the filter */ protected EnumSet<DispatcherType> getSessionDispatcherTypes() { return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC); } /** * Determine if the springSessionRepositoryFilter should be marked as supporting * asynch. Default is true. * @return true if springSessionRepositoryFilter should be marked as supporting asynch */ protected boolean isAsyncSessionSupported() { return true; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\context\AbstractHttpSessionApplicationInitializer.java
1
请完成以下Java代码
public Class<? extends HistoricDecisionExecutionEntity> getManagedEntityClass() { return HistoricDecisionExecutionEntityImpl.class; } @Override public HistoricDecisionExecutionEntity create() { return new HistoricDecisionExecutionEntityImpl(); } @Override public void deleteHistoricDecisionExecutionsByDeploymentId(String deploymentId) { getDbSqlSession().delete("deleteHistoricDecisionExecutionsByDeploymentId", deploymentId, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<DmnHistoricDecisionExecution> findHistoricDecisionExecutionsByQueryCriteria(HistoricDecisionExecutionQueryImpl decisionExecutionQuery) { return getDbSqlSession().selectList("selectHistoricDecisionExecutionsByQueryCriteria", decisionExecutionQuery, getManagedEntityClass()); } @Override public long findHistoricDecisionExecutionCountByQueryCriteria(HistoricDecisionExecutionQueryImpl decisionExecutionQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricDecisionExecutionCountByQueryCriteria", decisionExecutionQuery); } @Override @SuppressWarnings("unchecked") public List<DmnHistoricDecisionExecution> findHistoricDecisionExecutionsByNativeQuery(Map<String, Object> parameterMap) { return getDbSqlSession().selectListWithRawParameter("selectHistoricDecisionExecutionsByNativeQuery", parameterMap); } @Override public long findHistoricDecisionExecutionCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricDecisionExecutionCountByNativeQuery", parameterMap); } @Override public void delete(HistoricDecisionExecutionQueryImpl query) { getDbSqlSession().delete("bulkDeleteHistoricDecisionExecutions", query, getManagedEntityClass()); } @Override public void bulkDeleteHistoricDecisionExecutionsByInstanceIdsAndScopeType(Collection<String> instanceIds, String scopeType) { Map<String, Object> params = new HashMap<>(); params.put("instanceIds", createSafeInValuesList(instanceIds)); params.put("scopeType", scopeType); getDbSqlSession().delete("bulkDeleteHistoricDecisionExecutionsByInstanceIdsAndScopeType", params, getManagedEntityClass()); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\data\impl\MybatisHistoricDecisionExecutionDataManager.java
1
请完成以下Java代码
private static List<Centroid> randomCentroids(List<Record> records, int k) { List<Centroid> centroids = new ArrayList<>(); Map<String, Double> maxs = new HashMap<>(); Map<String, Double> mins = new HashMap<>(); for (Record record : records) { record .getFeatures() .forEach((key, value) -> { // compares the value with the current max and choose the bigger value between them maxs.compute(key, (k1, max) -> max == null || value > max ? value : max); // compare the value with the current min and choose the smaller value between them mins.compute(key, (k1, min) -> min == null || value < min ? value : min); }); } Set<String> attributes = records .stream() .flatMap(e -> e .getFeatures() .keySet() .stream()) .collect(toSet()); for (int i = 0; i < k; i++) { Map<String, Double> coordinates = new HashMap<>(); for (String attribute : attributes) { double max = maxs.get(attribute); double min = mins.get(attribute); coordinates.put(attribute, random.nextDouble() * (max - min) + min); }
centroids.add(new Centroid(coordinates)); } return centroids; } private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) { if (records == null || records.isEmpty()) { throw new IllegalArgumentException("The dataset can't be empty"); } if (k <= 1) { throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster"); } if (distance == null) { throw new IllegalArgumentException("The distance calculator is required"); } if (maxIterations <= 0) { throw new IllegalArgumentException("Max iterations should be a positive number"); } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\KMeans.java
1
请完成以下Java代码
public class JWTFilter extends BasicHttpAuthenticationFilter { private Logger log = LoggerFactory.getLogger(this.getClass()); private static final String TOKEN = "Token"; private AntPathMatcher pathMatcher = new AntPathMatcher(); @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; SystemProperties properties = SpringContextUtil.getBean(SystemProperties.class); String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ","); boolean match = false; for (String u : anonUrl) { if (pathMatcher.match(u, httpServletRequest.getRequestURI())) match = true; } if (match) return true; if (isLoginAttempt(request, response)) { return executeLogin(request, response); } return false; } @Override protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) { HttpServletRequest req = (HttpServletRequest) request; String token = req.getHeader(TOKEN); return token != null; }
@Override protected boolean executeLogin(ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String token = httpServletRequest.getHeader(TOKEN); JWTToken jwtToken = new JWTToken(token); try { getSubject(request, response).login(jwtToken); return true; } catch (Exception e) { log.error(e.getMessage()); return false; } } /** * 对跨域提供支持 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域时会首先发送一个 option请求,这里我们给 option请求直接返回正常状态 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTFilter.java
1
请完成以下Java代码
public int getHandOver_User_ID() { return delegate.getHandOver_User_ID(); } @Override public void setHandOver_User_ID(final int HandOver_User_ID) { delegate.setHandOver_User_ID(HandOver_User_ID); } @Override public String getHandOverAddress() { return delegate.getHandOverAddress(); } @Override public void setHandOverAddress(final String address) { delegate.setHandOverAddress(address); } @Override public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddressAndCapturedLocation(from); } @Override public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from) { IDocumentHandOverLocationAdapter.super.setRenderedAddress(from); }
@Override public I_C_Order getWrappedRecord() { return delegate; } @Override public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL) { return documentLocationBL.toPlainDocumentLocation(this); } @Override public OrderHandOverLocationAdapter toOldValues() { InterfaceWrapperHelper.assertNotOldValues(delegate); return new OrderHandOverLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class)); } public void setFromHandOverLocation(@NonNull final I_C_Order from) { final BPartnerId bpartnerId = BPartnerId.ofRepoId(from.getHandOver_Partner_ID()); final BPartnerInfo bpartnerInfo = BPartnerInfo.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, from.getHandOver_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, from.getHandOver_User_ID())) .build(); setFrom(bpartnerInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderHandOverLocationAdapter.java
1
请完成以下Java代码
public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; // StringBuffer sb = new StringBuffer (); // int pos = amount.lastIndexOf ('.'); // Old int pos = amount.lastIndexOf (','); // int pos2 = amount.lastIndexOf (','); // Old int pos2 = amount.lastIndexOf ('.'); if (pos2 > pos) pos = pos2; String oldamt = amount; // amount = amount.replaceAll (",", ""); // Old amount = amount.replaceAll( "\\.",""); // int newpos = amount.lastIndexOf ('.'); // Old int newpos = amount.lastIndexOf (','); int pesos = Integer.parseInt (amount.substring (0, newpos)); sb.append (convert (pesos)); for (int i = 0; i < oldamt.length (); i++)
{ if (pos == i) // we are done { String cents = oldamt.substring (i + 1); sb.append (' ') .append (cents) .append ("/100"); // .append ("/100 EUROS"); break; } } return sb.toString (); } // getAmtInWords } // AmtInWords_CA
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_CA.java
1
请完成以下Java代码
public Iterator<Resource> iterator() { return this.resources.iterator(); } public Scripts continueOnError(boolean continueOnError) { this.continueOnError = continueOnError; return this; } public boolean isContinueOnError() { return this.continueOnError; } public Scripts separator(String separator) { this.separator = separator; return this; }
public String getSeparator() { return this.separator; } public Scripts encoding(@Nullable Charset encoding) { this.encoding = encoding; return this; } public @Nullable Charset getEncoding() { return this.encoding; } } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_K_EntryRelated[") .append(get_ID()).append("]"); return sb.toString(); } public I_K_Entry getK_Entry() throws RuntimeException { return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name) .getPO(getK_Entry_ID(), get_TrxName()); } /** Set Entry. @param K_Entry_ID Knowledge Entry */ public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Related Entry. @param K_EntryRelated_ID Related Entry for this Enntry */ public void setK_EntryRelated_ID (int K_EntryRelated_ID) { if (K_EntryRelated_ID < 1) set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, null); else set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, Integer.valueOf(K_EntryRelated_ID)); } /** Get Related Entry. @return Related Entry for this Enntry */ public int getK_EntryRelated_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_ID);
if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getK_EntryRelated_ID())); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryRelated.java
1
请在Spring Boot框架中完成以下Java代码
public class RefreshTokenExpCheckService { public static final int AZURE_DEFAULT_REFRESH_TOKEN_LIFETIME_IN_DAYS = 90; private final AdminSettingsService adminSettingsService; @Scheduled(initialDelayString = "#{T(org.apache.commons.lang3.RandomUtils).nextLong(0, ${mail.oauth2.refreshTokenCheckingInterval})}", fixedDelayString = "${mail.oauth2.refreshTokenCheckingInterval}", timeUnit = TimeUnit.SECONDS) public void check() throws IOException { AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "mail"); if (settings != null && settings.getJsonValue().has("enableOauth2") && settings.getJsonValue().get("enableOauth2").asBoolean()) { JsonNode jsonValue = settings.getJsonValue(); if (OFFICE_365.name().equals(jsonValue.get("providerId").asText()) && jsonValue.has("refreshToken") && jsonValue.has("refreshTokenExpires")) { try { long expiresIn = jsonValue.get("refreshTokenExpires").longValue(); long tokenLifeDuration = expiresIn - System.currentTimeMillis(); if (tokenLifeDuration < 0) { ((ObjectNode) jsonValue).put("tokenGenerated", false); ((ObjectNode) jsonValue).remove("refreshToken"); ((ObjectNode) jsonValue).remove("refreshTokenExpires"); adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); } else if (tokenLifeDuration < 604800000L) { //less than 7 days log.info("Trying to refresh refresh token."); String clientId = jsonValue.get("clientId").asText(); String clientSecret = jsonValue.get("clientSecret").asText(); String refreshToken = jsonValue.get("refreshToken").asText();
String tokenUri = jsonValue.get("tokenUri").asText(); TokenResponse tokenResponse = new RefreshTokenRequest(new NetHttpTransport(), new GsonFactory(), new GenericUrl(tokenUri), refreshToken) .setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)) .execute(); ((ObjectNode) jsonValue).put("refreshToken", tokenResponse.getRefreshToken()); ((ObjectNode) jsonValue).put("refreshTokenExpires", Instant.now().plus(Duration.ofDays(AZURE_DEFAULT_REFRESH_TOKEN_LIFETIME_IN_DAYS)).toEpochMilli()); adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings); } } catch (Exception e) { log.error("Error occurred while checking token", e); } } } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\mail\RefreshTokenExpCheckService.java
2
请完成以下Java代码
private void validateRouteDefinition(RouteDefinition routeDefinition) { Set<String> unavailableFilterDefinitions = routeDefinition.getFilters() .stream() .filter(rd -> !isAvailable(rd)) .map(FilterDefinition::getName) .collect(Collectors.toSet()); Set<String> unavailablePredicatesDefinitions = routeDefinition.getPredicates() .stream() .filter(rd -> !isAvailable(rd)) .map(PredicateDefinition::getName) .collect(Collectors.toSet()); if (!unavailableFilterDefinitions.isEmpty()) { handleUnavailableDefinition(FilterDefinition.class.getSimpleName(), unavailableFilterDefinitions); } else if (!unavailablePredicatesDefinitions.isEmpty()) { handleUnavailableDefinition(PredicateDefinition.class.getSimpleName(), unavailablePredicatesDefinitions); } validateRouteUri(routeDefinition.getUri()); } private void validateRouteUri(URI uri) { if (uri == null) { handleError("The URI can not be empty"); } if (!StringUtils.hasText(uri.getScheme())) { handleError(String.format("The URI format [%s] is incorrect, scheme can not be empty", uri)); } } private void handleUnavailableDefinition(String simpleName, Set<String> unavailableDefinitions) { final String errorMessage = String.format("Invalid %s: %s", simpleName, unavailableDefinitions); log.warn(errorMessage); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage); } private void handleError(String errorMessage) { log.warn(errorMessage); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errorMessage);
} private boolean isAvailable(FilterDefinition filterDefinition) { return GatewayFilters.stream() .anyMatch(gatewayFilterFactory -> filterDefinition.getName().equals(gatewayFilterFactory.name())); } private boolean isAvailable(PredicateDefinition predicateDefinition) { return routePredicates.stream() .anyMatch(routePredicate -> predicateDefinition.getName().equals(routePredicate.name())); } @DeleteMapping("/routes/{id}") public Mono<ResponseEntity<Object>> delete(@PathVariable String id) { return this.routeDefinitionWriter.delete(Mono.just(id)).then(Mono.defer(() -> { publisher.publishEvent(new RouteDeletedEvent(this, id)); return Mono.just(ResponseEntity.ok().build()); })).onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build())); } @GetMapping("/routes/{id}/combinedfilters") public Mono<HashMap<String, Object>> combinedfilters(@PathVariable String id) { // TODO: missing global filters return this.routeLocator.getRoutes() .filter(route -> route.getId().equals(id)) .reduce(new HashMap<>(), this::putItem); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\actuate\AbstractGatewayControllerEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
public String getBatchSearchKey() { return batchSearchKey; } public String getBatchSearchKey2() { return batchSearchKey2; } public String getStatus() { return status; } public String getScopeId() { return scopeId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() { return scopeType; }
public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isCompleted() { return completed; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchPartQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class WFNodeTransition { @NonNull WFNodeTransitionId id; @NonNull ClientId clientId; @NonNull WFNodeId nextNodeId; boolean stdUserWorkflow; @NonNull WFNodeSplitType fromSplitType; @Nullable String description; int seqNo; @NonNull ImmutableList<WFNodeTransitionCondition> conditions; public boolean isMatchingClientId(@NonNull final ClientId clientIdToMatch) { return clientId.isSystem() || ClientId.equals(clientId, clientIdToMatch); } public boolean isUnconditional() { return !isStdUserWorkflow() && getConditions().isEmpty(); } // isUnconditional public BooleanWithReason checkAllowGoingAwayFrom(final WFActivity fromActivity) { if (isStdUserWorkflow()) { final IDocument document = fromActivity.getDocumentOrNull(); if (document != null) { final String docStatus = document.getDocStatus();
final String docAction = document.getDocAction(); if (!IDocument.ACTION_Complete.equals(docAction) || IDocument.STATUS_Completed.equals(docStatus) || IDocument.STATUS_WaitingConfirmation.equals(docStatus) || IDocument.STATUS_WaitingPayment.equals(docStatus) || IDocument.STATUS_Voided.equals(docStatus) || IDocument.STATUS_Closed.equals(docStatus) || IDocument.STATUS_Reversed.equals(docStatus)) { return BooleanWithReason.falseBecause("document state is not valid for a standard workflow transition (docStatus=" + docStatus + ", docAction=" + docAction + ")"); } } } // No Conditions final ImmutableList<WFNodeTransitionCondition> conditions = getConditions(); if (conditions.isEmpty()) { return BooleanWithReason.trueBecause("no conditions"); } // First condition always AND boolean ok = conditions.get(0).evaluate(fromActivity); for (int i = 1; i < conditions.size(); i++) { final WFNodeTransitionCondition condition = conditions.get(i); if (condition.isOr()) { ok = ok || condition.evaluate(fromActivity); } else { ok = ok && condition.evaluate(fromActivity); } } // for all conditions return ok ? BooleanWithReason.trueBecause("transition conditions matched") : BooleanWithReason.falseBecause("transition conditions NOT matched"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFNodeTransition.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public Book title(String title) { this.title = title; return this; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public Book author(String author) { this.author = author; return this; } public void setAuthor(String author) { this.author = author; } public LocalDate getPublished() { return published; } public Book published(LocalDate published) { this.published = published; return this; } public void setPublished(LocalDate published) { this.published = published; } public Integer getQuantity() { return quantity; } public Book quantity(Integer quantity) { this.quantity = quantity; return this; } public void setQuantity(Integer quantity) { this.quantity = quantity;
} public Double getPrice() { return price; } public Book price(Double price) { this.price = price; return this; } public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; if (book.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), book.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "Book{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\Book.java
1
请完成以下Java代码
public ResourceOptionsDto availableOperations(UriInfo context) { UriBuilder baseUriBuilder = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(TenantRestService.PATH); ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); // GET / URI baseUri = baseUriBuilder.build(); resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); // GET /count URI countUri = baseUriBuilder.clone().path("/count").build(); resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) { URI createUri = baseUriBuilder.clone().path("/create").build(); resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); } return resourceOptionsDto; } protected IdentityService getIdentityService() { return getProcessEngine().getIdentityService(); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\TenantRestServiceImpl.java
1
请完成以下Java代码
public void passOutputVariables(final ActivityExecution execution, final VariableScope subInstance) { // only data. no control flow available on this execution. VariableMap variables = filterVariables(getOutputVariables(subInstance)); VariableMap localVariables = getOutputVariablesLocal(subInstance); execution.setVariables(variables); execution.setVariablesLocal(localVariables); final DelegateVariableMapping varMapping = resolveDelegation(execution); if (varMapping != null) { invokeVarMappingDelegation(new DelegateInvocation(execution, null) { @Override protected void invoke() throws Exception { varMapping.mapOutputVariables(execution, subInstance); } }); } } protected void invokeVarMappingDelegation(DelegateInvocation delegation) { try { Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(delegation); } catch (Exception ex) { throw new ProcessEngineException(ex); } } protected VariableMap filterVariables(VariableMap variables) { if (variables != null) { for (String key : variablesFilter) { variables.remove(key); } } return variables; } @Override public void completed(ActivityExecution execution) throws Exception { // only control flow. no sub instance data available leave(execution); } public CallableElement getCallableElement() { return callableElement; } public void setCallableElement(CallableElement callableElement) {
this.callableElement = callableElement; } protected String getBusinessKey(ActivityExecution execution) { return getCallableElement().getBusinessKey(execution); } protected VariableMap getInputVariables(ActivityExecution callingExecution) { return getCallableElement().getInputVariables(callingExecution); } protected VariableMap getOutputVariables(VariableScope calledElementScope) { return getCallableElement().getOutputVariables(calledElementScope); } protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) { return getCallableElement().getOutputVariablesLocal(calledElementScope); } protected Integer getVersion(ActivityExecution execution) { return getCallableElement().getVersion(execution); } protected String getDeploymentId(ActivityExecution execution) { return getCallableElement().getDeploymentId(); } protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding(); } protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java
1
请完成以下Java代码
public List<EventSubscriptionEntity> findConditionalStartEventSubscriptionByTenantId(String tenantId) { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("tenantId", tenantId); configureParameterizedQuery(parameters); return getDbEntityManager().selectList("selectConditionalStartEventSubscriptionByTenantId", parameters); } /** * @return the conditional start event subscriptions (from any tenant) * */ @SuppressWarnings("unchecked") public List<EventSubscriptionEntity> findConditionalStartEventSubscription() { ListQueryParameterObject parameter = new ListQueryParameterObject(); configurParameterObject(parameter); return getDbEntityManager().selectList("selectConditionalStartEventSubscription", parameter); } protected void configurParameterObject(ListQueryParameterObject parameter) { getAuthorizationManager().configureConditionalEventSubscriptionQuery(parameter); getTenantManager().configureQuery(parameter); }
protected void configureQuery(EventSubscriptionQueryImpl query) { getAuthorizationManager().configureEventSubscriptionQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } protected boolean matchesSubscription(EventSubscriptionEntity subscription, String type, String eventName) { EnsureUtil.ensureNotNull("event type", type); String subscriptionEventName = subscription.getEventName(); return type.equals(subscription.getEventType()) && ((eventName == null && subscriptionEventName == null) || (eventName != null && eventName.equals(subscriptionEventName))); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionManager.java
1
请在Spring Boot框架中完成以下Java代码
public class Item { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "name") private String itemName; @Column(name = "price") private double itemPrice; @Column(name = "item_type") @Enumerated(EnumType.STRING) private ItemType itemType; @Temporal(TemporalType.TIMESTAMP) @Column(name = "created_on") private Date createdOn; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "seller_id") private Seller seller; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public double getItemPrice() { return itemPrice; } public void setItemPrice(double itemPrice) { this.itemPrice = itemPrice; } public ItemType getItemType() { return itemType; } public void setItemType(ItemType itemType) { this.itemType = itemType; } public Date getCreatedOn() {
return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public Seller getSeller() { return seller; } public void setSeller(Seller seller) { this.seller = seller; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return id == item.id && Double.compare(item.itemPrice, itemPrice) == 0 && Objects.equals(itemName, item.itemName) && itemType == item.itemType && Objects.equals(createdOn, item.createdOn) && Objects.equals(seller, item.seller); } @Override public int hashCode() { return Objects.hash(id, itemName, itemPrice, itemType, createdOn, seller); } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkeyjoincolumn\Item.java
2
请在Spring Boot框架中完成以下Java代码
public Boolean getFinished() { return finished; } public void setFinished(Boolean finished) { this.finished = finished; } public String getTaskAssignee() { return taskAssignee; } public void setTaskAssignee(String taskAssignee) { this.taskAssignee = taskAssignee; } public String getTaskCompletedBy() { return taskCompletedBy; } public void setTaskCompletedBy(String taskCompletedBy) { this.taskCompletedBy = taskCompletedBy; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike;
} public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(Set<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ActivityInstanceQueryRequest.java
2
请完成以下Java代码
private List<I_C_Print_Job_Detail> createPrintJobDetails(final I_C_Print_Job_Line printJobLine, final I_C_Printing_Queue item) { final List<I_AD_PrinterRouting> printerRoutings = findPrinterRoutings(item); Check.errorIf(printerRoutings.isEmpty(), "Found no AD_PrinterRouting record(s) for C_Printing_Queue {}", item); if (printerRoutings.isEmpty()) { return Collections.emptyList(); // just for the case that we configured Check not to throw an exception } final List<I_C_Print_Job_Detail> printJobDetails = new ArrayList<>(printerRoutings.size()); for (final I_AD_PrinterRouting printerRouting : printerRoutings) { Check.assumeNotNull(printerRouting, "AD_PrinterRouting {} found for C_Printing_Queue {}", printerRouting, item); final I_C_Print_Job_Detail printJobDetail = createPrintJobDetail(printJobLine, printerRouting); if (printJobDetail != null) { printJobDetails.add(printJobDetail); } } return printJobDetails; } private I_C_Print_Job_Detail createPrintJobDetail( final I_C_Print_Job_Line printJobLine, final I_AD_PrinterRouting routing) { final I_C_Print_Job_Detail printJobDetail = InterfaceWrapperHelper.newInstance(I_C_Print_Job_Detail.class, printJobLine); printJobDetail.setAD_Org_ID(printJobLine.getAD_Org_ID()); printJobDetail.setIsActive(true); printJobDetail.setAD_PrinterRouting_ID(routing.getAD_PrinterRouting_ID()); printJobDetail.setC_Print_Job_Line(printJobLine); InterfaceWrapperHelper.save(printJobDetail); return printJobDetail;
} private List<I_AD_PrinterRouting> findPrinterRoutings(final I_C_Printing_Queue item) { final PrinterRoutingsQuery query = printingQueueBL.createPrinterRoutingsQueryForItem(item); final List<de.metas.adempiere.model.I_AD_PrinterRouting> rs = printerRoutingDAO.fetchPrinterRoutings(query); return InterfaceWrapperHelper.createList(rs, I_AD_PrinterRouting.class); } @Override public String getSummary(final I_C_Print_Job printJob) { final Properties ctx = InterfaceWrapperHelper.getCtx(printJob); return Services.get(IMsgBL.class).translate(ctx, I_C_Print_Job.COLUMNNAME_C_Print_Job_ID) + " " + printJob.getC_Print_Job_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintJobBL.java
1
请完成以下Java代码
private void enqueueAllForReposting() { boolean tryAgain; do { final int chunkSize = getRetrieveChunkSize(); final List<AccountingDocToRepost> docsToRepost = accountingDocsToRepostDBTableRepository.retrieve(chunkSize); if (docsToRepost.isEmpty()) { return; } logger.info("Enqueueing for reposting {} documents: {}", docsToRepost.size(), docsToRepost); final Stopwatch stopwatch = Stopwatch.createStarted(); try { postingService.schedule(toDocumentPostMultiRequest(docsToRepost)); } catch (Exception ex) { logger.warn("Failed enqueueing {}", docsToRepost, ex); } finally { accountingDocsToRepostDBTableRepository.delete(docsToRepost); } tryAgain = docsToRepost.size() >= chunkSize; stopwatch.stop(); logger.info("Done enqueueing {} documents in {} (tryAgain={})", docsToRepost.size(), stopwatch, tryAgain); } while (tryAgain); } private static DocumentPostMultiRequest toDocumentPostMultiRequest(final List<AccountingDocToRepost> docsToRepost) { return DocumentPostMultiRequest.ofNonEmptyCollection( docsToRepost.stream() .map(AccountingDocsToRepostDBTableWatcher::toDocumentPostRequest)
.collect(ImmutableSet.toImmutableSet()) ); } private static DocumentPostRequest toDocumentPostRequest(@NonNull final AccountingDocToRepost docToRepost) { return DocumentPostRequest.builder() .record(docToRepost.getRecordRef()) .clientId(docToRepost.getClientId()) .force(docToRepost.isForce()) .onErrorNotifyUserId(docToRepost.getOnErrorNotifyUserId()) .build(); } private Duration getPollInterval() { final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1); return pollIntervalInSeconds > 0 ? Duration.ofSeconds(pollIntervalInSeconds) : DEFAULT_PollInterval; } private int getRetrieveChunkSize() { final int retrieveChunkSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveChunkSize, -1); return retrieveChunkSize > 0 ? retrieveChunkSize : DEFAULT_RetrieveChunkSize; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\posting\server\accouting_docs_to_repost_db_table\AccountingDocsToRepostDBTableWatcher.java
1
请完成以下Java代码
public void setDateLastAlert( @NonNull final WFActivityId activityId, @NonNull final Instant dateLastAlert) { final I_AD_WF_Activity activity = InterfaceWrapperHelper.loadOutOfTrx(activityId, I_AD_WF_Activity.class); activity.setDateLastAlert(TimeUtil.asTimestamp(dateLastAlert)); InterfaceWrapperHelper.save(activity); } /** * @return activity summary */ @Nullable public String getActiveInfo(final int AD_Table_ID, final int Record_ID) { final ImmutableList<I_AD_WF_Activity> activities = getActiveActivities(AD_Table_ID, Record_ID); if (activities.isEmpty()) { return null; } return activities.stream() .map(this::toStringX) .collect(Collectors.joining("\n")); } private String toStringX(final I_AD_WF_Activity activity) { final StringBuilder sb = new StringBuilder(); sb.append(WFState.ofCode(activity.getWFState())).append(": ").append(getActivityName(activity).getDefaultValue()); final UserId userId = UserId.ofRepoIdOrNullIfSystem(activity.getAD_User_ID()); if (userId != null) { final IUserDAO userDAO = Services.get(IUserDAO.class); final String userFullname = userDAO.retrieveUserFullName(userId); sb.append(" (").append(userFullname).append(")"); }
return sb.toString(); } private ITranslatableString getActivityName(@NonNull final I_AD_WF_Activity activity) { final IADWorkflowDAO workflowDAO = Services.get(IADWorkflowDAO.class); final WorkflowId workflowId = WorkflowId.ofRepoId(activity.getAD_Workflow_ID()); final WFNodeId wfNodeId = WFNodeId.ofRepoId(activity.getAD_WF_Node_ID()); return workflowDAO.getWFNodeName(workflowId, wfNodeId); } private ImmutableList<I_AD_WF_Activity> getActiveActivities(final int AD_Table_ID, final int Record_ID) { return queryBL.createQueryBuilderOutOfTrx(I_AD_WF_Activity.class) .addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_AD_Table_ID, AD_Table_ID) .addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_AD_Table_ID, Record_ID) .addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_Processed, false) .orderBy(I_AD_WF_Activity.COLUMNNAME_AD_WF_Activity_ID) .create() .listImmutable(I_AD_WF_Activity.class); } public List<WFProcessId> getActiveProcessIds(final TableRecordReference documentRef) { return queryBL.createQueryBuilderOutOfTrx(I_AD_WF_Process.class) .addEqualsFilter(I_AD_WF_Process.COLUMNNAME_AD_Table_ID, documentRef.getAD_Table_ID()) .addEqualsFilter(I_AD_WF_Process.COLUMNNAME_Record_ID, documentRef.getRecord_ID()) .addEqualsFilter(I_AD_WF_Process.COLUMNNAME_Processed, false) .create() .listDistinct(I_AD_WF_Process.COLUMNNAME_AD_WF_Process_ID, WFProcessId.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFProcessRepository.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("internalName", internalName) .add("layoutType", layoutType) .add("elementsLines-count", elementLinesBuilders.size()) .toString(); } public DocumentLayoutElementGroupDescriptor build() { final DocumentLayoutElementGroupDescriptor result = new DocumentLayoutElementGroupDescriptor(this); logger.trace("Built {} for {}", result, this); return result; } private List<DocumentLayoutElementLineDescriptor> buildElementLines() { return elementLinesBuilders .stream() .map(elementLinesBuilder -> elementLinesBuilder.build()) .collect(GuavaCollectors.toImmutableList()); } public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder setLayoutType(final LayoutType layoutType) { this.layoutType = layoutType; return this; } public Builder setLayoutType(final String layoutTypeStr) { layoutType = LayoutType.fromNullable(layoutTypeStr); return this; }
public Builder setColumnCount(final int columnCount) { this.columnCount = CoalesceUtil.firstGreaterThanZero(columnCount, 1); return this; } public Builder addElementLine(@NonNull final DocumentLayoutElementLineDescriptor.Builder elementLineBuilder) { elementLinesBuilders.add(elementLineBuilder); return this; } public Builder addElementLines(@NonNull final List<DocumentLayoutElementLineDescriptor.Builder> elementLineBuilders) { elementLinesBuilders.addAll(elementLineBuilders); return this; } public boolean hasElementLines() { return !elementLinesBuilders.isEmpty(); } public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return elementLinesBuilders.stream().flatMap(DocumentLayoutElementLineDescriptor.Builder::streamElementBuilders); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementGroupDescriptor.java
1
请完成以下Java代码
public static ExecutableScript parseCamundaScript(Element scriptElement) { String scriptLanguage = scriptElement.attribute("scriptFormat"); if (scriptLanguage == null || scriptLanguage.isEmpty()) { throw new BpmnParseException("Missing attribute 'scriptFormat' for 'script' element", scriptElement); } else { String scriptResource = scriptElement.attribute("resource"); String scriptSource = scriptElement.getText(); try { return ScriptUtil.getScript(scriptLanguage, scriptSource, scriptResource, getExpressionManager()); } catch (ProcessEngineException e) { throw new BpmnParseException("Unable to process script", scriptElement, e); } } } public static Map<String, String> parseCamundaExtensionProperties(Element element){ Element propertiesElement = findCamundaExtensionElement(element, "properties"); if(propertiesElement != null) {
List<Element> properties = propertiesElement.elementsNS(BpmnParse.CAMUNDA_BPMN_EXTENSIONS_NS, "property"); Map<String, String> propertiesMap = new HashMap<>(); for (Element property : properties) { propertiesMap.put(property.attribute("name"), property.attribute("value")); } return propertiesMap; } return null; } protected static ExpressionManager getExpressionManager() { return Context.getProcessEngineConfiguration().getExpressionManager(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\BpmnParseUtil.java
1
请完成以下Java代码
final List<Map.Entry<K, Float>> queryNearest(String query, int size) { if (query == null || query.length() == 0) { return Collections.emptyList(); } try { return nearest(query(query), size); } catch (Exception e) { return Collections.emptyList(); } } /** * 查询抽象文本对应的向量。此方法应当保证返回单位向量。 * * @param query * @return */ public abstract Vector query(String query); /** * 模型中的词向量总数(词表大小) * * @return */ public int size() { return storage.size(); } /** * 模型中的词向量维度 * * @return
*/ public int dimension() { if (storage == null || storage.isEmpty()) { return 0; } return storage.values().iterator().next().size(); } /** * 删除元素 * * @param key * @return */ public Vector remove(K key) { return storage.remove(key); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractVectorModel.java
1
请完成以下Java代码
public class RecurringAuto extends JavaProcess { @Override protected String doIt() throws Exception { final String result = recurringRun(getAD_Client_ID(), get_TrxName()); return result; } @Override protected void prepare() { // Nothing to to } String recurringRun(final int adClientId, final String trxName) { int count = 0; int thisTime = 0; while ((thisTime = run(adClientId, trxName)) != 0) { count += thisTime; } return "Performed " + count + " recurring runs"; }
private int run(final int adClientId, final String trxName) { final IRecurringPA recurringPA = Services.get(IRecurringPA.class); final IRecurringBL recurringBL = Services.get(IRecurringBL.class); // get recurring docs that need to run today. final Collection<I_C_Recurring> recurringDocs = recurringPA .retrieveForToday(adClientId, trxName); for (final I_C_Recurring recurring : recurringDocs) { recurringBL.recurringRun(recurring); } return recurringDocs.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\process\RecurringAuto.java
1
请完成以下Java代码
public abstract class PackageablesViewBasedProcess extends ViewBasedProcessTemplate implements IProcessPrecondition { @Override protected abstract ProcessPreconditionsResolution checkPreconditionsApplicable(); protected final ProcessPreconditionsResolution checkPreconditionsApplicable_SingleSelectedRow() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (!selectedRowIds.isSingleDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected final PackageableView getView() { return PackageableView.cast(super.getView()); } @Override protected final PackageableRow getSingleSelectedRow() { return PackageableRow.cast(super.getSingleSelectedRow()); }
@Override protected final Stream<PackageableRow> streamSelectedRows() { return super.streamSelectedRows() .map(PackageableRow::cast); } protected final ShipmentScheduleLockRequest createLockRequest(final PackageableRow row) { return ShipmentScheduleLockRequest.builder() .shipmentScheduleIds(row.getShipmentScheduleIds()) .lockType(ShipmentScheduleLockType.PICKING) .lockedBy(getLoggedUserId()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesViewBasedProcess.java
1
请完成以下Java代码
public class SEPADocumentDAO implements ISEPADocumentDAO { private final IQueryBL queryBL = Services.get(IQueryBL.class); @Override public I_C_BP_BankAccount retrieveSEPABankAccount(I_C_BPartner bPartner) { final Properties ctx = InterfaceWrapperHelper.getCtx(bPartner); final String trxName = InterfaceWrapperHelper.getTrxName(bPartner); final String whereClause = I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID + "=?"; final List<Object> params = new ArrayList<>(); params.add(bPartner.getC_BPartner_ID()); return new Query(ctx, I_C_BP_BankAccount.Table_Name, whereClause, trxName) .setParameters(params) .setOrderBy(I_C_BP_BankAccount.COLUMNNAME_IsDefault + " DESC") .setOnlyActiveRecords(true) .first(I_C_BP_BankAccount.class); } @Override public List<I_SEPA_Export_Line> retrieveLines(@NonNull final I_SEPA_Export doc) { return queryBL.createQueryBuilder(I_SEPA_Export_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_SEPA_Export_Line.COLUMNNAME_IsError, false) .addEqualsFilter(I_SEPA_Export_Line.COLUMNNAME_SEPA_Export_ID, doc.getSEPA_Export_ID()) .orderBy()
.addColumn(I_SEPA_Export_Line.COLUMNNAME_C_Currency_ID) .addColumn(I_SEPA_Export_Line.COLUMNNAME_SEPA_Export_Line_ID).endOrderBy() .create() .list(); } @Override public List<I_SEPA_Export_Line> retrieveLinesChangeRule(Properties ctx, String trxName) { // // Placeholder for future functionality. return Collections.emptyList(); } @NonNull public List<I_SEPA_Export_Line_Ref> retrieveLineReferences(@NonNull final I_SEPA_Export_Line line) { return toLineRefSqlQuery(line) .list(); } @NonNull private IQuery<I_SEPA_Export_Line_Ref> toLineRefSqlQuery(@NonNull final I_SEPA_Export_Line line) { return queryBL.createQueryBuilder(I_SEPA_Export_Line_Ref.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_SEPA_Export_Line_Ref.COLUMNNAME_SEPA_Export_Line_ID, line.getSEPA_Export_Line_ID()) .addEqualsFilter(I_SEPA_Export_Line_Ref.COLUMNNAME_SEPA_Export_ID, line.getSEPA_Export_ID()) .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\SEPADocumentDAO.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { JDIExampleDebugger debuggerInstance = new JDIExampleDebugger(); debuggerInstance.setDebugClass(JDIExampleDebuggee.class); int[] breakPoints = {6, 9}; debuggerInstance.setBreakPointLines(breakPoints); VirtualMachine vm = null; try { vm = debuggerInstance.connectAndLaunchVM(); debuggerInstance.enableClassPrepareRequest(vm); EventSet eventSet = null; while ((eventSet = vm.eventQueue().remove()) != null) { for (Event event : eventSet) { if (event instanceof ClassPrepareEvent) { debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event); } if (event instanceof BreakpointEvent) { event.request().disable(); debuggerInstance.displayVariables((BreakpointEvent) event); debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event); } if (event instanceof StepEvent) { debuggerInstance.displayVariables((StepEvent) event); } vm.resume();
} } } catch (VMDisconnectedException e) { System.out.println("Virtual Machine is disconnected."); } catch (Exception e) { e.printStackTrace(); } finally { InputStreamReader reader = new InputStreamReader(vm.process().getInputStream()); OutputStreamWriter writer = new OutputStreamWriter(System.out); char[] buf = new char[512]; reader.read(buf); writer.write(buf); writer.flush(); } } }
repos\tutorials-master\java-jdi\src\main\java\com\baeldung\jdi\JDIExampleDebugger.java
1
请完成以下Java代码
public JSONMenuNode build() { final MutableInt maxLeafNodes = new MutableInt(this.maxLeafNodes); return newInstanceOrNull(node, maxDepth, maxChildrenPerNode, maxLeafNodes, menuNodeFavoriteProvider); } public Builder setMaxDepth(final int maxDepth) { this.maxDepth = maxDepth > 0 ? maxDepth : Integer.MAX_VALUE; return this; } public Builder setMaxChildrenPerNode(final int maxChildrenPerNode) { this.maxChildrenPerNode = maxChildrenPerNode > 0 ? maxChildrenPerNode : Integer.MAX_VALUE; return this;
} public Builder setMaxLeafNodes(final int maxLeafNodes) { this.maxLeafNodes = maxLeafNodes > 0 ? maxLeafNodes : Integer.MAX_VALUE; return this; } public Builder setIsFavoriteProvider(final MenuNodeFavoriteProvider menuNodeFavoriteProvider) { this.menuNodeFavoriteProvider = menuNodeFavoriteProvider; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\datatypes\json\JSONMenuNode.java
1
请完成以下Java代码
public class M_ReceiptSchedule { @Init public void init() { Services.get(IHUAssignmentBL.class) .registerHUAssignmentListener(ReceiptScheduleHUAssignmentListener.instance); } /** * After deleting a receipt schedule, destroy it's HUs, which are no longer valid * * @param rs */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void onReceiptScheduleDelete(final I_M_ReceiptSchedule rs) { Check.assumeNotNull(rs, "Receipt schedule is null", rs); // List containing all the allocations for the give receipt schedule (including the ones without HU final List<I_M_ReceiptSchedule_Alloc> allocations = Services.get(IReceiptScheduleDAO.class).retrieveRsaForRs(rs); final String trxName = InterfaceWrapperHelper.getTrxName(rs);
// 07232 // Remove the assigned handling units // List of handling units receipt schedule allocations. // This is where we take the hus from and we mark them as destroyed final List<de.metas.handlingunits.model.I_M_ReceiptSchedule_Alloc> huAllocs = Services.get(IHUReceiptScheduleDAO.class).retrieveAllHandlingUnitAllocations(rs, trxName); Services.get(IHUReceiptScheduleBL.class).destroyHandlingUnits(huAllocs, trxName); // Finally, delete all the allocations ((hu or not hu) for (final I_M_ReceiptSchedule_Alloc alloc : allocations) { InterfaceWrapperHelper.delete(alloc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\model\validator\M_ReceiptSchedule.java
1
请完成以下Java代码
public void deletePurchaseCandidates(@NonNull final DeletePurchaseCandidateQuery deletePurchaseCandidateQuery) { final IQueryBuilder<I_C_PurchaseCandidate> deleteQuery = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class); if (deletePurchaseCandidateQuery.isOnlySimulated()) { deleteQuery.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_IsSimulated, deletePurchaseCandidateQuery.isOnlySimulated()); } if (deletePurchaseCandidateQuery.getSalesOrderLineId() != null) { deleteQuery.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_C_OrderLineSO_ID, deletePurchaseCandidateQuery.getSalesOrderLineId()); } if (deleteQuery.getCompositeFilter().isEmpty()) { throw new AdempiereException("Deleting all I_C_PurchaseCandidate records is not allowed!"); } deleteQuery .create() .deleteDirectly(); } @NonNull private IQuery<I_C_PurchaseCandidate> toSqlQuery(@NonNull final PurchaseCandidateQuery query) { final IQueryBuilder<I_C_PurchaseCandidate> queryBuilder = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class) .addOnlyActiveRecordsFilter(); if (query.getExternalSystemType() != null) { final ExternalSystemId externalSystemId = externalSystemRepository.getIdByType(query.getExternalSystemType());
queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_ExternalSystem_ID, externalSystemId); } if (query.getExternalHeaderId() != null) { queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMN_ExternalHeaderId, query.getExternalHeaderId()); } if (query.getExternalLineId() != null) { queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_ExternalLineId, query.getExternalLineId()); } return queryBuilder .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidateRepository.java
1
请在Spring Boot框架中完成以下Java代码
public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService( T userDetailsService) { return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder); } } static class LazyPasswordEncoder implements PasswordEncoder { private ApplicationContext applicationContext; private PasswordEncoder passwordEncoder; LazyPasswordEncoder(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public String encode(CharSequence rawPassword) { return getPasswordEncoder().encode(rawPassword); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return getPasswordEncoder().matches(rawPassword, encodedPassword); } @Override public boolean upgradeEncoding(String encodedPassword) { return getPasswordEncoder().upgradeEncoding(encodedPassword); }
private PasswordEncoder getPasswordEncoder() { if (this.passwordEncoder != null) { return this.passwordEncoder; } this.passwordEncoder = this.applicationContext.getBeanProvider(PasswordEncoder.class) .getIfUnique(PasswordEncoderFactories::createDelegatingPasswordEncoder); return this.passwordEncoder; } @Override public String toString() { return getPasswordEncoder().toString(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configuration\AuthenticationConfiguration.java
2
请完成以下Java代码
public boolean updateNode(String path, String data) { try { //The data version of zk starts counting from 0. If the client passes -1, it means that the zk server needs to be updated based on the latest data. If there is no atomicity requirement for the update operation of zk's data node, you can use -1. //The version parameter specifies the version of the data to be updated. If the version is different from the real version, the update operation will fail. Specify version as -1 to ignore the version check. zkClient.setData(path, data.getBytes(), -1); return true; } catch (Exception e) { log.error("【update persist node exception】{},{},{}", path, data, e); return false; } } /** * delete persist node * * @param path */ public boolean deleteNode(String path) { try { //The version parameter specifies the version of the data to be updated. If the version is different from the real version, the update operation will fail. Specify version as -1 to ignore the version check. zkClient.delete(path, -1); return true; } catch (Exception e) { log.error("【delete persist node exception】{},{}", path, e); return false; } } /** * Get the child nodes of the current node (excluding grandchild nodes) * * @param path */ public List<String> getChildren(String path) throws KeeperException, InterruptedException { List<String> list = zkClient.getChildren(path, false);
return list; } /** * Get the value of the specified node * * @param path * @return */ public String getData(String path, Watcher watcher) { try { Stat stat = new Stat(); byte[] bytes = zkClient.getData(path, watcher, stat); return new String(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } }
repos\springboot-demo-master\zookeeper\src\main\java\com\et\zookeeper\api\ZkApi.java
1
请完成以下Java代码
private List<I_M_HU_PI_Item> getAvailableLUPIItems() { final HUEditorRow tuRow = getSelectedRow(); final I_M_HU tuHU = tuRow.getM_HU(); final I_M_HU_PI_Version effectivePIVersion = handlingUnitsBL.getEffectivePIVersion(tuHU); Check.errorIf(effectivePIVersion == null, "tuHU is inconsistent; hu={}", tuHU); return handlingUnitsDAO.retrieveParentPIItemsForParentPI( effectivePIVersion.getM_HU_PI(), null, IHandlingUnitsBL.extractBPartnerIdOrNull(tuHU)); } public boolean getShowWarehouseFlag() { final ActionType currentActionType = getActionType(); if (currentActionType == null) { return false; } final boolean isMoveToWarehouseAllowed = _isMoveToDifferentWarehouseEnabled && statusBL.isStatusActive(getSelectedRow().getM_HU()); if (!isMoveToWarehouseAllowed) {
return false; } final boolean showWarehouse; switch (currentActionType) { case CU_To_NewCU: case CU_To_NewTUs: case TU_To_NewLUs: case TU_To_NewTUs: showWarehouse = true; break; default: showWarehouse = false; } return showWarehouse; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WebuiHUTransformParametersFiller.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.getSelectionSize().isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override @RunOutOfTrx // we update each shipment sched within its own little trx, to avoid blocking on DB level protected String doIt() throws Exception { final IQueryFilter<I_M_ShipmentSchedule> queryFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final ShipmentScheduleUserChangeRequestBuilder builder = ShipmentScheduleUserChangeRequest.builder().bestBeforeDate(p_bestBeforeDate); final IQueryFilter<I_M_ShipmentSchedule> notLockedFilter = lockManager.getNotLockedFilter(I_M_ShipmentSchedule.class); // get the selected shipment schedule IDs final Iterator<ShipmentScheduleId> ids = queryBL .createQueryBuilder(I_M_ShipmentSchedule.class) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule.COLUMN_Processed, false) .filter(queryFilter) .filter(notLockedFilter) .create() .iterateIds(ShipmentScheduleId::ofRepoId); // update them one by one while (ids.hasNext()) { final ShipmentScheduleUserChangeRequest singleRequest = builder.shipmentScheduleId(ids.next()).build(); final ShipmentScheduleUserChangeRequestsList userChanges = ShipmentScheduleUserChangeRequestsList.of(ImmutableList.of(singleRequest)); shipmentScheduleBL.applyUserChangesInTrx(userChanges); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_Set_BestBeforeDate.java
1
请完成以下Java代码
public final DefaultPaymentBuilder externalId(@Nullable final ExternalId externalId) { assertNotBuilt(); if (externalId != null) { payment.setExternalId(externalId.getValue()); } return this; } public final DefaultPaymentBuilder orderId(@Nullable final OrderId orderId) { assertNotBuilt(); if (orderId != null) { payment.setC_Order_ID(orderId.getRepoId()); } return this; } public final DefaultPaymentBuilder orderExternalId(@Nullable final String orderExternalId) { assertNotBuilt(); if (Check.isNotBlank(orderExternalId)) { payment.setExternalOrderId(orderExternalId); } return this; } public final DefaultPaymentBuilder isAutoAllocateAvailableAmt(final boolean isAutoAllocateAvailableAmt) { assertNotBuilt();
payment.setIsAutoAllocateAvailableAmt(isAutoAllocateAvailableAmt); return this; } private DefaultPaymentBuilder fromOrder(@NonNull final I_C_Order order) { adOrgId(OrgId.ofRepoId(order.getAD_Org_ID())); orderId(OrderId.ofRepoId(order.getC_Order_ID())); bpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID())); currencyId(CurrencyId.ofRepoId(order.getC_Currency_ID())); final SOTrx soTrx = SOTrx.ofBoolean(order.isSOTrx()); direction(PaymentDirection.ofSOTrxAndCreditMemo(soTrx, false)); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\DefaultPaymentBuilder.java
1
请完成以下Java代码
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override
public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请完成以下Java代码
public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM) { set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM); } @Override public BigDecimal getQtyDeliveredInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyEntered (final BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM) { set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM); } @Override public BigDecimal getQtyInvoicedInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderSummary.java
1
请在Spring Boot框架中完成以下Java代码
public class DataSource1Config { @Bean(name = "oneDataSource") @ConfigurationProperties(prefix = "spring.datasource.one") @Primary public DataSource testDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "oneSqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/one/*.xml")); return bean.getObject();
} @Bean(name = "oneTransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("oneDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "oneSqlSessionTemplate") @Primary public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-multi-mybatis-xml\src\main\java\com\neo\datasource\DataSource1Config.java
2
请完成以下Java代码
private Component editCellAt(MouseEvent e) { if (m_vtable == null) { return null; } final Point p = e.getPoint(); final boolean canEdit = !m_vtable.isEditing() || m_vtable.getCellEditor().stopCellEditing(); if (canEdit && m_vtable.editCellAt(m_vtable.rowAtPoint(p), m_vtable.columnAtPoint(p))) { Component editor = m_vtable.getEditorComponent(); editor.dispatchEvent(e); return editor; } return null; } private EditorContextPopupMenu getContextMenu(final TableCellEditor cellEditor, final int rowIndexView, final int columnIndexView) { if (m_vtable == null) { // VTable not set yet ?!
return null; } final Object value = m_vtable.getValueAt(rowIndexView, columnIndexView); final Component component = cellEditor.getTableCellEditorComponent(m_vtable, value, true, rowIndexView, columnIndexView); // isSelected=true if (component == null) { // It seems there is no editor for given cell (e.g. one reason could be the cell is not actually displayed) return null; } if (!(component instanceof VEditor)) { return null; } final VEditor editor = (VEditor)component; final IContextMenuActionContext menuCtx = Services.get(IContextMenuProvider.class).createContext(editor, m_vtable, rowIndexView, columnIndexView); final EditorContextPopupMenu contextMenu = new EditorContextPopupMenu(menuCtx); return contextMenu; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VTableMouseListener.java
1
请完成以下Java代码
private static CallOrderDetail ofRecord(@NonNull final I_C_CallOrderDetail record) { return CallOrderDetail.builder() .detailId(CallOrderDetailId.ofRepoId(record.getC_CallOrderDetail_ID())) .detailData(ofRecordData(record)) .build(); } @NonNull private static CallOrderDetailData ofRecordData(@NonNull final I_C_CallOrderDetail record) { final CallOrderDetailData.CallOrderDetailDataBuilder builder = CallOrderDetailData.builder() .summaryId(CallOrderSummaryId.ofRepoId(record.getC_CallOrderSummary_ID())); final UomId uomId = UomId.ofRepoId(record.getC_UOM_ID()); if (record.getC_OrderLine_ID() > 0) { final Quantity qtyEntered = Quantitys.of(record.getQtyEntered(), uomId); return builder .orderId(OrderId.ofRepoIdOrNull(record.getC_Order_ID())) .orderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLine_ID())) .qtyEntered(qtyEntered) .build(); } else if (record.getM_InOutLine_ID() > 0) { final Quantity qtyDeliveredInUOM = Quantitys.of(record.getQtyDeliveredInUOM(), uomId); return builder .shipmentId(InOutId.ofRepoIdOrNull(record.getM_InOut_ID())) .shipmentLineId(InOutLineId.ofRepoIdOrNull(record.getM_InOutLine_ID())) .qtyDelivered(qtyDeliveredInUOM) .build(); } else if (record.getC_InvoiceLine_ID() > 0)
{ final Quantity qtyInvoicedInUOM = Quantitys.of(record.getQtyInvoicedInUOM(), uomId); return builder .invoiceId(InvoiceId.ofRepoIdOrNull(record.getC_Invoice_ID())) .invoiceAndLineId(InvoiceAndLineId.ofRepoIdOrNull(record.getC_Invoice_ID(), record.getC_InvoiceLine_ID())) .qtyInvoiced(qtyInvoicedInUOM) .build(); } else { throw new AdempiereException("Detail with no reference document is not supported!") .appendParametersToMessage() .setParameter("C_CallOrderDetail_ID", record.getC_CallOrderDetail_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\CallOrderDetailRepo.java
1
请完成以下Java代码
public static BasicConnectionPool create(String url, String user, String password) throws SQLException { List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE); for (int i = 0; i < INITIAL_POOL_SIZE; i++) { pool.add(createConnection(url, user, password)); } return new BasicConnectionPool(url, user, password, pool); } private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) { this.url = url; this.user = user; this.password = password; this.connectionPool = connectionPool; } @Override public Connection getConnection() throws SQLException { if (connectionPool.isEmpty()) { if (usedConnections.size() < MAX_POOL_SIZE) { connectionPool.add(createConnection(url, user, password)); } else { throw new RuntimeException("Maximum pool size reached, no available connections!"); } } Connection connection = connectionPool.remove(connectionPool.size() - 1); if(!connection.isValid(MAX_TIMEOUT)){ connection = createConnection(url, user, password); } usedConnections.add(connection); return connection; } @Override public boolean releaseConnection(Connection connection) { connectionPool.add(connection); return usedConnections.remove(connection); } private static Connection createConnection(String url, String user, String password) throws SQLException { return DriverManager.getConnection(url, user, password); } @Override public int getSize() { return connectionPool.size() + usedConnections.size(); } @Override public List<Connection> getConnectionPool() { return connectionPool; }
@Override public String getUrl() { return url; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } @Override public void shutdown() throws SQLException { usedConnections.forEach(this::releaseConnection); for (Connection c : connectionPool) { c.close(); } connectionPool.clear(); } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\connectionpool\BasicConnectionPool.java
1
请完成以下Java代码
public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPage() { return totalPage; }
public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrPage() { return currPage; } public void setCurrPage(int currPage) { this.currPage = currPage; } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\utils\PageResult.java
1
请在Spring Boot框架中完成以下Java代码
public void persistLabels(@NonNull final IssueId issueId, @NonNull final ImmutableList<IssueLabel> issueLabels) { final ImmutableList<I_S_IssueLabel> newLabels = issueLabels .stream() .map(label -> of(issueId, label)) .collect(ImmutableList.toImmutableList()); final ImmutableList<I_S_IssueLabel> existingLabels = getRecordsByIssueId(issueId); persistLabels(newLabels, existingLabels); } @VisibleForTesting @NonNull ImmutableList<I_S_IssueLabel> getRecordsByIssueId(@NonNull final IssueId issueId) { return queryBL.createQueryBuilder(I_S_IssueLabel.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_IssueLabel.COLUMNNAME_S_Issue_ID, issueId.getRepoId()) .create() .list() .stream() .collect(ImmutableList.toImmutableList()); } @NonNull private I_S_IssueLabel of(@NonNull final IssueId issueId, @NonNull final IssueLabel issueLabel) { final I_S_IssueLabel record = InterfaceWrapperHelper.newInstance(I_S_IssueLabel.class); record.setS_Issue_ID(issueId.getRepoId()); record.setAD_Org_ID(issueLabel.getOrgId().getRepoId()); record.setLabel(issueLabel.getValue()); return record; } private void persistLabels(@NonNull final List<I_S_IssueLabel> newLabels, @NonNull final List<I_S_IssueLabel> existingLabels) { if (Check.isEmpty(newLabels)) {
InterfaceWrapperHelper.deleteAll(existingLabels); return; } final List<I_S_IssueLabel> recordsToInsert = newLabels .stream() .filter(label -> existingLabels .stream() .noneMatch(record -> areEqual(record, label)) ) .collect(Collectors.toList()); final List<I_S_IssueLabel> recordsToDelete = existingLabels .stream() .filter(record -> newLabels .stream() .noneMatch(label -> areEqual(record, label)) ) .collect(Collectors.toList()); InterfaceWrapperHelper.deleteAll(recordsToDelete); InterfaceWrapperHelper.saveAll(recordsToInsert); } private boolean areEqual(@NonNull final I_S_IssueLabel record1, @NonNull final I_S_IssueLabel record2) { return record1.getLabel().equalsIgnoreCase(record2.getLabel()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\external\label\IssueLabelRepository.java
2
请完成以下Java代码
static class ArgumentValueTypeModifier extends TypeModifier { @Override public JavaType modifyType(JavaType type, Type jdkType, TypeBindings context, TypeFactory typeFactory) { Class<?> raw = type.getRawClass(); if (!type.isReferenceType() && !type.isContainerType() && raw == ArgumentValue.class) { JavaType refType = type.containedTypeOrUnknown(0); return ReferenceType.upgradeFrom(type, refType); } else { return type; } } } /** * {@link ReferenceTypeSerializer} that serializes {@link ArgumentValue} values as: * <ul> * <li>the embedded value if it is present and not {@literal null}. * <li>{@literal null} if the embedded value is present and {@literal null}. * <li>an empty value if the embedded value is not present. * </ul> */ static class ArgumentValueSerializer extends ReferenceTypeSerializer<ArgumentValue<?>> { ArgumentValueSerializer(ReferenceType fullType, boolean staticTyping, @Nullable TypeSerializer vts, ValueSerializer<Object> ser) { super(fullType, staticTyping, vts, ser); } ArgumentValueSerializer(ReferenceTypeSerializer<?> base, BeanProperty property, TypeSerializer vts, ValueSerializer<?> valueSer, NameTransformer unwrapper, Object suppressableValue, boolean suppressNulls) { super(base, property, vts, valueSer, unwrapper, suppressableValue, suppressNulls); } @Override protected ReferenceTypeSerializer<ArgumentValue<?>> withResolved(BeanProperty prop, TypeSerializer vts, ValueSerializer<?> valueSer, NameTransformer unwrapper) { return new ArgumentValueSerializer(this, prop, vts, valueSer, unwrapper, _suppressableValue, _suppressNulls); }
@Override public ReferenceTypeSerializer<ArgumentValue<?>> withContentInclusion(final Object suppressableValue, final boolean suppressNulls) { return new ArgumentValueSerializer(this, _property, _valueTypeSerializer, _valueSerializer, _unwrapper, suppressableValue, suppressNulls); } @Override protected boolean _isValuePresent(final ArgumentValue<?> value) { return !value.isOmitted(); } @Override protected @Nullable Object _getReferenced(final ArgumentValue<?> value) { return value.value(); } @Override protected @Nullable Object _getReferencedIfPresent(final ArgumentValue<?> value) { return value.value(); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\json\GraphQlJacksonModule.java
1
请完成以下Java代码
public class M_Inventory_RecomputeCosts extends JavaProcess implements IProcessPrecondition { private final IInventoryDAO inventoryDAO = Services.get(IInventoryDAO.class); private final IAcctSchemaDAO acctSchemaDAO = Services.get(IAcctSchemaDAO.class); private final ICostElementRepository costElementRepository = SpringContextHolder.instance.getBean(ICostElementRepository.class); @Param(parameterName = I_C_AcctSchema.COLUMNNAME_C_AcctSchema_ID, mandatory = true) private AcctSchemaId p_C_AcctSchema_ID; @Param(parameterName = I_C_AcctSchema.COLUMNNAME_CostingMethod, mandatory = false) private CostingMethod p_costingMethod; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final PInstanceId productsSelectionId = createProductsSelection(); final Instant startDate = getStartDate(); getCostElements().forEach(costElement -> recomputeCosts(costElement, productsSelectionId, startDate)); return MSG_OK; } private PInstanceId createProductsSelection() { final Set<ProductId> productIds = inventoryDAO.retrieveUsedProductsByInventoryIds(getSelectedInventoryIds()); if (productIds.isEmpty()) { throw new AdempiereException("No Products"); } return DB.createT_Selection(productIds, ITrx.TRXNAME_ThreadInherited); }
private Set<InventoryId> getSelectedInventoryIds() { return retrieveSelectedRecordsQueryBuilder(I_M_Inventory.class) .create() .listIds() .stream() .map(InventoryId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } private void recomputeCosts( @NonNull final CostElement costElement, @NonNull final PInstanceId productsSelectionId, @NonNull final Instant startDate) { DB.executeFunctionCallEx(getTrxName() , "select \"de_metas_acct\".product_costs_recreate_from_date( p_C_AcctSchema_ID :=" + getAccountingSchemaId().getRepoId() + ", p_M_CostElement_ID:=" + costElement.getId().getRepoId() + ", p_m_product_selection_id:=" + productsSelectionId.getRepoId() + " , p_ReorderDocs_DateAcct_Trunc:='MM'" + ", p_StartDateAcct:=" + DB.TO_SQL(startDate) + "::date)" // , null // ); } private Instant getStartDate() { return inventoryDAO.getMinInventoryDate(getSelectedInventoryIds()) .orElseThrow(() -> new AdempiereException("Cannot determine Start Date")); } private List<CostElement> getCostElements() { if (p_costingMethod != null) { return costElementRepository.getMaterialCostingElementsForCostingMethod(p_costingMethod); } return costElementRepository.getActiveMaterialCostingElements(getClientID()); } private AcctSchemaId getAccountingSchemaId() {return p_C_AcctSchema_ID;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\process\M_Inventory_RecomputeCosts.java
1
请在Spring Boot框架中完成以下Java代码
public class InvoiceCreditContext { /** * The DocType used to create the CreditMemo. */ @Nullable DocTypeId docTypeId; /** * If <code>true</code>, then the credit memo is completed and the credit memo's <code>GrandTotal</code> is allocated against the given invoice, so that the given * invoice has <code>IsPaid='Y'</code> afterwards. If <code>false</code>, then the credit memo is only "prepared", so to that is can still be edited by a user. */ boolean completeAndAllocate; /** * If <code>true</code>, then we copy <code>C_Invoice.C_Order_ID</code>, <code>C_Invoice.POReference</code> and <code>C_InvoiceLine.C_OrderLine_ID</code>s
*/ boolean referenceOriginalOrder; /** * If <code>true</code>, then the credit memo and the invoice will reference each other via <code>Ref_CrediMemo_ID</code> (this is already the case) and if the credit memo * is completed later, it is automatically allocated against the invoice (also if it's completed right directly).<br> * Also, the credit memo will reference the invoice via <code>Ref_Invoice_ID</code>. * If <code>false</code>, then the original invoice is just used as a template, but not linked with the credit memo */ boolean referenceInvoice; /** * If <code>true</code> then the credit memo is generated with <code>IsCreditedInvoiceReinvoicable='Y'</code>, which leads to the invoice candidates to be updated in a manner that allows * the credited quantities to be invoiced once more. Note that if the invoice's grand total is already partially allocated, this value will be override with <code>false</code>. */ boolean creditedInvoiceReinvoicable; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceCreditContext.java
2
请完成以下Java代码
public void complete() { validateState(); this.status = OrderStatus.COMPLETED; } public void addOrder(final Product product) { validateState(); validateProduct(product); orderItems.add(new OrderItem(product)); price = price.add(product.getPrice()); } public void removeOrder(final UUID id) { validateState(); final OrderItem orderItem = getOrderItem(id); orderItems.remove(orderItem); price = price.subtract(orderItem.getPrice()); } private OrderItem getOrderItem(final UUID id) { return orderItems.stream() .filter(orderItem -> orderItem.getProductId() .equals(id)) .findFirst() .orElseThrow(() -> new DomainException("Product with " + id + " doesn't exist.")); } private void validateState() { if (OrderStatus.COMPLETED.equals(status)) { throw new DomainException("The order is in completed state."); } } private void validateProduct(final Product product) { if (product == null) { throw new DomainException("The product cannot be null."); } } public UUID getId() { return id; } public OrderStatus getStatus() { return status; } public BigDecimal getPrice() { return price;
} public List<OrderItem> getOrderItems() { return Collections.unmodifiableList(orderItems); } @Override public int hashCode() { return Objects.hash(id, orderItems, price, status); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Order)) return false; Order other = (Order) obj; return Objects.equals(id, other.id) && Objects.equals(orderItems, other.orderItems) && Objects.equals(price, other.price) && status == other.status; } private Order() { } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\domain\Order.java
1
请完成以下Java代码
private static <T> T fromObjectTo( final Object valueObj, @NonNull final Class<T> type, @NonNull final Function<String, T> fromJsonConverer, @NonNull final Function<Object, T> fromObjectConverter) { if (valueObj == null || JSONNullValue.isNull(valueObj)) { return null; } else if (type.isInstance(valueObj)) { return type.cast(valueObj); } else if (valueObj instanceof CharSequence) { final String json = valueObj.toString().trim(); if (json.isEmpty()) { return null; } if (isPossibleJdbcTimestamp(json)) { try { final Timestamp timestamp = fromPossibleJdbcTimestamp(json); return fromObjectConverter.apply(timestamp); } catch (final Exception e) { logger.warn("Error while converting possible JDBC Timestamp `{}` to java.sql.Timestamp", json, e); return fromJsonConverer.apply(json); } } else { return fromJsonConverer.apply(json);
} } else if (valueObj instanceof StringLookupValue) { final String key = ((StringLookupValue)valueObj).getIdAsString(); if (Check.isEmpty(key)) { return null; } else { return fromJsonConverer.apply(key); } } else { return fromObjectConverter.apply(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\DateTimeConverters.java
1
请完成以下Java代码
public class HillValleyCounter { public int countHillsAndValleys(int[] numbers) { int hills = 0; int valleys = 0; for (int i = 1; i < numbers.length - 1; i++) { int prev = numbers[i - 1]; int current = numbers[i]; int next = numbers[i + 1]; while (i < numbers.length - 1 && numbers[i] == numbers[i + 1]) { i++; }
if (i != numbers.length - 1) { next = numbers[i + 1]; } if (current > prev && current > next) { hills++; } else if (current < prev && current < next) { valleys++; } } return hills + valleys; } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-3\src\main\java\com\baeldung\hillsandvalleys\HillValleyCounter.java
1
请完成以下Java代码
private void createAndAddFacts( @NonNull final CommissionShare commissionShare, @NonNull final CommissionTriggerData commissionTriggerData) { try (final MDC.MDCCloseable shareMDC = TableRecordMDC.putTableRecordReference(I_C_Commission_Share.Table_Name, commissionShare.getId())) { Check.assume(LicenseFeeConfig.isInstance(commissionShare.getConfig()), "The commission share is always carrying a license fee commission config at this stage!"); final LicenseFeeConfig licenseFeeConfig = LicenseFeeConfig.cast(commissionShare.getConfig()); try (final MDC.MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_LicenseFeeSettings.Table_Name, licenseFeeConfig.getId())) { logger.debug("LicenseFeeConfig - Create commission shares and facts"); final Function<CommissionPoints, CommissionPoints> computeOrgCommissionAmount = (basePoints) -> basePoints.computePercentageOf(licenseFeeConfig.getCommissionPercent(), licenseFeeConfig.getPointsPrecision()); final CommissionPoints forecastCP = computeOrgCommissionAmount.apply(commissionTriggerData.getForecastedBasePoints());
final CommissionPoints toInvoiceCP = computeOrgCommissionAmount.apply(commissionTriggerData.getInvoiceableBasePoints()); final CommissionPoints invoicedCP = computeOrgCommissionAmount.apply(commissionTriggerData.getInvoicedBasePoints()); final Instant triggerDataTimestamp = commissionTriggerData.getTimestamp(); final Optional<CommissionFact> forecastedFact = CommissionFact.createFact(triggerDataTimestamp, CommissionState.FORECASTED, forecastCP, commissionShare.getForecastedPointsSum()); final Optional<CommissionFact> toInvoiceFact = CommissionFact.createFact(triggerDataTimestamp, CommissionState.INVOICEABLE, toInvoiceCP, commissionShare.getInvoiceablePointsSum()); final Optional<CommissionFact> invoicedFact = CommissionFact.createFact(triggerDataTimestamp, CommissionState.INVOICED, invoicedCP, commissionShare.getInvoicedPointsSum()); forecastedFact.ifPresent(commissionShare::addFact); toInvoiceFact.ifPresent(commissionShare::addFact); invoicedFact.ifPresent(commissionShare::addFact); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\algorithm\LicenseFeeAlgorithm.java
1
请在Spring Boot框架中完成以下Java代码
public class FlowableMailProperties { /** * The host of the mail server. */ private String host = "localhost"; /** * The port of the mail server. */ private int port = 1025; /** * The SSL port of the mail server. */ private int sslPort = 1465; /** * The username that needs to be used for the mail server authentication. * If empty no authentication would be used. */ private String username; /** * The password for the mail server authentication. */ private String password; /** * The default from address that needs to be used when sending emails. */ private String defaultFrom = "flowable@localhost"; /** * The force to address(es) that would be used when sending out emails. * IMPORTANT: If this is set then all emails will be send to defined address(es) instead of the address * configured in the MailActivity. */ private String forceTo; /** * The default charset to use when not set in the mail task. */ private Charset defaultCharset = StandardCharsets.UTF_8; /** * Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). */ private boolean useSsl; /** * Set or disable the STARTTLS encryption. */ private boolean useTls; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; }
public int getSSLPort() { return sslPort; } public void setSSLPort(int sslPort) { this.sslPort = sslPort; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDefaultFrom() { return defaultFrom; } public void setDefaultFrom(String defaultFrom) { this.defaultFrom = defaultFrom; } public String getForceTo() { return forceTo; } public void setForceTo(String forceTo) { this.forceTo = forceTo; } public Charset getDefaultCharset() { return defaultCharset; } public void setDefaultCharset(Charset defaultCharset) { this.defaultCharset = defaultCharset; } public boolean isUseSsl() { return useSsl; } public void setUseSsl(boolean useSsl) { this.useSsl = useSsl; } public boolean isUseTls() { return useTls; } public void setUseTls(boolean useTls) { this.useTls = useTls; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableMailProperties.java
2
请完成以下Java代码
public static class Fehlmenge { @XmlAttribute(name = "AuftragsID") protected String auftragsID; @XmlAttribute(name = "Menge", required = true) protected int menge; /** * Gets the value of the auftragsID property. * * @return * possible object is * {@link String } * */ public String getAuftragsID() { return auftragsID; } /** * Sets the value of the auftragsID property. * * @param value * allowed object is * {@link String } * */ public void setAuftragsID(String value) { this.auftragsID = value; } /** * Gets the value of the menge property. * */ public int getMenge() {
return menge; } /** * Sets the value of the menge property. * */ public void setMenge(int value) { this.menge = value; } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfragenAntwort.java
1
请完成以下Spring Boot application配置
server: port: 8080 servlet: context-path: /demo spring: kafka: bootstrap-servers: localhost:9092 producer: retries: 0 batch-size: 16384 buffer-memory: 33554432 key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.apache.kafka.common.serialization.StringSerializer consumer: group-id: spring-boot-demo # 手动提交 enable-auto-commit: false auto-offset-reset: latest key-deserializer: org.apache.kafka.common.serialization.StringDeserializer v
alue-deserializer: org.apache.kafka.common.serialization.StringDeserializer properties: session.timeout.ms: 60000 listener: log-container-config: false concurrency: 5 # 手动提交 ack-mode: manual_immediate
repos\spring-boot-demo-master\demo-mq-kafka\src\main\resources\application.yml
2
请完成以下Java代码
/* for testing */ Map<String, GroupWeightConfig> getGroupWeights() { return groupWeights; } @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { Map<String, String> weights = getWeights(exchange); for (String group : groupWeights.keySet()) { GroupWeightConfig config = groupWeights.get(group); if (config == null) { if (log.isDebugEnabled()) { log.debug("No GroupWeightConfig found for group: " + group); } continue; // nothing we can do, but this is odd } // Usually, multiple threads accessing the same random object will have some // performance problems, so we can use ThreadLocalRandom by default double r = randomFunction.apply(exchange); List<Double> ranges = config.ranges; if (log.isTraceEnabled()) { log.trace("Weight for group: " + group + ", ranges: " + ranges + ", r: " + r); } for (int i = 0; i < ranges.size() - 1; i++) { if (r >= ranges.get(i) && r < ranges.get(i + 1)) { String routeId = config.rangeIndexes.get(i); weights.put(group, routeId); break; } } } if (log.isTraceEnabled()) { log.trace("Weights attr: " + weights); } return chain.filter(exchange); } /* for testing */ static class GroupWeightConfig { String group; LinkedHashMap<String, Integer> weights = new LinkedHashMap<>();
LinkedHashMap<String, Double> normalizedWeights = new LinkedHashMap<>(); LinkedHashMap<Integer, String> rangeIndexes = new LinkedHashMap<>(); List<Double> ranges = new ArrayList<>(); GroupWeightConfig(String group) { this.group = group; } GroupWeightConfig(GroupWeightConfig other) { this.group = other.group; this.weights = new LinkedHashMap<>(other.weights); this.normalizedWeights = new LinkedHashMap<>(other.normalizedWeights); this.rangeIndexes = new LinkedHashMap<>(other.rangeIndexes); } @Override public String toString() { return new ToStringCreator(this).append("group", group) .append("weights", weights) .append("normalizedWeights", normalizedWeights) .append("rangeIndexes", rangeIndexes) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\WeightCalculatorWebFilter.java
1
请完成以下Java代码
public ImmutableList<String> getOtherParts() { return parts.size() > 2 ? parts.subList(2, parts.size()) : ImmutableList.of(); } public ViewId withWindowId(@NonNull final WindowId newWindowId) { if (windowId.equals(newWindowId)) { return this; } final ImmutableList<String> newParts = ImmutableList.<String>builder() .add(newWindowId.toJson()) .addAll(parts.subList(1, parts.size())) .build(); final String newViewId = JOINER.join(newParts);
return new ViewId(newViewId, newParts, newWindowId); } public void assertWindowId(@NonNull final WindowId expectedWindowId) { if (!windowId.equals(expectedWindowId)) { throw new AdempiereException("" + this + " does not have expected windowId: " + expectedWindowId); } } public static boolean equals(@Nullable final ViewId id1, @Nullable final ViewId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewId.java
1
请在Spring Boot框架中完成以下Java代码
private I_S_IssueLabel of(@NonNull final IssueId issueId, @NonNull final IssueLabel issueLabel) { final I_S_IssueLabel record = InterfaceWrapperHelper.newInstance(I_S_IssueLabel.class); record.setS_Issue_ID(issueId.getRepoId()); record.setAD_Org_ID(issueLabel.getOrgId().getRepoId()); record.setLabel(issueLabel.getValue()); return record; } private void persistLabels(@NonNull final List<I_S_IssueLabel> newLabels, @NonNull final List<I_S_IssueLabel> existingLabels) { if (Check.isEmpty(newLabels)) { InterfaceWrapperHelper.deleteAll(existingLabels); return; } final List<I_S_IssueLabel> recordsToInsert = newLabels .stream() .filter(label -> existingLabels .stream()
.noneMatch(record -> areEqual(record, label)) ) .collect(Collectors.toList()); final List<I_S_IssueLabel> recordsToDelete = existingLabels .stream() .filter(record -> newLabels .stream() .noneMatch(label -> areEqual(record, label)) ) .collect(Collectors.toList()); InterfaceWrapperHelper.deleteAll(recordsToDelete); InterfaceWrapperHelper.saveAll(recordsToInsert); } private boolean areEqual(@NonNull final I_S_IssueLabel record1, @NonNull final I_S_IssueLabel record2) { return record1.getLabel().equalsIgnoreCase(record2.getLabel()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\external\label\IssueLabelRepository.java
2
请完成以下Java代码
public String getTemplate() { if (featureIndex_ != null) { return featureIndex_.getTemplate(); } else { return null; } } public int getNbest_() { return nbest_; } public void setNbest_(int nbest_) { this.nbest_ = nbest_; }
public int getVlevel_() { return vlevel_; } public void setVlevel_(int vlevel_) { this.vlevel_ = vlevel_; } public DecoderFeatureIndex getFeatureIndex_() { return featureIndex_; } public void setFeatureIndex_(DecoderFeatureIndex featureIndex_) { this.featureIndex_ = featureIndex_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\ModelImpl.java
1