instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private Mono<Void> handleWebClientResponseException(ClientRequest request, WebClientResponseException exception) { return Mono.justOrEmpty(resolveErrorIfPossible(exception.getStatusCode())).flatMap((oauth2Error) -> { Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request); Mono<String> clientRegistrationId = effectiveClientRegistrationId(request); return Mono .zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono, serverWebExchange, clientRegistrationId) .flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), new ClientAuthorizationException(oauth2Error, zipped.getT3(), exception))); }); } /** * Handles the given OAuth2AuthorizationException that occurred downstream by * notifying the authorization failure handler. * @param request the request being processed * @param exception the authorization exception to include in the failure event. * @return a {@link Mono} that completes empty after the authorization failure * handler completes. */ private Mono<Void> handleAuthorizationException(ClientRequest request, OAuth2AuthorizationException exception) { Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request); return Mono .zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono, serverWebExchange) .flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), exception)); } /** * Delegates to the authorization failure handler of the failed authorization. * @param principal the principal associated with the failed authorization attempt * @param exchange the currently active exchange
* @param exception the authorization exception to include in the failure event. * @return a {@link Mono} that completes empty after the authorization failure * handler completes. */ private Mono<Void> handleAuthorizationFailure(Authentication principal, Optional<ServerWebExchange> exchange, OAuth2AuthorizationException exception) { return this.authorizationFailureHandler.onAuthorizationFailure(exception, principal, createAttributes(exchange.orElse(null))); } private Map<String, Object> createAttributes(ServerWebExchange exchange) { if (exchange == null) { return Collections.emptyMap(); } return Collections.singletonMap(ServerWebExchange.class.getName(), exchange); } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\reactive\function\client\ServerOAuth2AuthorizedClientExchangeFilterFunction.java
1
请完成以下Java代码
public <K, V> IAutoCloseable putCache(@Nullable final CacheInterface cache) { if (cache == null) { return null; } final ImmutableList.Builder<MDCCloseable> closables = ImmutableList.builder(); final String cacheId = Long.toString(cache.getCacheId()); if (!Objects.equals(MDC.get("de.metas.cache.cacheId"), cacheId)) { closables.add(MDC.putCloseable("de.metas.cache.cacheId", cacheId)); } if (cache instanceof CCache) { final CCache<?, ?> ccache = (CCache<?, ?>)cache; final String cacheName = ccache.getCacheName(); if (!Objects.equals(MDC.get("de.metas.cache.cacheName"), cacheName)) {
closables.add(MDC.putCloseable("de.metas.cache.cacheName", cacheName)); } } final ImmutableList<MDCCloseable> composite = closables.build(); return () -> composite.forEach(MDCCloseable::close); } public MDCCloseable putCacheLabel(@Nullable final CacheLabel cacheLabel) { if (cacheLabel == null) { return null; } if (Objects.equals(MDC.get("de.metas.cache.cacheLabel"), cacheLabel.getName())) { return null; } return MDC.putCloseable("de.metas.cache.cacheLabel", cacheLabel.getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheMDC.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.") public String getExternalUrl() { return externalUrl; } public void setExternalUrl(String externalUrl) { this.externalUrl = externalUrl; } public String getContentUrl() {
return contentUrl; } public void setContentUrl(String contentUrl) { this.contentUrl = contentUrl; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java
2
请完成以下Java代码
public void setM_Forecast_ID (final int M_Forecast_ID) { if (M_Forecast_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Forecast_ID, M_Forecast_ID); } @Override public int getM_Forecast_ID() { return get_ValueAsInt(COLUMNNAME_M_Forecast_ID); } @Override public void setM_PriceList_ID (final int M_PriceList_ID) { if (M_PriceList_ID < 1) set_Value (COLUMNNAME_M_PriceList_ID, null); else set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID); } @Override public int getM_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_M_PriceList_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); }
@Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java
1
请完成以下Java代码
public void updateAuthorization(AuthorizationDto dto) { // get db auth Authorization dbAuthorization = getDbAuthorization(); // copy values from dto AuthorizationDto.update(dto, dbAuthorization, getProcessEngine().getProcessEngineConfiguration()); // save authorizationService.saveAuthorization(dbAuthorization); } public ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); URI uri = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(AuthorizationRestService.PATH) .path(resourceId) .build(); dto.addReflexiveLink(uri, HttpMethod.GET, "self"); if (isAuthorized(DELETE)) { dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); } if (isAuthorized(UPDATE)) { dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); } return dto; } // utils //////////////////////////////////////////////////
protected Authorization getDbAuthorization() { Authorization dbAuthorization = authorizationService.createAuthorizationQuery() .authorizationId(resourceId) .singleResult(); if (dbAuthorization == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Authorization with id " + resourceId + " does not exist."); } else { return dbAuthorization; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\authorization\impl\AuthorizationResourceImpl.java
1
请完成以下Java代码
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public DateTime getCreated() { return created; } public void setCreated(DateTime created) { this.created = created; } public DateTime getUpdated() { return updated; } public void setUpdated(DateTime updated) { this.updated = updated; } @Override public int hashCode() { int hash = 1; if (id != null) { hash = hash * 31 + id.hashCode(); } if (firstName != null) {
hash = hash * 31 + firstName.hashCode(); } if (lastName != null) { hash = hash * 31 + lastName.hashCode(); } return hash; } @Override public boolean equals(Object obj) { if ((obj == null) || (obj.getClass() != this.getClass())) return false; if (obj == this) return true; Person other = (Person) obj; return this.hashCode() == other.hashCode(); } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Person.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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()); } /** Set Report Column Set. @param PA_ReportColumnSet_ID Collection of Columns for Report */ public void setPA_ReportColumnSet_ID (int PA_ReportColumnSet_ID) { if (PA_ReportColumnSet_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, Integer.valueOf(PA_ReportColumnSet_ID)); }
/** Get Report Column Set. @return Collection of Columns for Report */ public int getPA_ReportColumnSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportColumnSet_ID); 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_PA_ReportColumnSet.java
1
请在Spring Boot框架中完成以下Java代码
public int getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } public long getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } public long getMaxEvictableIdleTimeMillis() { return maxEvictableIdleTimeMillis; } public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) { this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestWhileIdle() { return testWhileIdle; } public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() {
return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } public boolean isPoolPreparedStatements() { return poolPreparedStatements; } public void setPoolPreparedStatements(boolean poolPreparedStatements) { this.poolPreparedStatements = poolPreparedStatements; } public String getFilters() { return filters; } public void setFilters(String filters) { this.filters = filters; } public String getConnectionProperties() { return connectionProperties; } public void setConnectionProperties(String connectionProperties) { this.connectionProperties = connectionProperties; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\druid\DruidConfig.java
2
请完成以下Java代码
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { this.process(bean, EventBus::register, "initialization"); return bean; } private void process(final Object bean, final BiConsumer<EventBus, Object> consumer, final String action) { Object proxy = this.getTargetObject(bean); final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class); if (annotation == null) return; this.logger.info("{}: processing bean of type {} during {}", this.getClass().getSimpleName(), proxy.getClass().getName(), action); final String annotationValue = annotation.value(); try { final Expression expression = this.expressionParser.parseExpression(annotationValue); final Object value = expression.getValue(); if (!(value instanceof EventBus)) { this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}",
this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName()); return; } final EventBus eventBus = (EventBus)value; consumer.accept(eventBus, proxy); } catch (ExpressionException ex) { this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getName()); } } private Object getTargetObject(Object proxy) throws BeansException { if (AopUtils.isJdkDynamicProxy(proxy)) { try { return ((Advised)proxy).getTargetSource().getTarget(); } catch (Exception e) { throw new FatalBeanException("Error getting target of JDK proxy", e); } } return proxy; } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanPostProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public Step step1() { return new StepBuilder("job1step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("Tasklet has run"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } @Bean public Step step2() { return new StepBuilder("job1step2", jobRepository).<String, String> chunk(3, transactionManager) .reader(new ListItemReader<>(Arrays.asList("7", "2", "3", "10", "5", "6"))) .processor(new ItemProcessor<String, String>() { @Override public String process(String item) throws Exception { LOGGER.info("Processing of chunks"); return String.valueOf(Integer.parseInt(item) * -1); } }) .writer(new ItemWriter<String>() { @Override public void write(Chunk<? extends String> items) throws Exception { for (String item : items) { LOGGER.info(">> " + item); } } }) .build(); } @Bean public Job job2(Step job2step1) { return new JobBuilder("job2", jobRepository).incrementer(new RunIdIncrementer())
.start(job2step1) .build(); } @Bean public Step job2step1() { return new StepBuilder("job2step1", jobRepository).tasklet(new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { LOGGER.info("This job is from Baeldung"); return RepeatStatus.FINISHED; } }, transactionManager) .build(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-task\springcloudtaskbatch\src\main\java\com\baeldung\task\JobConfiguration.java
2
请完成以下Java代码
public int getM_HU_Trx_Line_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Trx_Line_ID); } /** * Operation AD_Reference_ID=540410 * Reference name: M_HU_PI_Attribute_Operation */ public static final int OPERATION_AD_Reference_ID=540410; /** Save = SAVE */ public static final String OPERATION_Save = "SAVE"; /** Drop = DROP */ public static final String OPERATION_Drop = "DROP"; @Override public void setOperation (final java.lang.String Operation) { set_Value (COLUMNNAME_Operation, Operation); } @Override public java.lang.String getOperation() { return get_ValueAsString(COLUMNNAME_Operation); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueDate (final @Nullable java.sql.Timestamp ValueDate) { set_Value (COLUMNNAME_ValueDate, ValueDate); } @Override public java.sql.Timestamp getValueDate() { return get_ValueAsTimestamp(COLUMNNAME_ValueDate); } @Override public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial)
{ set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial); } @Override public java.sql.Timestamp getValueDateInitial() { return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial); } @Override public void setValueInitial (final @Nullable java.lang.String ValueInitial) { set_Value (COLUMNNAME_ValueInitial, ValueInitial); } @Override public java.lang.String getValueInitial() { return get_ValueAsString(COLUMNNAME_ValueInitial); } @Override public void setValueNumber (final @Nullable BigDecimal ValueNumber) { set_Value (COLUMNNAME_ValueNumber, ValueNumber); } @Override public BigDecimal getValueNumber() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial) { set_Value (COLUMNNAME_ValueNumberInitial, ValueNumberInitial); } @Override public BigDecimal getValueNumberInitial() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public class TxProducerListener implements RocketMQLocalTransactionListener { @Override public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { // 执行本地事务 System.out.println("TX message listener execute local transaction"); RocketMQLocalTransactionState result; try { // 业务代码( 例如下订单 ) result = RocketMQLocalTransactionState.COMMIT; } catch (Exception e) { System.out.println("execute local transaction error"); result = RocketMQLocalTransactionState.UNKNOWN; } return result; }
@Override public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { // 检查本地事务( 例如检查下订单是否成功 ) System.out.println("TX message listener check local transaction"); RocketMQLocalTransactionState result; try { //业务代码( 根据检查结果,决定是COMMIT或ROLLBACK ) result = RocketMQLocalTransactionState.COMMIT; } catch (Exception e) { // 异常就回滚 System.out.println("check local transaction error"); result = RocketMQLocalTransactionState.ROLLBACK; } return result; } }
repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\TxProducerListener.java
2
请完成以下Java代码
public ViewLayout getViewLayout( @NonNull final WindowId windowId, @NonNull final JSONViewDataType viewDataType, final ViewProfileId profileId) { final ITranslatableString caption = processDAO .retrieveProcessNameByClassIfUnique(WEBUI_C_Flatrate_DataEntry_Detail_Launcher.class) .orElse(null); return ViewLayout.builder() .setWindowId(windowId) .setCaption(caption) //.allowViewCloseAction(ViewCloseAction.CANCEL) .allowViewCloseAction(ViewCloseAction.DONE) // .setFocusOnFieldName(DataEntryDetailsRow.FIELD_Qty) .addElementsFromViewRowClassAndFieldNames( DataEntryDetailsRow.class, viewDataType, ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_Department), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_ASI), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_Qty), ViewColumnHelper.ClassViewColumnOverrides.ofFieldName(DataEntryDetailsRow.FIELD_UOM)) // .setAllowOpeningRowDetails(false) .build(); } @Override public WindowId getWindowId() { return WINDOW_ID; }
@Override public final void put(@NonNull final IView view) { views.put(view.getViewId(), DataEntryDetailsView.cast(view)); } @Nullable @Override public IView getByIdOrNull(final ViewId viewId) { return views.getIfPresent(viewId); } @Override public void closeById(final ViewId viewId, final ViewCloseAction closeAction) { } @Override public Stream<IView> streamAllViews() { return Stream.empty(); } @Override public void invalidateView(final ViewId viewId) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\view\DataEntryDedailsViewFactory.java
1
请完成以下Java代码
public TaskCompletionBuilder taskId(String id) { this.taskId = id; return this; } @Override public TaskCompletionBuilder formDefinitionId(String formDefinitionId) { this.formDefinitionId = formDefinitionId; return this; } @Override public TaskCompletionBuilder outcome(String outcome) { this.outcome = outcome; return this; } protected void completeTask() { this.commandExecutor.execute(new CompleteTaskCmd(this.taskId, variables, variablesLocal, transientVariables, transientVariablesLocal));
} protected void completeTaskWithForm() { this.commandExecutor.execute(new CompleteTaskWithFormCmd(this.taskId, formDefinitionId, outcome, variables, variablesLocal, transientVariables, transientVariablesLocal)); } @Override public void complete() { if (this.formDefinitionId != null) { completeTaskWithForm(); } else { completeTask(); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\task\TaskCompletionBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<RestIdentityLink> getIdentityLinks(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) { ProcessDefinition processDefinition = getProcessDefinitionFromRequestWithoutAccessCheck(processDefinitionId); if (restApiInterceptor != null) { restApiInterceptor.accessProcessDefinitionIdentityLinks(processDefinition); } return restResponseFactory.createRestIdentityLinks(repositoryService.getIdentityLinksForProcessDefinition(processDefinition.getId())); } @ApiOperation(value = "Add a candidate starter to a process definition", tags = { "Process Definitions" }, notes = "It is possible to add either a user or a group.", code = 201) @ApiResponses(value = { @ApiResponse(code = 201, message = "Indicates the process definition was found and the identity link was created."), @ApiResponse(code = 400, message = "Indicates the body does not contain the correct information."), @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.") }) @PostMapping(value = "/repository/process-definitions/{processDefinitionId}/identitylinks", produces = "application/json") @ResponseStatus(HttpStatus.CREATED) public RestIdentityLink createIdentityLink(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId, @RequestBody RestIdentityLink identityLink) { ProcessDefinition processDefinition = getProcessDefinitionFromRequestWithoutAccessCheck(processDefinitionId); if (identityLink.getGroup() == null && identityLink.getUser() == null) { throw new FlowableIllegalArgumentException("A group or a user is required to create an identity link."); } if (identityLink.getGroup() != null && identityLink.getUser() != null) { throw new FlowableIllegalArgumentException("Only one of user or group can be used to create an identity link."); }
if (restApiInterceptor != null) { restApiInterceptor.createProcessDefinitionIdentityLink(processDefinition, identityLink); } if (identityLink.getGroup() != null) { repositoryService.addCandidateStarterGroup(processDefinition.getId(), identityLink.getGroup()); } else { repositoryService.addCandidateStarterUser(processDefinition.getId(), identityLink.getUser()); } // Always candidate for process-definition. User-provided value is // ignored identityLink.setType(IdentityLinkType.CANDIDATE); return restResponseFactory.createRestIdentityLink(identityLink.getType(), identityLink.getUser(), identityLink.getGroup(), null, processDefinition.getId(), null); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionIdentityLinkCollectionResource.java
2
请完成以下Java代码
public abstract class AbstractResultSetBlindIterator<E> implements BlindIterator<E>, Closeable { private ResultSet rs = null; private boolean closed = false; public AbstractResultSetBlindIterator() { super(); } /** * Create and returns the {@link ResultSet}. * * This method will be called internally, one time, right before trying to iterate first element. * * @return * @throws SQLException */ protected abstract ResultSet createResultSet() throws SQLException; /** * Method responsible for fetching current row from {@link ResultSet} and convert it to target object. * * NOTE: implementors of this method shall NEVER call rs.next(). * * @param rs * @return * @throws SQLException */ protected abstract E fetch(ResultSet rs) throws SQLException; @Override public final E next() { if (closed) { throw new NoSuchElementException("ResultSet already closed"); } boolean keepAliveResultSet = false; // if false, underlying ResultSet will be closed in finally block try { if (rs == null) { rs = createResultSet(); if (rs == null) { throw new IllegalStateException("No ResultSet was created"); } } if (!rs.next()) { // we reached the end of result set keepAliveResultSet = false; // flag that we need to close the ResultSet return null; }
final E item = fetch(rs); keepAliveResultSet = true; return item; } catch (SQLException e) { keepAliveResultSet = false; // make sure we will close the ResultSet onSQLException(e); // NOTE: we shall not reach this point because onSQLException is assumed to throw the exception throw new DBException(e); } finally { if (!keepAliveResultSet) { close(); } } } /** * Gets the {@link SQLException} and throws the proper exception (maybe with more informations) * * @param e */ protected void onSQLException(final SQLException e) { throw new DBException(e); } /** * Closes the underlying {@link ResultSet}. */ @Override public void close() { DB.close(rs); rs = null; closed = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\db\util\AbstractResultSetBlindIterator.java
1
请完成以下Java代码
public String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todo.setUsername(username); todoRepository.save(todo); // todoService.addTodo(username, todo.getDescription(), // todo.getTargetDate(), todo.isDone()); return "redirect:list-todos"; } @RequestMapping("delete-todo") public String deleteTodo(@RequestParam int id) { //Delete todo todoRepository.deleteById(id); return "redirect:list-todos"; } @RequestMapping(value="update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam int id, ModelMap model) { Todo todo = todoRepository.findById(id).get(); model.addAttribute("todo", todo); return "todo"; }
@RequestMapping(value="update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if(result.hasErrors()) { return "todo"; } String username = getLoggedInUsername(model); todo.setUsername(username); todoRepository.save(todo); return "redirect:list-todos"; } private String getLoggedInUsername(ModelMap model) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication.getName(); } }
repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoControllerJpa.java
1
请完成以下Java代码
public String getActivityInstanceId() { return activityInstanceId; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getTenantId() { return tenantId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public Date getRemovalTime() {
return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId(); result.timestamp = historicExternalTaskLog.getTimestamp(); result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries(); result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请完成以下Spring Boot application配置
server.port=8081 spring.application.name=nacos-consumer spring.cloud.nacos.discovery.server-addr=localhost:8848 spring.cloud.nacos.config.refresh-enabled=true spring.cloud.nacos.config.group=${spring.application.name} #nacos.discovery.server-addr=localhost:8848 spring.main.allow-bean-definition-overriding=true dubbo.registry.address=spring-cloud://localhost:8848 dubbo.proto
col.name=dubbo dubbo.protocol.port=-1 dubbo.consumer.check=false dubbo.cloud.subscribed-services=nacos-provider service.version=1.0.0 service.name=helloService
repos\spring-boot-quick-master\quick-dubbo-nacos\consumer\src\main\resources\application.properties
2
请完成以下Java代码
protected final HUEditorRow getSingleSelectedRow() { return HUEditorRow.cast(super.getSingleSelectedRow()); } protected final Stream<HUEditorRow> streamSelectedRows(@NonNull final HUEditorRowFilter filter) { final DocumentIdsSelection selectedDocumentIds = getSelectedRowIds(); if (selectedDocumentIds.isEmpty()) { return Stream.empty(); } return getView().streamByIds(filter.andOnlyRowIds(selectedDocumentIds)); } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override protected Stream<HUEditorRow> streamSelectedRows() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); return getView().streamByIds(selectedRowIds); } protected final Stream<HuId> streamSelectedHUIds(@NonNull final Select select) { return streamSelectedHUIds(HUEditorRowFilter.select(select)); } protected final Stream<HuId> streamSelectedHUIds(@NonNull final HUEditorRowFilter filter) { return streamSelectedRows(filter) .map(HUEditorRow::getHuId) .filter(Objects::nonNull); } /** * Gets <b>all</b> selected {@link HUEditorRow}s and loads the top level-HUs from those. * I.e. this method does not rely on {@link HUEditorRow#isTopLevel()}, but checks the underlying HU.
*/ protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final Select select) { return streamSelectedHUs(HUEditorRowFilter.select(select)); } protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final HUEditorRowFilter filter) { final Stream<HuId> huIds = streamSelectedHUIds(filter); return StreamUtils .dice(huIds, 100) .flatMap(huIdsChunk -> handlingUnitsRepo.getByIds(huIdsChunk).stream()); } protected final void addHUIdsAndInvalidateView(Collection<HuId> huIds) { if (huIds.isEmpty()) { return; } getView().addHUIdsAndInvalidate(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorProcessTemplate.java
1
请完成以下Java代码
public Employee build() { try { Employee record = new Employee(); record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]); record.firstName = fieldSetFlags()[1] ? this.firstName : (java.lang.CharSequence) defaultValue(fields()[1]); record.lastName = fieldSetFlags()[2] ? this.lastName : (java.lang.CharSequence) defaultValue(fields()[2]); record.department = fieldSetFlags()[3] ? this.department : (java.lang.CharSequence) defaultValue(fields()[3]); record.designation = fieldSetFlags()[4] ? this.designation : (java.lang.CharSequence) defaultValue(fields()[4]); return record; } catch (java.lang.Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumWriter<Employee> WRITER$ = (org.apache.avro.io.DatumWriter<Employee>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { WRITER$.write(this, SpecificData.getEncoder(out)); } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumReader<Employee> READER$ = (org.apache.avro.io.DatumReader<Employee>)MODEL$.createDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { READER$.read(this, SpecificData.getDecoder(in)); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\Employee.java
1
请完成以下Java代码
public void setMsgText (java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } /** Set PMM_Message. @param PMM_Message_ID PMM_Message */ @Override public void setPMM_Message_ID (int PMM_Message_ID) { if (PMM_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_Message_ID, null); else set_ValueNoCheck (COLUMNNAME_PMM_Message_ID, Integer.valueOf(PMM_Message_ID)); } /** Get PMM_Message. @return PMM_Message */ @Override public int getPMM_Message_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Message_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Message.java
1
请完成以下Java代码
public RegulatoryAuthority2 createRegulatoryAuthority2() { return new RegulatoryAuthority2(); } /** * Create an instance of {@link RegulatoryReporting3 } * */ public RegulatoryReporting3 createRegulatoryReporting3() { return new RegulatoryReporting3(); } /** * Create an instance of {@link RemittanceAmount1 } * */ public RemittanceAmount1 createRemittanceAmount1() { return new RemittanceAmount1(); } /** * Create an instance of {@link RemittanceInformation5CH } * */ public RemittanceInformation5CH createRemittanceInformation5CH() { return new RemittanceInformation5CH(); } /** * Create an instance of {@link ServiceLevel8Choice } * */ public ServiceLevel8Choice createServiceLevel8Choice() { return new ServiceLevel8Choice(); } /** * Create an instance of {@link StructuredRegulatoryReporting3 } *
*/ public StructuredRegulatoryReporting3 createStructuredRegulatoryReporting3() { return new StructuredRegulatoryReporting3(); } /** * Create an instance of {@link StructuredRemittanceInformation7 } * */ public StructuredRemittanceInformation7 createStructuredRemittanceInformation7() { return new StructuredRemittanceInformation7(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "http://www.six-interbank-clearing.com/de/pain.001.001.03.ch.02.xsd", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ObjectFactory.java
1
请完成以下Java代码
public String getFrom() { return from; } /** * Sets the value of the from property. * * @param value * allowed object is * {@link String } * */ public void setFrom(String value) { this.from = value; } /** * Gets the value of the to property. * * @return * possible object is * {@link String } * */ public String getTo() { return to; } /** * Sets the value of the to property. * * @param value * allowed object is * {@link String } * */ public void setTo(String value) { this.to = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="via" use="required" type="{http://www.forum-datenaustausch.ch/invoice}eanPartyType" /&gt; * &lt;attribute name="sequence_id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedShort" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Via { @XmlAttribute(name = "via", required = true) protected String via; @XmlAttribute(name = "sequence_id", required = true) @XmlSchemaType(name = "unsignedShort") protected int sequenceId; /** * Gets the value of the via property. * * @return * possible object is * {@link String } * */
public String getVia() { return via; } /** * Sets the value of the via property. * * @param value * allowed object is * {@link String } * */ public void setVia(String value) { this.via = value; } /** * Gets the value of the sequenceId property. * */ public int getSequenceId() { return sequenceId; } /** * Sets the value of the sequenceId property. * */ public void setSequenceId(int value) { this.sequenceId = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransportType.java
1
请在Spring Boot框架中完成以下Java代码
private AbstractRememberMeServices createTokenBasedRememberMeServices(H http, String key) { UserDetailsService userDetailsService = getUserDetailsService(http); return new TokenBasedRememberMeServices(key, userDetailsService); } /** * Creates {@link PersistentTokenBasedRememberMeServices} * @param http the {@link HttpSecurity} to lookup shared objects * @param key the {@link #key(String)} * @return the {@link PersistentTokenBasedRememberMeServices} */ private AbstractRememberMeServices createPersistentRememberMeServices(H http, String key) { UserDetailsService userDetailsService = getUserDetailsService(http); return new PersistentTokenBasedRememberMeServices(key, userDetailsService, this.tokenRepository); } /** * Gets the {@link UserDetailsService} to use. Either the explicitly configured * {@link UserDetailsService} from {@link #userDetailsService(UserDetailsService)}, a * shared object from {@link HttpSecurity#getSharedObject(Class)} or the * {@link UserDetailsService} bean. * @param http {@link HttpSecurity} to get the shared {@link UserDetailsService} * @return the {@link UserDetailsService} to use */ private UserDetailsService getUserDetailsService(H http) { if (this.userDetailsService == null) { this.userDetailsService = getSharedOrBean(http, UserDetailsService.class); } Assert.state(this.userDetailsService != null, () -> "userDetailsService cannot be null. Invoke " + RememberMeConfigurer.class.getSimpleName() + "#userDetailsService(UserDetailsService) or see its javadoc for alternative approaches."); return this.userDetailsService; } /** * Gets the key to use for validating remember me tokens. If a value was passed into * {@link #key(String)}, then that is returned. Alternatively, if a key was specified * in the {@link #rememberMeServices(RememberMeServices)}}, then that is returned. If * no key was specified in either of those cases, then a secure random string is * generated.
* @return the remember me key to use */ private String getKey() { if (this.key == null) { if (this.rememberMeServices instanceof AbstractRememberMeServices) { this.key = ((AbstractRememberMeServices) this.rememberMeServices).getKey(); } else { this.key = UUID.randomUUID().toString(); } } return this.key; } private <C> C getSharedOrBean(H http, Class<C> type) { C shared = http.getSharedObject(type); if (shared != null) { return shared; } ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return context.getBeanProvider(type).getIfUnique(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\RememberMeConfigurer.java
2
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } /* public Long getSku() { return sku; } public void setSku(Long sku) { this.sku = sku; } */
@Override public boolean equals(Object o) { if (this == o) { return true; } if (getClass() != o.getClass()) { return false; } Book other = (Book) o; return Objects.equals(isbn, other.getIsbn()); // including sku // return Objects.equals(isbn, other.getIsbn()) // && Objects.equals(sku, other.getSku()); } @Override public int hashCode() { return Objects.hash(isbn); // including sku // return Objects.hash(isbn, sku); } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + '}'; // including sku //return "Book{" + "id=" + id + ", title=" + title // + ", isbn=" + isbn + ", price=" + price + ", sku=" + sku + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalId\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
void add(int value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } void deleteLast() { --_size; } void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size; } void resize(int size, int value) { if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) {
capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } int[] buf = new int[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } private int[] _buf; private int _size; private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoIntPool.java
1
请完成以下Java代码
public void setM_ReceiptSchedule_ID (final int M_ReceiptSchedule_ID) { if (M_ReceiptSchedule_ID < 1) set_Value (COLUMNNAME_M_ReceiptSchedule_ID, null); else set_Value (COLUMNNAME_M_ReceiptSchedule_ID, M_ReceiptSchedule_ID); } @Override public int getM_ReceiptSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ReceiptSchedule_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); }
@Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Cockpit_DocumentDetail.java
1
请在Spring Boot框架中完成以下Java代码
public class Cache { private List<MessagingService> services; public Cache(){ services = new ArrayList<MessagingService>(); } public MessagingService getService(String serviceName){ for (MessagingService service : services) { if(service.getServiceName().equalsIgnoreCase(serviceName)){ System.out.println("Returning cached " + serviceName + " object"); return service; } } return null;
} public void addService(MessagingService newService){ boolean exists = false; for (MessagingService service : services) { if(service.getServiceName().equalsIgnoreCase(newService.getServiceName())){ exists = true; } } if(!exists){ services.add(newService); } } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\service\locator\Cache.java
2
请在Spring Boot框架中完成以下Java代码
public Result executeByRuleCode(@PathVariable("ruleCode") String ruleCode, @RequestBody JSONObject formData) { Object result = FillRuleUtil.executeRule(ruleCode, formData); return Result.ok(result); } /** * 批量通过 ruleCode 执行自定义填值规则 * * @param ruleData 要执行的填值规则JSON数组: * 示例: { "commonFormData": {}, rules: [ { "ruleCode": "xxx", "formData": null } ] } * @return 运行后的结果,返回示例: [{"ruleCode": "order_num_rule", "result": "CN2019111117212984"}] * */ @PutMapping("/executeRuleByCodeBatch") public Result executeByRuleCodeBatch(@RequestBody JSONObject ruleData) { JSONObject commonFormData = ruleData.getJSONObject("commonFormData"); JSONArray rules = ruleData.getJSONArray("rules"); // 遍历 rules ,批量执行规则 JSONArray results = new JSONArray(rules.size()); for (int i = 0; i < rules.size(); i++) { JSONObject rule = rules.getJSONObject(i); String ruleCode = rule.getString("ruleCode"); JSONObject formData = rule.getJSONObject("formData");
// 如果没有传递 formData,就用common的 if (formData == null) { formData = commonFormData; } // 执行填值规则 Object result = FillRuleUtil.executeRule(ruleCode, formData); JSONObject obj = new JSONObject(rules.size()); obj.put("ruleCode", ruleCode); obj.put("result", result); results.add(obj); } return Result.ok(results); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysFillRuleController.java
2
请在Spring Boot框架中完成以下Java代码
private EdqsSyncState getSyncState() { EdqsSyncState state = attributesService.find(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID, AttributeScope.SERVER_SCOPE, "edqsSyncState").get(30, TimeUnit.SECONDS) .flatMap(KvEntry::getJsonValue) .map(value -> JacksonUtil.fromString(value, EdqsSyncState.class)) .orElse(null); log.info("EDQS sync state: {}", state); return state; } @SneakyThrows private void saveSyncState(EdqsSyncStatus status) { saveSyncState(status, null); } @SneakyThrows private void saveSyncState(EdqsSyncStatus status, Set<ObjectType> objectTypes) {
EdqsSyncState state = new EdqsSyncState(status, objectTypes); log.info("New EDQS sync state: {}", state); attributesService.save(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID, AttributeScope.SERVER_SCOPE, new BaseAttributeKvEntry( new JsonDataEntry("edqsSyncState", JacksonUtil.toString(state)), System.currentTimeMillis())).get(30, TimeUnit.SECONDS); } @PreDestroy private void stop() { executor.shutdown(); scheduler.shutdownNow(); eventsProducer.stop(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edqs\DefaultEdqsService.java
2
请完成以下Java代码
public class PrintPackagePDFBuilder { private final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class); private I_C_Print_Package printPackage; public PrintPackagePDFBuilder setPrintPackage(@NonNull final I_C_Print_Package printPackage) { this.printPackage = printPackage; return this; } private PrintablePDF createPrintable() { final byte[] data = printingDAO.retrievePrintPackageData(printPackage).getPrintData(); if (data == null) { return null; } final InputStream in = new ByteArrayInputStream(data); final PrintablePDF printable = new PrintablePDF(in); return printable; } public byte[] printToBytes() throws Exception { final ByteArrayOutputStream out = new ByteArrayOutputStream(); print(out); return out.toByteArray(); } public void print(@NonNull final OutputStream bos) throws Exception { final I_C_Print_Job_Instructions print_Job_Instructions = printPackage.getC_Print_Job_Instructions(); final Document document = new Document(); final PdfCopy copy = new PdfCopy(document, bos); document.open(); final PrintablePDF printable = createPrintable(); if (printable == null) { return; } try { for (final I_C_Print_PackageInfo printPackageInfo : printingDAO.retrievePrintPackageInfos(printPackage)) { final byte[] pdf = print(printPackageInfo, printable);
final PdfReader reader = new PdfReader(pdf); for (int page = 0; page < reader.getNumberOfPages(); ) { copy.addPage(copy.getImportedPage(reader, ++page)); } copy.freeReader(reader); reader.close(); } document.close(); print_Job_Instructions.setErrorMsg(null); print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Done); InterfaceWrapperHelper.save(print_Job_Instructions); } catch (final Exception e) { print_Job_Instructions.setErrorMsg(e.getLocalizedMessage()); print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Error); InterfaceWrapperHelper.save(print_Job_Instructions); throw new AdempiereException(e.getLocalizedMessage()); } } private byte[] print(@NonNull final I_C_Print_PackageInfo printPackageInfo, @NonNull final PrintablePDF printable) { printable.setCalX(printPackageInfo.getCalX()); printable.setCalY(printPackageInfo.getCalY()); final PrintablePDF clone = printable; return PdfPrinter.print(printable, clone); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrintPackagePDFBuilder.java
1
请完成以下Java代码
public void setS_Resource_ID (int S_Resource_ID) { if (S_Resource_ID < 1) set_Value (COLUMNNAME_S_Resource_ID, null); else set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Ressource. @return Resource */ @Override public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** * TypeMRP AD_Reference_ID=53230 * Reference name: _MRP Type */ public static final int TYPEMRP_AD_Reference_ID=53230; /** Demand = D */ public static final String TYPEMRP_Demand = "D"; /** Supply = S */ public static final String TYPEMRP_Supply = "S"; /** Set TypeMRP. @param TypeMRP TypeMRP */ @Override public void setTypeMRP (java.lang.String TypeMRP) { set_Value (COLUMNNAME_TypeMRP, TypeMRP); } /** Get TypeMRP. @return TypeMRP */ @Override public java.lang.String getTypeMRP () { return (java.lang.String)get_Value(COLUMNNAME_TypeMRP); } /** Set Suchschlüssel.
@param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.math.BigDecimal Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.math.BigDecimal getVersion () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
1
请完成以下Java代码
public void setUp() { array = new boolean[size]; for (int i = 0; i < array.length; i++) { array[i] = ThreadLocalRandom.current().nextBoolean(); } bitSet = new BitSet(size); for (int i = 0; i < size; i++) { bitSet.set(i, ThreadLocalRandom.current().nextBoolean()); } } @Benchmark public boolean getBoolArray() { return array[ThreadLocalRandom.current().nextInt(size)]; } @Benchmark public boolean getBitSet() { return bitSet.get(ThreadLocalRandom.current().nextInt(size)); } @Benchmark public void setBoolArray() { int index = ThreadLocalRandom.current().nextInt(size); array[index] = true; } @Benchmark public void setBitSet() { int index = ThreadLocalRandom.current().nextInt(size);
bitSet.set(index); } @Benchmark public int cardinalityBoolArray() { int sum = 0; for (boolean b : array) { if (b) { sum++; } } return sum; } @Benchmark public int cardinalityBitSet() { return bitSet.cardinality(); } }
repos\tutorials-master\jmh\src\main\java\com\baeldung\bitset\VectorOfBitsBenchmark.java
1
请完成以下Java代码
public void setAge(int age) { this.age = age; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Expose int age; @Expose(serialize = true, deserialize = false) public long id;
@Expose(serialize = false, deserialize = false) private String email; public User(String name, int age, String email) { this.name = name; this.age = age; this.email = email; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", id=" + id + ", email='" + email + '\'' + '}'; } }
repos\tutorials-master\json-modules\gson-3\src\main\java\com\baeldung\gson\entities\User.java
1
请完成以下Java代码
public org.compiere.model.I_AD_Rule getAD_Rule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class); } @Override public void setAD_Rule(org.compiere.model.I_AD_Rule AD_Rule) { set_ValueFromPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class, AD_Rule); } /** Set Rule. @param AD_Rule_ID Rule */ @Override public void setAD_Rule_ID (int AD_Rule_ID) { if (AD_Rule_ID < 1) set_Value (COLUMNNAME_AD_Rule_ID, null); else set_Value (COLUMNNAME_AD_Rule_ID, Integer.valueOf(AD_Rule_ID)); } /** Get Rule. @return Rule */ @Override public int getAD_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation code. @param Code Validation Code */ @Override public void setCode (java.lang.String Code) { set_Value (COLUMNNAME_Code, Code); } /** Get Validation code. @return Validation Code */ @Override public java.lang.String getCode () { return (java.lang.String)get_Value(COLUMNNAME_Code); } /** 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); } /** * Type AD_Reference_ID=540047 * Reference name: AD_BoilerPlate_VarType */ public static final int TYPE_AD_Reference_ID=540047; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Rule Engine = R */ public static final String TYPE_RuleEngine = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java
1
请在Spring Boot框架中完成以下Java代码
public Doctor timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Doctor doctor = (Doctor) o; return Objects.equals(this._id, doctor._id) && Objects.equals(this.gender, doctor.gender) && Objects.equals(this.titleShort, doctor.titleShort) && Objects.equals(this.title, doctor.title) && Objects.equals(this.firstName, doctor.firstName) && Objects.equals(this.lastName, doctor.lastName) && Objects.equals(this.address, doctor.address) && Objects.equals(this.postalCode, doctor.postalCode) && Objects.equals(this.city, doctor.city) && Objects.equals(this.phone, doctor.phone) && Objects.equals(this.fax, doctor.fax) && Objects.equals(this.timestamp, doctor.timestamp); } @Override public int hashCode() { return Objects.hash(_id, gender, titleShort, title, firstName, lastName, address, postalCode, city, phone, fax, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Doctor {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" titleShort: ").append(toIndentedString(titleShort)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" address: ").append(toIndentedString(address)).append("\n"); sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n"); sb.append(" city: ").append(toIndentedString(city)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Doctor.java
2
请完成以下Java代码
public ResponseEntity<?> getByExternalIdentifier( @PathVariable("orgCode") @Nullable final String orgCode, @ApiParam(PRODUCT_IDENTIFIER_DOC) @PathVariable(value = "externalIdentifier") @NonNull final String externalIdentifier) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); try { final ExternalIdentifier productIdentifier = ExternalIdentifier.of(externalIdentifier); final JsonGetProductsResponse response = GetProductsCommand.builder() .servicesFacade(productsServicesFacade) .albertaProductService(albertaProductService) .externalSystemService(externalSystemService) .productLookupService(productLookupService) .adLanguage(adLanguage) .orgCode(orgCode) .productIdentifier(productIdentifier) .execute(); Check.assumeEquals(response.getProducts().size(), 1, "JsonGetProductsResponse should have only one JsonProduct!"); return ResponseEntity.ok().body(response.getProducts().get(0)); } catch (final Exception ex) { logger.error(ex.getMessage(), ex); return ResponseEntity .status(HttpStatus.UNPROCESSABLE_ENTITY) .body(ex); } } private void logExportedProducts( @Nullable final Map<String, String> queryParameters, @Nullable final ExternalSystemType externalSystemType, @Nullable final Integer pInstanceId, @NonNull final JsonGetProductsResponse products) { final String exportParameters = queryParameters == null ? null : queryParameters.entrySet()
.stream() .map(entry -> entry.getKey() + "=" + entry.getValue()) .collect(Collectors.joining(", ")); products.getProducts().stream() .map(product -> TableRecordReference.of(I_M_Product.Table_Name, product.getId().getValue())) .map( productTableRecordReference -> CreateExportAuditRequest.builder() .exportParameters(exportParameters) .exportRoleId(Env.getLoggedRoleId()) .exportUserId(Env.getLoggedUserId()) .externalSystemType(externalSystemType) .exportTime(Instant.now()) .pInstanceId(pInstanceId != null ? PInstanceId.ofRepoIdOrNull(pInstanceId) : null) .tableRecordReference(productTableRecordReference) .build()) .forEach(externalSystemService::createESExportAudit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductsRestController.java
1
请在Spring Boot框架中完成以下Java代码
public void addHandle(final ApiConfigChangeHandle handle) { super.addObserver(handle); } /** * 移除配置变化监听器 * * @param handle 监听器 */ public void removeHandle(final ApiConfigChangeHandle handle) { super.deleteObserver(handle); } /** * 移除所有配置变化监听器 */ public void removeAllHandle() { super.deleteObservers(); } /** * 初始化微信配置,即第一次获取access_token * * @param refreshTime 刷新时间 */ private void initToken(final long refreshTime) { LOG.debug("开始初始化access_token........"); //记住原本的时间,用于出错回滚 final long oldTime = this.weixinTokenStartTime; this.weixinTokenStartTime = refreshTime; String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.appid + "&secret=" + this.secret; NetWorkCenter.get(url, null, (resultCode, resultJson) -> { if (HttpStatus.SC_OK == resultCode) { GetTokenResponse response = JSON.parseObject(resultJson, GetTokenResponse.class); LOG.debug("获取access_token:{}", response.getAccessToken()); if (null == response.getAccessToken()) { //刷新时间回滚 weixinTokenStartTime = oldTime; throw new WeixinException( "微信公众号token获取出错,错误信息:" + response.getErrcode() + "," + response.getErrmsg()); } accessToken = response.getAccessToken(); //设置通知点 setChanged(); notifyObservers(new ConfigChangeNotice(appid, ChangeType.ACCESS_TOKEN, accessToken)); } }); //刷新工作做完,将标识设置回false this.tokenRefreshing.set(false); } /** * 初始化微信JS-SDK,获取JS-SDK token * * @param refreshTime 刷新时间 */ private void initJSToken(final long refreshTime) { LOG.debug("初始化 jsapi_ticket........");
//记住原本的时间,用于出错回滚 final long oldTime = this.jsTokenStartTime; this.jsTokenStartTime = refreshTime; String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi"; NetWorkCenter.get(url, null, new NetWorkCenter.ResponseCallback() { @Override public void onResponse(int resultCode, String resultJson) { if (HttpStatus.SC_OK == resultCode) { GetJsApiTicketResponse response = JSON.parseObject(resultJson, GetJsApiTicketResponse.class); LOG.debug("获取jsapi_ticket:{}", response.getTicket()); if (StringUtils.isBlank(response.getTicket())) { //刷新时间回滚 jsTokenStartTime = oldTime; throw new WeixinException( "微信公众号jsToken获取出错,错误信息:" + response.getErrcode() + "," + response.getErrmsg()); } jsApiTicket = response.getTicket(); //设置通知点 setChanged(); notifyObservers(new ConfigChangeNotice(appid, ChangeType.JS_TOKEN, jsApiTicket)); } } }); //刷新工作做完,将标识设置回false this.jsRefreshing.set(false); } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\config\ApiConfig.java
2
请在Spring Boot框架中完成以下Java代码
public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Phone phone = (Phone)o; return Objects.equals(this.countryCode, phone.countryCode) && Objects.equals(this.number, phone.number); } @Override public int hashCode() { return Objects.hash(countryCode, number); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class Phone {\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" number: ").append(toIndentedString(number)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Phone.java
2
请完成以下Java代码
private void consume() { while (true) { Double value; try { value = blockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); break; } // Consume value log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value)); } } private double generateValue() { return Math.random(); } private void runProducerConsumer() { for (int i = 0; i < 2; i++) { Thread producerThread = new Thread(this::produce); producerThread.start();
} for (int i = 0; i < 3; i++) { Thread consumerThread = new Thread(this::consume); consumerThread.start(); } } public static void main(String[] args) { SimpleProducerConsumerDemonstrator simpleProducerConsumerDemonstrator = new SimpleProducerConsumerDemonstrator(); simpleProducerConsumerDemonstrator.runProducerConsumer(); sleep(2000); System.exit(0); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\SimpleProducerConsumerDemonstrator.java
1
请完成以下Java代码
protected Properties getCtx() { return InterfaceWrapperHelper.getCtx(referenceModel); } @Override public String getDisplayName() { final I_M_Product product = Services.get(IProductDAO.class).getById(getProductId()); final StringBuilder name = new StringBuilder() .append(product.getName()).append("#").append(product.getM_Product_ID()); return name.toString(); } @Override public IHUDocumentLine getReversal() { throw new UnsupportedOperationException("Getting reversal for " + this + " is not supported"); } @Override public ProductId getProductId() { return storage.getProductId(); } @Override public BigDecimal getQty() { return storage.getQtyCapacity(); } @Override public I_C_UOM getC_UOM() { return storage.getC_UOM(); } @Override public BigDecimal getQtyAllocated() { return storage.getQtyFree(); } @Override public BigDecimal getQtyToAllocate()
{ return storage.getQty().toBigDecimal(); } @Override public Object getTrxReferencedModel() { return referenceModel; } protected IProductStorage getStorage() { return storage; } @Override public IAllocationSource createAllocationSource(final I_M_HU hu) { return HUListAllocationSourceDestination.of(hu); } @Override public boolean isReadOnly() { return readonly; } @Override public void setReadOnly(final boolean readonly) { this.readonly = readonly; } @Override public I_M_HU_Item getInnerHUItem() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
1
请在Spring Boot框架中完成以下Java代码
void createDummyProductSupplies() { for (final BPartner bpartner : bpartnersRepo.findAll()) { for (final Contract contract : contractsRepo.findByBpartnerAndDeletedFalse(bpartner)) { final List<ContractLine> contractLines = contract.getContractLines(); if (contractLines.isEmpty()) { continue; } final ContractLine contractLine = contractLines.get(0); final Product product = contractLine.getProduct(); productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder() .bpartner(bpartner) .contractLine(contractLine) .productId(product.getId())
.date(LocalDate.now()) // today .qty(new BigDecimal("10")) .qtyConfirmedByUser(true) .build()); productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder() .bpartner(bpartner) .contractLine(contractLine) .productId(product.getId()) .date(LocalDate.now().plusDays(1)) // tomorrow .qty(new BigDecimal("3")) .qtyConfirmedByUser(true) .build()); } } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DummyDataProducer.java
2
请在Spring Boot框架中完成以下Java代码
public String getPoReference() { return poReference; } public void setPoReference(final String poReference) { this.poReference = poReference; } public String getShipmentDocumentno() { return shipmentDocumentno; } public void setShipmentDocumentno(final String shipmentDocumentno) { this.shipmentDocumentno = shipmentDocumentno; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (cOrderID == null ? 0 : cOrderID.hashCode()); result = prime * result + (dateOrdered == null ? 0 : dateOrdered.hashCode()); result = prime * result + (mInOutID == null ? 0 : mInOutID.hashCode()); result = prime * result + (movementDate == null ? 0 : movementDate.hashCode()); result = prime * result + (poReference == null ? 0 : poReference.hashCode()); result = prime * result + (shipmentDocumentno == null ? 0 : shipmentDocumentno.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop111V other = (Cctop111V)obj; if (cOrderID == null) { if (other.cOrderID != null) { return false; } } else if (!cOrderID.equals(other.cOrderID)) { return false; } if (dateOrdered == null) { if (other.dateOrdered != null) { return false; } } else if (!dateOrdered.equals(other.dateOrdered)) { return false; } if (mInOutID == null) { if (other.mInOutID != null) { return false; } } else if (!mInOutID.equals(other.mInOutID)) { return false; } if (movementDate == null) { if (other.movementDate != null)
{ return false; } } else if (!movementDate.equals(other.movementDate)) { return false; } if (poReference == null) { if (other.poReference != null) { return false; } } else if (!poReference.equals(other.poReference)) { return false; } if (shipmentDocumentno == null) { if (other.shipmentDocumentno != null) { return false; } } else if (!shipmentDocumentno.equals(other.shipmentDocumentno)) { return false; } return true; } @Override public String toString() { return "Cctop111V [cOrderID=" + cOrderID + ", mInOutID=" + mInOutID + ", dateOrdered=" + dateOrdered + ", movementDate=" + movementDate + ", poReference=" + poReference + ", shipmentDocumentno=" + shipmentDocumentno + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop111V.java
2
请完成以下Java代码
public boolean contains(@NonNull final AttributeId attributeId) { return byId.containsKey(attributeId); } public Optional<AttributeSetAttribute> getByAttributeId(@NonNull final AttributeId attributeId) { return Optional.ofNullable(byId.get(attributeId)); } public OptionalBoolean getMandatoryOnReceipt(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnReceipt) .orElse(OptionalBoolean.UNKNOWN); } public OptionalBoolean getMandatoryOnShipment(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnShipment) .orElse(OptionalBoolean.UNKNOWN); } public OptionalBoolean getMandatoryOnPicking(@NonNull final AttributeId attributeId) {
return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnPicking) .orElse(OptionalBoolean.UNKNOWN); } public boolean isASIMandatory(@NonNull final SOTrx soTrx) { if (!isInstanceAttribute) { return false; } else { return mandatoryType.isASIMandatory(soTrx); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\AttributeSetDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public PackagingUnit archived(Boolean archived) { this.archived = archived; return this; } /** * Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann * @return archived **/ @Schema(example = "false", description = "Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann") public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PackagingUnit packagingUnit = (PackagingUnit) o; return Objects.equals(this.unit, packagingUnit.unit) && Objects.equals(this.quantity, packagingUnit.quantity) && Objects.equals(this.pcn, packagingUnit.pcn) && Objects.equals(this.defaultPackagingUnit, packagingUnit.defaultPackagingUnit) && Objects.equals(this.archived, packagingUnit.archived); } @Override public int hashCode() { return Objects.hash(unit, quantity, pcn, defaultPackagingUnit, archived); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class PackagingUnit {\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" defaultPackagingUnit: ").append(toIndentedString(defaultPackagingUnit)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\PackagingUnit.java
2
请完成以下Java代码
public Map<Class<?>, SessionFactory> getSessionFactories() { return sessionFactories; } public HistoryManager getHistoryManager() { return getSession(HistoryManager.class); } // getters and setters ////////////////////////////////////////////////////// public TransactionContext getTransactionContext() { return transactionContext; } public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; }
public Throwable getException() { return exception; } public FailedJobCommandFactory getFailedJobCommandFactory() { return failedJobCommandFactory; } public ProcessEngineConfigurationImpl getProcessEngineConfiguration() { return processEngineConfiguration; } public FlowableEventDispatcher getEventDispatcher() { return processEngineConfiguration.getEventDispatcher(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
public List<ReferenceType2> getReference() { if (reference == null) { reference = new ArrayList<ReferenceType2>(); } return this.reference; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() {
return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ManifestType.java
1
请完成以下Java代码
public static Partition partition(int input[], int begin, int end) { int left = begin, right = end; int leftEqualKeysCount = 0, rightEqualKeysCount = 0; int partitioningValue = input[end]; while (true) { while (input[left] < partitioningValue) left++; while (input[right] > partitioningValue) { if (right == begin) break; right--; } if (left == right && input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; left++; } if (left >= right) { break; } swap(input, left, right); if (input[left] == partitioningValue) { swap(input, begin + leftEqualKeysCount, left); leftEqualKeysCount++; } if (input[right] == partitioningValue) { swap(input, right, end - rightEqualKeysCount); rightEqualKeysCount++; } left++; right--; } right = left - 1; for (int k = begin; k < begin + leftEqualKeysCount; k++, right--) { if (right >= begin + leftEqualKeysCount)
swap(input, k, right); } for (int k = end; k > end - rightEqualKeysCount; k--, left++) { if (left <= end - rightEqualKeysCount) swap(input, left, k); } return new Partition(right + 1, left - 1); } public static void quicksort(int input[], int begin, int end) { if (end <= begin) return; Partition middlePartition = partition(input, begin, end); quicksort(input, begin, middlePartition.getLeft() - 1); quicksort(input, middlePartition.getRight() + 1, end); } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\quicksort\BentleyMcIlroyPartioning.java
1
请完成以下Java代码
public boolean isSequential() { return sequential; } public void setSequential(boolean sequential) { this.sequential = sequential; } public boolean isNoWaitStatesAsyncLeave() { return noWaitStatesAsyncLeave; } public void setNoWaitStatesAsyncLeave(boolean noWaitStatesAsyncLeave) { this.noWaitStatesAsyncLeave = noWaitStatesAsyncLeave; } public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) { if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions(); } this.aggregations.getAggregations().add(aggregation);
} @Override public MultiInstanceLoopCharacteristics clone() { MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics(); clone.setValues(this); return clone; } public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) { super.setValues(otherLoopCharacteristics); setInputDataItem(otherLoopCharacteristics.getInputDataItem()); setCollectionString(otherLoopCharacteristics.getCollectionString()); if (otherLoopCharacteristics.getHandler() != null) { setHandler(otherLoopCharacteristics.getHandler().clone()); } setLoopCardinality(otherLoopCharacteristics.getLoopCardinality()); setCompletionCondition(otherLoopCharacteristics.getCompletionCondition()); setElementVariable(otherLoopCharacteristics.getElementVariable()); setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable()); setSequential(otherLoopCharacteristics.isSequential()); setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave()); if (otherLoopCharacteristics.getAggregations() != null) { setAggregations(otherLoopCharacteristics.getAggregations().clone()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java
1
请完成以下Java代码
public void setQtyRejectedToPick (final BigDecimal QtyRejectedToPick) { set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick); } @Override public BigDecimal getQtyRejectedToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); }
@Override public void setSinglePackage (final boolean SinglePackage) { set_Value (COLUMNNAME_SinglePackage, SinglePackage); } @Override public boolean isSinglePackage() { return get_ValueAsBoolean(COLUMNNAME_SinglePackage); } @Override public void setWorkplaceIndicator_ID (final int WorkplaceIndicator_ID) { throw new IllegalArgumentException ("WorkplaceIndicator_ID is virtual column"); } @Override public int getWorkplaceIndicator_ID() { return get_ValueAsInt(COLUMNNAME_WorkplaceIndicator_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step.java
1
请完成以下Java代码
public List<CashDeposit1> getCshDpst() { if (cshDpst == null) { cshDpst = new ArrayList<CashDeposit1>(); } return this.cshDpst; } /** * Gets the value of the cardTx property. * * @return * possible object is * {@link CardTransaction1 } * */ public CardTransaction1 getCardTx() { return cardTx; } /** * Sets the value of the cardTx property. * * @param value * allowed object is * {@link CardTransaction1 } * */ public void setCardTx(CardTransaction1 value) { this.cardTx = value; } /** * Gets the value of the addtlTxInf property. * * @return * possible object is * {@link String } * */ public String getAddtlTxInf() { return addtlTxInf; } /** * Sets the value of the addtlTxInf property. *
* @param value * allowed object is * {@link String } * */ public void setAddtlTxInf(String value) { this.addtlTxInf = value; } /** * Gets the value of the splmtryData property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the splmtryData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSplmtryData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SupplementaryData1 } * * */ public List<SupplementaryData1> getSplmtryData() { if (splmtryData == null) { splmtryData = new ArrayList<SupplementaryData1>(); } return this.splmtryData; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\EntryTransaction4.java
1
请完成以下Java代码
private static String toJson(final com.paypal.orders.Order apiOrder) { if (apiOrder == null) { return ""; } try { // IMPORTANT: we shall use paypal's JSON serializer, else we won't get any result return new com.braintreepayments.http.serializer.Json().serialize(apiOrder); } catch (final Exception ex) { logger.warn("Failed converting {} to JSON. Returning toString()", apiOrder, ex); return apiOrder.toString(); } } public PayPalOrder markRemoteDeleted(@NonNull final PayPalOrderId id)
{ final I_PayPal_Order existingRecord = getRecordById(id); final PayPalOrder order = toPayPalOrder(existingRecord) .toBuilder() .status(PayPalOrderStatus.REMOTE_DELETED) .build(); updateRecord(existingRecord, order); saveRecord(existingRecord); return order; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderRepository.java
1
请完成以下Java代码
public class ItemParam { @HeaderParam("headerParam") private String shopKey; @PathParam("pathParam") private String itemId; @FormParam("formParam") private String price; public String getShopKey() { return shopKey; } public void setShopKey(String shopKey) { this.shopKey = shopKey; } public String getItemId() { return itemId;
} public void setItemId(String itemId) { this.itemId = itemId; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "ItemParam{shopKey='" + shopKey + ", itemId='" + itemId + ", price='" + price + '}'; } }
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\ItemParam.java
1
请完成以下Java代码
public static <V, K> Map<V, K> invertMapUsingForLoop(Map<K, V> map) { Map<V, K> inversedMap = new HashMap<V, K>(); for (Entry<K, V> entry : map.entrySet()) { inversedMap.put(entry.getValue(), entry.getKey()); } System.out.println(inversedMap); return inversedMap; } public static <V, K> Map<V, K> invertMapUsingStreams(Map<K, V> map) { Map<V, K> inversedMap = map.entrySet() .stream() .collect(Collectors.toMap(Entry::getValue, Entry::getKey)); System.out.println(inversedMap); return inversedMap; } public static <K, V> Map<V, K> invertMapUsingMapper(Map<K, V> sourceMap) { Map<V, K> inversedMap = sourceMap.entrySet()
.stream() .collect(Collectors.toMap(Entry::getValue, Entry::getKey, (oldValue, newValue) -> oldValue)); System.out.println(inversedMap); return inversedMap; } public static <V, K> Map<V, List<K>> invertMapUsingGroupingBy(Map<K, V> map) { Map<V, List<K>> inversedMap = map.entrySet() .stream() .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList()))); System.out.println(inversedMap); return inversedMap; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-5\src\main\java\com\baeldung\map\invert\InvertHashMapExample.java
1
请完成以下Java代码
public void setTargetCaseDefinitionId(String targetProcessDefinitionId) { this.targetProcessDefinitionId = targetProcessDefinitionId; } public List<CaseInstanceBatchMigrationPartResult> getAllMigrationParts() { return allMigrationParts; } public void addMigrationPart(CaseInstanceBatchMigrationPartResult migrationPart) { if (allMigrationParts == null) { allMigrationParts = new ArrayList<>(); } allMigrationParts.add(migrationPart); if (!STATUS_COMPLETED.equals(migrationPart.getStatus())) { if (waitingMigrationParts == null) { waitingMigrationParts = new ArrayList<>(); } waitingMigrationParts.add(migrationPart); } else { if (RESULT_SUCCESS.equals(migrationPart.getResult())) { if (succesfulMigrationParts == null) { succesfulMigrationParts = new ArrayList<>(); } succesfulMigrationParts.add(migrationPart); } else { if (failedMigrationParts == null) { failedMigrationParts = new ArrayList<>(); } failedMigrationParts.add(migrationPart); }
} } public List<CaseInstanceBatchMigrationPartResult> getSuccessfulMigrationParts() { return succesfulMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getFailedMigrationParts() { return failedMigrationParts; } public List<CaseInstanceBatchMigrationPartResult> getWaitingMigrationParts() { return waitingMigrationParts; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationResult.java
1
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.error("prepare - Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return Message (clear text) * @throws Exception if not successful */ protected String doIt() throws Exception { m_C_ProjectPhase_ID = getRecord_ID(); log.info("doIt - C_ProjectPhase_ID=" + m_C_ProjectPhase_ID); if (m_C_ProjectPhase_ID == 0) throw new IllegalArgumentException("C_ProjectPhase_ID == 0"); MProjectPhase fromPhase = new MProjectPhase (getCtx(), m_C_ProjectPhase_ID, get_TrxName()); MProject fromProject = ProjectGenOrder.getProject (getCtx(), fromPhase.getC_Project_ID(), get_TrxName()); MOrder order = new MOrder (fromProject, true, MOrder.DocSubType_OnCredit); order.setDescription(order.getDescription() + " - " + fromPhase.getName()); if (!order.save()) throw new Exception("Could not create Order"); // Create an order on Phase Level if (fromPhase.getM_Product_ID() != 0) { MOrderLine ol = new MOrderLine(order); ol.setLine(fromPhase.getSeqNo()); StringBuffer sb = new StringBuffer (fromPhase.getName()); if (fromPhase.getDescription() != null && fromPhase.getDescription().length() > 0) sb.append(" - ").append(fromPhase.getDescription()); ol.setDescription(sb.toString()); // ol.setM_Product_ID(fromPhase.getM_Product_ID(), true); ol.setQty(fromPhase.getQty()); ol.setPrice(); if (fromPhase.getPriceActual() != null && fromPhase.getPriceActual().compareTo(Env.ZERO) != 0) ol.setPrice(fromPhase.getPriceActual()); orderLineBL.setTax(ol); if (!ol.save()) log.error("doIt - Lines not generated"); return "@C_Order_ID@ " + order.getDocumentNo() + " (1)"; } // Project Tasks
int count = 0; List<I_C_ProjectTask> tasks = fromPhase.getTasks (); for (int i = 0; i < tasks.size(); i++) { MOrderLine ol = new MOrderLine(order); ol.setLine(tasks.get(i).getSeqNo()); StringBuffer sb = new StringBuffer (tasks.get(i).getName()); if (tasks.get(i).getDescription() != null && tasks.get(i).getDescription().length() > 0) sb.append(" - ").append(tasks.get(i).getDescription()); ol.setDescription(sb.toString()); // ol.setM_Product_ID(tasks.get(i).getM_Product_ID(), true); ol.setQty(tasks.get(i).getQty()); ol.setPrice(); orderLineBL.setTax(ol); if (ol.save()) count++; } // for all lines if (tasks.size() != count) log.error("doIt - Lines difference - ProjectTasks=" + tasks.size() + " <> Saved=" + count); return "@C_Order_ID@ " + order.getDocumentNo() + " (" + count + ")"; } // doIt } // ProjectPhaseGenOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectPhaseGenOrder.java
1
请完成以下Java代码
private static String getValueAsString(EntityKeyValue entityKeyValue) { Object result = null; switch (entityKeyValue.getDataType()) { case STRING: result = entityKeyValue.getStrValue(); break; case JSON: result = entityKeyValue.getJsonValue(); break; case LONG: result = entityKeyValue.getLngValue(); break; case DOUBLE: result = entityKeyValue.getDblValue(); break; case BOOLEAN: result = entityKeyValue.getBoolValue(); break; } return String.valueOf(result); } public boolean processAlarmClear(TbContext ctx, Alarm alarmNf) {
boolean updated = false; if (currentAlarm != null && currentAlarm.getId().equals(alarmNf.getId())) { currentAlarm = null; for (AlarmRuleState state : createRulesSortedBySeverityDesc) { updated = clearAlarmState(updated, state); } } return updated; } public void processAckAlarm(Alarm alarm) { if (currentAlarm != null && currentAlarm.getId().equals(alarm.getId())) { currentAlarm.setAcknowledged(alarm.isAcknowledged()); currentAlarm.setAckTs(alarm.getAckTs()); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\AlarmState.java
1
请完成以下Java代码
public BigDecimal getAllocatedAmt(final PaymentId paymentId) { final I_C_Payment payment = getById(paymentId); return getAllocatedAmt(payment); } @Override public BigDecimal getAllocatedAmt(final I_C_Payment payment) { Adempiere.assertUnitTestMode(); BigDecimal sum = BigDecimal.ZERO; for (final I_C_AllocationLine line : retrieveAllocationLines(payment)) { final I_C_AllocationHdr ah = line.getC_AllocationHdr(); final BigDecimal lineAmt = line.getAmount(); if (null != ah && ah.getC_Currency_ID() != payment.getC_Currency_ID()) { final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert( lineAmt, // Amt CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID CurrencyId.ofRepoId(payment.getC_Currency_ID()), // CurTo_ID ah.getDateTrx().toInstant(), // ConvDate CurrencyConversionTypeId.ofRepoIdOrNull(payment.getC_ConversionType_ID()), ClientId.ofRepoId(line.getAD_Client_ID()), OrgId.ofRepoId(line.getAD_Org_ID())); sum = sum.add(lineAmtConv); } else
{ sum = sum.add(lineAmt); } } return sum; } @Override public void updateDiscountAndPayment(final I_C_Payment payment, final int c_Invoice_ID, final I_C_DocType c_DocType) { Adempiere.assertUnitTestMode(); throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\PlainPaymentDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class TaxExtensionType { @XmlElement(name = "VATAmount") protected BigDecimal vatAmount; @XmlElement(name = "DocumentDefaultTax") protected BigDecimal documentDefaultTax; /** * Gets the value of the vatAmount property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getVATAmount() { return vatAmount; } /** * Sets the value of the vatAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setVATAmount(BigDecimal value) { this.vatAmount = value; } /** * Gets the value of the documentDefaultTax property. * * @return * possible object is * {@link BigDecimal } * */
public BigDecimal getDocumentDefaultTax() { return documentDefaultTax; } /** * Sets the value of the documentDefaultTax property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setDocumentDefaultTax(BigDecimal value) { this.documentDefaultTax = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\TaxExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
SysDepartModel queryCompByOrgCodeAndLevel(@RequestParam("orgCode") String orgCode, @RequestParam("level") Integer level){ return sysBaseApi.queryCompByOrgCodeAndLevel(orgCode,level); } /** * 运行AIRag流程 * for [QQYUN-13634]在baseapi里面封装方法,方便其他模块调用 * @param airagFlowDTO * @return 流程执行结果,可能是String或者Map * @return */ @PostMapping(value = "/runAiragFlow") Object runAiragFlow(@RequestBody AiragFlowDTO airagFlowDTO) { return sysBaseApi.runAiragFlow(airagFlowDTO); } /** * 根据部门code或部门id获取部门名称(当前和上级部门) * * @param orgCode 部门编码 * @param depId 部门id * @return String 部门名称 */ @GetMapping(value = "/getDepartPathNameByOrgCode") String getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode, @RequestParam(name = "depId", required = false) String depId) { return sysBaseApi.getDepartPathNameByOrgCode(orgCode, depId); } /** * 根据部门ID查询用户ID * @param deptIds
* @return */ @GetMapping("/queryUserIdsByCascadeDeptIds") public List<String> queryUserIdsByCascadeDeptIds(@RequestParam("deptIds") List<String> deptIds){ return sysBaseApi.queryUserIdsByCascadeDeptIds(deptIds); } /** * 推送uniapp 消息 * @param pushMessageDTO * @return */ @PostMapping("/uniPushMsgToUser") public void uniPushMsgToUser(@RequestBody PushMessageDTO pushMessageDTO){ sysBaseApi.uniPushMsgToUser(pushMessageDTO); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\api\controller\SystemApiController.java
2
请完成以下Java代码
public class BranchAndFinancialInstitutionIdentification4CHBicOrClrId { @XmlElement(name = "FinInstnId", required = true) protected FinancialInstitutionIdentification7CHBicOrClrId finInstnId; /** * Gets the value of the finInstnId property. * * @return * possible object is * {@link FinancialInstitutionIdentification7CHBicOrClrId } * */ public FinancialInstitutionIdentification7CHBicOrClrId getFinInstnId() { return finInstnId;
} /** * Sets the value of the finInstnId property. * * @param value * allowed object is * {@link FinancialInstitutionIdentification7CHBicOrClrId } * */ public void setFinInstnId(FinancialInstitutionIdentification7CHBicOrClrId value) { this.finInstnId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\BranchAndFinancialInstitutionIdentification4CHBicOrClrId.java
1
请完成以下Java代码
protected void verifyResultVariableName(Process process, ServiceTask serviceTask, List<ValidationError> errors) { if ( StringUtils.isNotEmpty(serviceTask.getResultVariableName()) && (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(serviceTask.getImplementationType()) || ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(serviceTask.getImplementationType())) ) { addError(errors, Problems.SERVICE_TASK_RESULT_VAR_NAME_WITH_DELEGATE, process, serviceTask); } } protected void verifyWebservice( BpmnModel bpmnModel, Process process, ServiceTask serviceTask, List<ValidationError> errors ) { if ( ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(serviceTask.getImplementationType()) && StringUtils.isNotEmpty(serviceTask.getOperationRef())
) { boolean operationFound = false; if (bpmnModel.getInterfaces() != null && !bpmnModel.getInterfaces().isEmpty()) { for (Interface bpmnInterface : bpmnModel.getInterfaces()) { if (bpmnInterface.getOperations() != null && !bpmnInterface.getOperations().isEmpty()) { for (Operation operation : bpmnInterface.getOperations()) { if (operation.getId() != null && operation.getId().equals(serviceTask.getOperationRef())) { operationFound = true; } } } } } if (!operationFound) { addError(errors, Problems.SERVICE_TASK_WEBSERVICE_INVALID_OPERATION_REF, process, serviceTask); } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\ServiceTaskValidator.java
1
请在Spring Boot框架中完成以下Java代码
private boolean isCandidate(PropertyDescriptor descriptor) { return descriptor.isProperty(this.environment) || descriptor.isNested(this.environment); } /** * Wrapper around a {@link TypeElement} that could be bound. */ private static class Bindable { private final TypeElement type; private final List<ExecutableElement> constructors; private final List<ExecutableElement> boundConstructors; Bindable(TypeElement type, List<ExecutableElement> constructors, List<ExecutableElement> boundConstructors) { this.type = type; this.constructors = constructors; this.boundConstructors = boundConstructors; } TypeElement getType() { return this.type; } boolean isConstructorBindingEnabled() { return !this.boundConstructors.isEmpty(); } ExecutableElement getBindConstructor() { if (this.boundConstructors.isEmpty()) { return findBoundConstructor(); } if (this.boundConstructors.size() == 1) { return this.boundConstructors.get(0); } return null; } private ExecutableElement findBoundConstructor() { ExecutableElement boundConstructor = null; for (ExecutableElement candidate : this.constructors) { if (!candidate.getParameters().isEmpty()) { if (boundConstructor != null) { return null; } boundConstructor = candidate; }
} return boundConstructor; } static Bindable of(TypeElement type, MetadataGenerationEnvironment env) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(type.getEnclosedElements()); List<ExecutableElement> boundConstructors = getBoundConstructors(type, env, constructors); return new Bindable(type, constructors, boundConstructors); } private static List<ExecutableElement> getBoundConstructors(TypeElement type, MetadataGenerationEnvironment env, List<ExecutableElement> constructors) { ExecutableElement bindConstructor = deduceBindConstructor(type, constructors, env); if (bindConstructor != null) { return Collections.singletonList(bindConstructor); } return constructors.stream().filter(env::hasConstructorBindingAnnotation).toList(); } private static ExecutableElement deduceBindConstructor(TypeElement type, List<ExecutableElement> constructors, MetadataGenerationEnvironment env) { if (constructors.size() == 1) { ExecutableElement candidate = constructors.get(0); if (!candidate.getParameters().isEmpty() && !env.hasAutowiredAnnotation(candidate)) { if (type.getNestingKind() == NestingKind.MEMBER && candidate.getModifiers().contains(Modifier.PRIVATE)) { return null; } return candidate; } } return null; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\PropertyDescriptorResolver.java
2
请在Spring Boot框架中完成以下Java代码
public class C_Order_CreateCompensationMultiGroups extends OrderCompensationGroupProcess { @Autowired private GroupTemplateRepository groupTemplateRepo; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { return acceptIfEligibleOrder(context) .and(() -> acceptIfOrderLinesNotInGroup(context)); } @Override protected String doIt() { final List<I_C_OrderLine> selectedOrderLines = getSelectedOrderLines(); Check.assumeNotEmpty(selectedOrderLines, "selectedOrderLines is not empty"); final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = extractOrderLineIdsByGroupTemplate(selectedOrderLines); if (orderLineIdsByGroupTemplate.isEmpty()) { throw new AdempiereException("Nothing to group"); // TODO trl } final List<Group> groups = orderLineIdsByGroupTemplate.asMap() .entrySet() .stream() .map(e -> createGroup(e.getKey(), e.getValue())) .collect(ImmutableList.toImmutableList()); final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroups(groups); groupsRepo.renumberOrderLinesForOrderId(orderId); return MSG_OK; } private ListMultimap<GroupTemplate, OrderLineId> extractOrderLineIdsByGroupTemplate(final List<I_C_OrderLine> orderLines) { final List<I_C_OrderLine> orderLinesSorted = orderLines.stream() .sorted(Comparator.comparing(I_C_OrderLine::getLine)) .collect(ImmutableList.toImmutableList());
final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = LinkedListMultimap.create(); for (final I_C_OrderLine orderLine : orderLinesSorted) { final GroupTemplate groupTemplate = extractGroupTemplate(orderLine); if (groupTemplate == null) { continue; } orderLineIdsByGroupTemplate.put(groupTemplate, OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID())); } return orderLineIdsByGroupTemplate; } @Nullable private GroupTemplate extractGroupTemplate(final I_C_OrderLine orderLine) { final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID()); if (productId == null) { return null; } final IProductDAO productsRepo = Services.get(IProductDAO.class); final ProductCategoryId productCategoryId = productsRepo.retrieveProductCategoryByProductId(productId); final I_M_Product_Category productCategory = productsRepo.getProductCategoryById(productCategoryId, I_M_Product_Category.class); final GroupTemplateId groupTemplateId = GroupTemplateId.ofRepoIdOrNull(productCategory.getC_CompensationGroup_Schema_ID()); if (groupTemplateId == null) { return null; } return groupTemplateRepo.getById(groupTemplateId); } private Group createGroup(final GroupTemplate groupTemplate, final Collection<OrderLineId> orderLineIds) { return groupsRepo.prepareNewGroup() .groupTemplate(groupTemplate) .createGroup(orderLineIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\C_Order_CreateCompensationMultiGroups.java
2
请在Spring Boot框架中完成以下Java代码
public String getGroupsClaim() { return groupsClaim; } /** * @param groupsClaim the groupsClaim to set */ public void setGroupsClaim(String groupsClaim) { this.groupsClaim = groupsClaim; } /** * @return the groupToAuthorities */ public Map<String, List<String>> getGroupToAuthorities() { return groupToAuthorities; } /** * @param groupToAuthorities the groupToAuthorities to set */ public void setGroupToAuthorities(Map<String, List<String>> groupToAuthorities) {
this.groupToAuthorities = groupToAuthorities; } /** * @return the authoritiesPrefix */ public String getAuthoritiesPrefix() { return authoritiesPrefix; } /** * @param authoritiesPrefix the authoritiesPrefix to set */ public void setAuthoritiesPrefix(String authoritiesPrefix) { this.authoritiesPrefix = authoritiesPrefix; } }
repos\tutorials-master\spring-security-modules\spring-security-azuread\src\main\java\com\baeldung\security\azuread\config\JwtAuthorizationProperties.java
2
请完成以下Java代码
public void setC_ElementValue_ID (final int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_Value (COLUMNNAME_C_ElementValue_ID, null); else set_Value (COLUMNNAME_C_ElementValue_ID, C_ElementValue_ID); } @Override public int getC_ElementValue_ID() { return get_ValueAsInt(COLUMNNAME_C_ElementValue_ID); } @Override public void setC_Invoice_Acct_ID (final int C_Invoice_Acct_ID) { if (C_Invoice_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, C_Invoice_Acct_ID); } @Override public int getC_Invoice_Acct_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Acct_ID); } @Override public org.compiere.model.I_C_Invoice getC_Invoice() { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } @Override public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice) { set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice); } @Override public void setC_Invoice_ID (final int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, C_Invoice_ID); } @Override public int getC_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_ID); } @Override public org.compiere.model.I_C_InvoiceLine getC_InvoiceLine()
{ return get_ValueAsPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class); } @Override public void setC_InvoiceLine(final org.compiere.model.I_C_InvoiceLine C_InvoiceLine) { set_ValueFromPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class, C_InvoiceLine); } @Override public void setC_InvoiceLine_ID (final int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, C_InvoiceLine_ID); } @Override public int getC_InvoiceLine_ID() { return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerDispatchMessageProcessor implements Processor { @Override public void process(final Exchange exchange) throws Exception { final JsonResponseComposite jsonResponseComposite = exchange.getIn().getBody(JsonResponseComposite.class); final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class); final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); final String payload = objectMapper.writeValueAsString(jsonResponseComposite); final JsonRabbitMQHttpMessage jsonRabbitMQHttpMessage = JsonRabbitMQHttpMessage.builder() .routingKey(routeContext.getRoutingKey()) .jsonRabbitMQProperties(getDefaultRabbitMQProperties()) .payload(payload) .payloadEncoding(RABBIT_MQ_PAYLOAD_ENCODING) .build(); final DispatchMessageRequest dispatchMessageRequest = DispatchMessageRequest.builder()
.url(routeContext.getRemoteUrl()) .authToken(routeContext.getAuthToken()) .message(jsonRabbitMQHttpMessage) .build(); exchange.getIn().setBody(dispatchMessageRequest); } @NonNull private JsonRabbitMQProperties getDefaultRabbitMQProperties() { return JsonRabbitMQProperties.builder() .delivery_mode(RABBITMQ_PROPS_PERSISTENT_DELIVERY_MODE) .header(RABBITMQ_HEADERS_SUBJECT, RABBITMQ_HEADERS_METASFRESH_BUSINESS_PARTNER_SYNC) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-rabbitmq\src\main\java\de\metas\camel\externalsystems\rabbitmq\bpartner\processor\BPartnerDispatchMessageProcessor.java
2
请完成以下Java代码
public static I_AD_Field createADField( final I_AD_Tab tab, final I_AD_Column adColumn, final boolean displayedIfNotIDColumn, @Nullable final String p_EntityType) { final String entityTypeToUse; if (Check.isEmpty(p_EntityType, true)) { entityTypeToUse = tab.getEntityType(); // Use Tab's Entity Type - teo_sarca, BF [ 2827782 ] } else { entityTypeToUse = p_EntityType; } final MField field = new MField(tab);
field.setColumn(adColumn); field.setEntityType(entityTypeToUse); if (adColumn.isKey() || !displayedIfNotIDColumn) { field.setIsDisplayed(false); field.setIsDisplayedGrid(false); } if("AD_Client_ID".equals(adColumn.getColumnName())) { field.setIsReadOnly(true); } InterfaceWrapperHelper.save(field); return field; } } // TabCreateFields
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\AD_Tab_CreateFields.java
1
请完成以下Java代码
private List<ShipmentSchedule> retrieveShipmentSchedulesByPackageId(@NonNull final PackageId packageId) { return shipmentScheduleRepository.loadByPackageId(packageId); } private Set<CarrierServiceId> retrieveCarrierServiceIdsForShipmentSchedules(@NonNull final List<ShipmentSchedule> schedules) { return carrierServiceRepository.getAssignedServiceIdsByShipmentScheduleIds(schedules.stream() .map(ShipmentSchedule::getId) .collect(Collectors.toSet())); } private Optional<BigDecimal> extractWeightInKg(@NonNull final I_M_Package mpackage) { if (InterfaceWrapperHelper.isNull(mpackage, I_M_Package.COLUMNNAME_PackageWeight)) { return Optional.empty(); } final BigDecimal weightInKg = kgPrecision.round(mpackage.getPackageWeight()); // we assume it's in Kg return weightInKg.signum() > 0 ? Optional.of(weightInKg) : Optional.empty(); } private void createAndSendDeliveryOrder( @NonNull final DeliveryOrderKey deliveryOrderKey, @NonNull final Collection<I_M_Package> mpackages) { final ShipperId shipperId = deliveryOrderKey.getShipperId(); final ShipperGatewayId shipperGatewayId = getShipperGatewayId(shipperId); final DeliveryOrderService deliveryOrderRepository = shipperRegistry.getDeliveryOrderService(shipperGatewayId); final ImmutableSet<PackageInfo> packageInfos = mpackages.stream() .map(mpackage -> PackageInfo.builder() .packageId(PackageId.ofRepoId(mpackage.getM_Package_ID())) .poReference(mpackage.getPOReference()) .description(StringUtils.trimBlankToNull(mpackage.getDescription())) .weightInKg(extractWeightInKg(mpackage).orElse(null)) .packageDimension(extractPackageDimensions(mpackage)) .build())
.collect(ImmutableSet.toImmutableSet()); final CreateDraftDeliveryOrderRequest request = CreateDraftDeliveryOrderRequest.builder() .deliveryOrderKey(deliveryOrderKey) .packageInfos(packageInfos) .build(); final DraftDeliveryOrderCreator shipperGatewayService = shipperRegistry.getShipperGatewayService(shipperGatewayId); DeliveryOrder deliveryOrder = shipperGatewayService.createDraftDeliveryOrder(request); deliveryOrder = deliveryOrderRepository.save(deliveryOrder); DeliveryOrderWorkpackageProcessor.enqueueOnTrxCommit(deliveryOrder.getId(), shipperGatewayId, deliveryOrderKey.getAsyncBatchId()); } private static PackageDimensions extractPackageDimensions(@NonNull final I_M_Package mpackage) { return PackageDimensions.builder() .lengthInCM(mpackage.getLengthInCm()) .widthInCM(mpackage.getWidthInCm()) .heightInCM(mpackage.getHeightInCm()) .build(); } private ShipperGatewayId getShipperGatewayId(final ShipperId shipperId) { return shipperDAO.getShipperGatewayId(shipperId).orElseThrow(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean hasServiceSupport(@NonNull final ShipperGatewayId shipperGatewayId) { return shipperRegistry.hasServiceSupport(shipperGatewayId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\ShipperGatewayFacade.java
1
请完成以下Java代码
public PhoneNumber instantiate(ValueAccess values) { return new PhoneNumber(values.getValue(0, Integer.class), values.getValue(1, Integer.class), values.getValue(2, Integer.class)); } @Override public Class<?> embeddable() { return PhoneNumber.class; } @Override public Class returnedClass() { return PhoneNumber.class; } @Override public boolean equals(PhoneNumber x, PhoneNumber y) { if (x == y) { return true; } if (Objects.isNull(x) || Objects.isNull(y)) { return false; } return x.equals(y); } @Override public int hashCode(PhoneNumber x) { return x.hashCode(); } @Override public PhoneNumber deepCopy(PhoneNumber value) { if (Objects.isNull(value)) { return null; } return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber()); } @Override
public boolean isMutable() { return false; } @Override public Serializable disassemble(PhoneNumber value) { return (Serializable) value; } @Override public PhoneNumber assemble(Serializable cached, Object owner) { return (PhoneNumber) cached; } @Override public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) { return detached; } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\PhoneNumberType.java
1
请完成以下Java代码
public void destroy() { filterConfig = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { applyFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } /** * Apply the filter to the given request/response. * * This method must be provided by subclasses to perform actual work. * * @param request * @param response * @param chain * * @throws IOException * @throws ServletException */ protected abstract void applyFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException; /** * Returns true if the given web resource exists. * * @param name * @return */ protected boolean hasWebResource(String name) { try { URL resource = filterConfig.getServletContext().getResource(name); return resource != null; } catch (MalformedURLException e) { return false; } } /** * Returns the string contents of a web resource with the given name. * * The resource must be static and text based. * * @param name the name of the resource *
* @return the resource contents * * @throws IOException */ protected String getWebResourceContents(String name) throws IOException { InputStream is = null; try { is = filterConfig.getServletContext().getResourceAsStream(name); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringWriter writer = new StringWriter(); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.append("\n"); } return writer.toString(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\filter\AbstractTemplateFilter.java
1
请完成以下Java代码
public LookupValue findById(final Object idObj) { final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey()); if (idNormalized == null) { return null; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getById(idNormalized); } @Override public @NonNull LookupValuesList findByIdsOrdered(@NonNull final Collection<?> ids) { final ImmutableList<Object> idsNormalized = LookupValue.normalizeIds(ids, fetcher.isNumericKey()); if (idsNormalized.isEmpty()) { return LookupValuesList.EMPTY; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getByIdsInOrder(idsNormalized); } @Override public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { final String tableName = fetcher.getLookupTableName() .orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null TableName: " + fetcher));
return DocumentZoomIntoInfo.of(tableName, id); } @Override public Optional<WindowId> getZoomIntoWindowId() { return fetcher.getZoomIntoWindowId(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(cacheByPartition.stats()); } @Override public void cacheInvalidate() { cacheByPartition.reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\FullyCachedLookupDataSource.java
1
请完成以下Java代码
protected static class CacheValue { protected final String json; protected final int version; protected final String definitionId; public CacheValue(String json, ChannelDefinition definition) { this.json = json; this.version = definition.getVersion(); this.definitionId = definition.getId(); } } protected static class CacheRegisteredChannel implements RegisteredChannel { protected final CacheValue value; protected CacheRegisteredChannel(CacheValue value) { this.value = value; } @Override public int getChannelDefinitionVersion() { return value.version; } @Override public String getChannelDefinitionId() { return value.definitionId; } } protected class ChannelRegistrationImpl implements ChannelRegistration { protected final boolean registered;
protected final CacheRegisteredChannel previousChannel; protected final CacheKey cacheKey; public ChannelRegistrationImpl(boolean registered, CacheRegisteredChannel previousChannel, CacheKey cacheKey) { this.registered = registered; this.previousChannel = previousChannel; this.cacheKey = cacheKey; } @Override public boolean registered() { return registered; } @Override public RegisteredChannel previousChannel() { return previousChannel; } @Override public void rollback() { CacheValue cacheValue = previousChannel != null ? previousChannel.value : null; if (cacheValue == null) { cache.remove(cacheKey); } else { cache.put(cacheKey, cacheValue); } } } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\DefaultInboundChannelModelCacheManager.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_MediatedCommissionSettings_ID (final int C_MediatedCommissionSettings_ID) { if (C_MediatedCommissionSettings_ID < 1) set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, null); else set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, C_MediatedCommissionSettings_ID); } @Override public int getC_MediatedCommissionSettings_ID() { return get_ValueAsInt(COLUMNNAME_C_MediatedCommissionSettings_ID); } @Override public void setCommission_Product_ID (final int Commission_Product_ID) { if (Commission_Product_ID < 1) set_Value (COLUMNNAME_Commission_Product_ID, null); else set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID); } @Override public int getCommission_Product_ID() { return get_ValueAsInt(COLUMNNAME_Commission_Product_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() {
return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPointsPrecision (final int PointsPrecision) { set_Value (COLUMNNAME_PointsPrecision, PointsPrecision); } @Override public int getPointsPrecision() { return get_ValueAsInt(COLUMNNAME_PointsPrecision); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_MediatedCommissionSettings.java
1
请完成以下Java代码
public void reactivated(CmmnActivityExecution execution) { // noop } // repetition /////////////////////////////////////////////////////////////// public void repeat(CmmnActivityExecution execution, String standardEvent) { CmmnActivity activity = execution.getActivity(); boolean repeat = false; if (activity.getEntryCriteria().isEmpty()) { List<String> events = activity.getProperties().get(CmmnProperties.REPEAT_ON_STANDARD_EVENTS); if (events != null && events.contains(standardEvent)) { repeat = evaluateRepetitionRule(execution); } } else { if (ENABLE.equals(standardEvent) || START.equals(standardEvent) || OCCUR.equals(standardEvent)) { repeat = evaluateRepetitionRule(execution); } } if (repeat) { CmmnActivityExecution parent = execution.getParent(); // instantiate a new instance of given activity List<CmmnExecution> children = parent.createChildExecutions(Arrays.asList(activity)); // start the lifecycle of the new instance parent.triggerChildExecutionsLifecycle(children); } } // helper ////////////////////////////////////////////////////////////////////// protected void ensureTransitionAllowed(CmmnActivityExecution execution, CaseExecutionState expected, CaseExecutionState target, String transition) { String id = execution.getId(); CaseExecutionState currentState = execution.getCurrentState(); // the state "suspending" or "terminating" will set immediately // inside the corresponding AtomicOperation, that's why the // previous state will be used to ensure that the transition // is allowed.
if (execution.isTerminating() || execution.isSuspending()) { currentState = execution.getPreviousState(); } // is the case execution already in the target state if (target.equals(currentState)) { throw LOG.isAlreadyInStateException(transition, id, target); } else // is the case execution in the expected state if (!expected.equals(currentState)) { throw LOG.unexpectedStateException(transition, id, expected, currentState); } } protected void ensureNotCaseInstance(CmmnActivityExecution execution, String transition) { if (execution.isCaseInstanceExecution()) { String id = execution.getId(); throw LOG.impossibleTransitionException(transition, id); } } protected CmmnActivity getActivity(CmmnActivityExecution execution) { String id = execution.getId(); CmmnActivity activity = execution.getActivity(); ensureNotNull(PvmException.class, "Case execution '"+id+"': has no current activity.", "activity", activity); return activity; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\PlanItemDefinitionActivityBehavior.java
1
请完成以下Java代码
public Flux<ClientGraphQlResponse> executeSubscription() { return initRequestSpec().executeSubscription(); } private GraphQLQueryRequest createRequest() { Assert.state(this.projectionNode != null || this.coercingMap == null, "Coercing map provided without projection"); GraphQLQueryRequest request; if (this.coercingMap != null && this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode, this.coercingMap); } else if (this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode); } else { request = new GraphQLQueryRequest(this.query); } return request; } @SuppressWarnings("NullAway") private GraphQlClient.RequestSpec initRequestSpec() { String document; String operationName; if (!this.additionalRequests.isEmpty()) { this.additionalRequests.add(createRequest()); document = new GraphQLMultiQueryRequest(this.additionalRequests).serialize(); operationName = null; } else { document = createRequest().serialize();
operationName = (this.query.getName() != null) ? this.query.getName() : null; } return DgsGraphQlClient.this.graphQlClient.document(document) .operationName(operationName) .attributes((map) -> { if (this.attributes != null) { map.putAll(this.attributes); } }); } private String getDefaultPath() { return this.query.getOperationName(); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DgsGraphQlClient.java
1
请完成以下Java代码
default String getListenerId() { throw new UnsupportedOperationException("This container does not support retrieving the listener id"); } /** * The 'id' attribute of the main {@code @KafkaListener} container, if this container * is for a retry topic; null otherwise. * @return the id. * @since 3.0 */ @Nullable default String getMainListenerId() { throw new UnsupportedOperationException("This container does not support retrieving the main listener id"); } /** * Get arbitrary static information that will be added to the * {@link KafkaHeaders#LISTENER_INFO} header of all records. * @return the info. * @since 2.8.6 */ @Nullable default byte[] getListenerInfo() { throw new UnsupportedOperationException("This container does not support retrieving the listener info"); } /** * If this container has child containers, return true if at least one child is running. If there are not * child containers, returns {@link #isRunning()}. * @return true if a child is running. * @since 2.7.3 */ default boolean isChildRunning() { return isRunning(); } /** * Return true if the container is running, has never been started, or has been * stopped. * @return true if the state is as expected. * @since 2.8 * @see #stopAbnormally(Runnable) */ default boolean isInExpectedState() { return true; } /** * Stop the container after some exception so that {@link #isInExpectedState()} will * return false. * @param callback the callback. * @since 2.8 * @see #isInExpectedState()
*/ default void stopAbnormally(Runnable callback) { stop(callback); } /** * If this container has child containers, return the child container that is assigned * the topic/partition. Return this when there are no child containers. * @param topic the topic. * @param partition the partition. * @return the container. */ default MessageListenerContainer getContainerFor(String topic, int partition) { return this; } /** * Notify a parent container that a child container has stopped. * @param child the container. * @param reason the reason. * @since 2.9.7 */ default void childStopped(MessageListenerContainer child, ConsumerStoppedEvent.Reason reason) { } /** * Notify a parent container that a child container has started. * @param child the container. * @since 3.3 */ default void childStarted(MessageListenerContainer child) { } @Override default void destroy() { stop(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\MessageListenerContainer.java
1
请完成以下Java代码
public WebEndpointResponse<QuartzGroupsDescriptor> quartzJobOrTriggerGroups(@Selector String jobsOrTriggers) throws SchedulerException { return handle(jobsOrTriggers, this.delegate::quartzJobGroups, this.delegate::quartzTriggerGroups); } @ReadOperation public WebEndpointResponse<Object> quartzJobOrTriggerGroup(@Selector String jobsOrTriggers, @Selector String group) throws SchedulerException { return handle(jobsOrTriggers, () -> this.delegate.quartzJobGroupSummary(group), () -> this.delegate.quartzTriggerGroupSummary(group)); } @ReadOperation public WebEndpointResponse<Object> quartzJobOrTrigger(SecurityContext securityContext, @Selector String jobsOrTriggers, @Selector String group, @Selector String name) throws SchedulerException { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); return handle(jobsOrTriggers, () -> this.delegate.quartzJob(group, name, showUnsanitized), () -> this.delegate.quartzTrigger(group, name, showUnsanitized)); } /** * Trigger a Quartz job. * @param jobs path segment "jobs" * @param group job's group * @param name job name * @param state desired state * @return web endpoint response * @throws SchedulerException if there is an error triggering the job */ @WriteOperation public WebEndpointResponse<Object> triggerQuartzJob(@Selector String jobs, @Selector String group, @Selector String name, String state) throws SchedulerException { if ("jobs".equals(jobs) && "running".equals(state)) { return handleNull(this.delegate.triggerQuartzJob(group, name)); } return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST); } private <T> WebEndpointResponse<T> handle(String jobsOrTriggers, ResponseSupplier<T> jobAction, ResponseSupplier<T> triggerAction) throws SchedulerException { if ("jobs".equals(jobsOrTriggers)) { return handleNull(jobAction.get()); } if ("triggers".equals(jobsOrTriggers)) { return handleNull(triggerAction.get()); } return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
} private <T> WebEndpointResponse<T> handleNull(@Nullable T value) { return (value != null) ? new WebEndpointResponse<>(value) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } @FunctionalInterface private interface ResponseSupplier<T> { @Nullable T get() throws SchedulerException; } static class QuartzEndpointWebExtensionRuntimeHints implements RuntimeHintsRegistrar { private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { this.bindingRegistrar.registerReflectionHints(hints.reflection(), QuartzGroupsDescriptor.class, QuartzJobDetailsDescriptor.class, QuartzJobGroupSummaryDescriptor.class, QuartzTriggerGroupSummaryDescriptor.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-quartz\src\main\java\org\springframework\boot\quartz\actuate\endpoint\QuartzEndpointWebExtension.java
1
请完成以下Java代码
private String getAlphaNumerics(String value) { StringBuilder result = new StringBuilder(value.length()); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9') { result.append(ch); } } return result.toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return this.lowerCaseAlphaNumeric.equals(((EndpointId) obj).lowerCaseAlphaNumeric); } @Override public int hashCode() { return this.lowerCaseAlphaNumeric.hashCode(); } /** * Return a lower-case version of the endpoint ID. * @return the lower-case endpoint ID */ public String toLowerCaseString() { return this.lowerCaseValue; } @Override public String toString() { return this.value; } /** * Factory method to create a new {@link EndpointId} of the specified value. * @param value the endpoint ID value * @return an {@link EndpointId} instance */ public static EndpointId of(String value) { return new EndpointId(value);
} /** * Factory method to create a new {@link EndpointId} of the specified value. This * variant will respect the {@code management.endpoints.migrate-legacy-names} property * if it has been set in the {@link Environment}. * @param environment the Spring environment * @param value the endpoint ID value * @return an {@link EndpointId} instance * @since 2.2.0 */ public static EndpointId of(Environment environment, String value) { Assert.notNull(environment, "'environment' must not be null"); return new EndpointId(migrateLegacyId(environment, value)); } private static String migrateLegacyId(Environment environment, String value) { if (environment.getProperty(MIGRATE_LEGACY_NAMES_PROPERTY, Boolean.class, false)) { return value.replaceAll("[-.]+", ""); } return value; } /** * Factory method to create a new {@link EndpointId} from a property value. More * lenient than {@link #of(String)} to allow for common "relaxed" property variants. * @param value the property value to convert * @return an {@link EndpointId} instance */ public static EndpointId fromPropertyValue(String value) { return new EndpointId(value.replace("-", "")); } static void resetLoggedWarnings() { loggedWarnings.clear(); } private static void logWarning(String value) { if (logger.isWarnEnabled() && loggedWarnings.add(value)) { logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format."); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\EndpointId.java
1
请在Spring Boot框架中完成以下Java代码
public Properties getCtx() { final Object referencedObject = getReferencedObject(); if (referencedObject == null) { return Env.getCtx(); } return InterfaceWrapperHelper.getCtx(referencedObject); } @Override public OptionalBoolean getManualPriceEnabled() { return manualPriceEnabled; } @Override public IEditablePricingContext setManualPriceEnabled(final boolean manualPriceEnabled) { this.manualPriceEnabled = OptionalBoolean.ofBoolean(manualPriceEnabled); return this; } @Override @Nullable public CountryId getCountryId() { return countryId; } @Override public IEditablePricingContext setCountryId(@Nullable final CountryId countryId) { this.countryId = countryId; return this; } @Override public boolean isFailIfNotCalculated() { return failIfNotCalculated; } @Override public IEditablePricingContext setFailIfNotCalculated() { this.failIfNotCalculated = true; return this; } @Override public IEditablePricingContext setSkipCheckingPriceListSOTrxFlag(final boolean skipCheckingPriceListSOTrxFlag) { this.skipCheckingPriceListSOTrxFlag = skipCheckingPriceListSOTrxFlag; return this; } @Nullable public BigDecimal getManualPrice() { return manualPrice; } @Override public IEditablePricingContext setManualPrice(@Nullable final BigDecimal manualPrice) { this.manualPrice = manualPrice; return this; } @Override public boolean isSkipCheckingPriceListSOTrxFlag() { return skipCheckingPriceListSOTrxFlag; } /** If set to not-{@code null}, then the {@link de.metas.pricing.rules.Discount} rule with go with this break as opposed to look for the currently matching break. */ @Override public IEditablePricingContext setForcePricingConditionsBreak(@Nullable final PricingConditionsBreak forcePricingConditionsBreak) {
this.forcePricingConditionsBreak = forcePricingConditionsBreak; return this; } @Override public Optional<IAttributeSetInstanceAware> getAttributeSetInstanceAware() { final Object referencedObj = getReferencedObject(); if (referencedObj == null) { return Optional.empty(); } final IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class); final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(referencedObj); return Optional.ofNullable(asiAware); } @Override public Quantity getQuantity() { final BigDecimal ctxQty = getQty(); if (ctxQty == null) { return null; } final UomId ctxUomId = getUomId(); if (ctxUomId == null) { return null; } return Quantitys.of(ctxQty, ctxUomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingContext.java
2
请完成以下Java代码
public Object getPrincipal() { return this.clientPrincipal; } @Override public Object getCredentials() { return ""; } /** * Returns the authorization {@code URI}. * @return the authorization {@code URI} */ public String getAuthorizationUri() { return this.authorizationUri; } /** * Returns the requested scope(s). * @return the requested scope(s) */ public Set<String> getScopes() { return this.scopes; } /** * Returns the device code. * @return the device code */ public OAuth2DeviceCode getDeviceCode() {
return this.deviceCode; } /** * Returns the user code. * @return the user code */ public OAuth2UserCode getUserCode() { return this.userCode; } /** * Returns the additional parameters. * @return the additional parameters */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); registry.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // registry.addEndpoint("/send_to_all") // .setAllowedOrigins("*") // .withSockJS(); registry.addEndpoint("/") .setAllowedOrigins("*") .withSockJS(); // RequestUpgradeStrategy upgradeStrategy = new TomcatRequestUpgradeStrategy(); // registry.addEndpoint("/") // .setHandshakeHandler(new DefaultHandshakeHandler(upgradeStrategy)) // .setAllowedOrigins("*"); } // @Override // public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
// registry.addHandler(this.webSocketHandler(), "/") // 配置处理器 // .addInterceptors(new DemoWebSocketShakeInterceptor()) // 配置拦截器 // .setAllowedOrigins("*"); // 解决跨域问题 // } // @Bean // public DemoWebSocketHandler webSocketHandler() { // return new DemoWebSocketHandler(); // } // @Bean // public DemoWebSocketShakeInterceptor webSocketShakeInterceptor() { // return new DemoWebSocketShakeInterceptor(); // } }
repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-03\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\config\WebSocketConfiguration.java
2
请完成以下Java代码
public static int usingRecursion(int[] prices, int n) { if (n <= 0) { return 0; } int maxRevenue = Integer.MIN_VALUE; for (int i = 1; i <= n; i++) { maxRevenue = Math.max(maxRevenue, prices[i - 1] + usingRecursion(prices, n - i)); } return maxRevenue; } public static int usingMemoizedRecursion(int[] prices, int n) { int[] memo = new int[n + 1]; Arrays.fill(memo, -1); return memoizedHelper(prices, n, memo); } private static int memoizedHelper(int[] prices, int n, int[] memo) { if (n <= 0) { return 0; } if (memo[n] != -1) { return memo[n]; } int maxRevenue = Integer.MIN_VALUE; for (int i = 1; i <= n; i++) { maxRevenue = Math.max(maxRevenue, prices[i - 1] + memoizedHelper(prices, n - i, memo)); } memo[n] = maxRevenue; return maxRevenue; } public static int usingDynamicProgramming(int[] prices, int n) { int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) { int maxRevenue = Integer.MIN_VALUE; for (int j = 1; j <= i; j++) { maxRevenue = Math.max(maxRevenue, prices[j - 1] + dp[i - j]); } dp[i] = maxRevenue; } return dp[n]; } public static int usingUnboundedKnapsack(int[] prices, int n) { int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) { for (int j = 0; j < prices.length; j++) { if (j + 1 <= i) { dp[i] = Math.max(dp[i], dp[i - (j + 1)] + prices[j]); } } } return dp[n]; } }
repos\tutorials-master\core-java-modules\core-java-lang-math-4\src\main\java\com\baeldung\math\rodcutting\RodCuttingProblem.java
1
请在Spring Boot框架中完成以下Java代码
public final class DataJdbcRepositoriesAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(JdbcRepositoryConfigExtension.class) @Import(DataJdbcRepositoriesRegistrar.class) static class JdbcRepositoriesConfiguration { } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(AbstractJdbcConfiguration.class) static class SpringBootJdbcConfiguration extends AbstractJdbcConfiguration { private final ApplicationContext applicationContext; private final DataJdbcProperties properties; SpringBootJdbcConfiguration(ApplicationContext applicationContext, DataJdbcProperties properties) { this.applicationContext = applicationContext; this.properties = properties; } @Override protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException { return new EntityScanner(this.applicationContext).scan(Table.class); } @Override @Bean @ConditionalOnMissingBean public RelationalManagedTypes jdbcManagedTypes() throws ClassNotFoundException { return super.jdbcManagedTypes(); } @Override @Bean @ConditionalOnMissingBean public JdbcMappingContext jdbcMappingContext(Optional<NamingStrategy> namingStrategy, JdbcCustomConversions customConversions, RelationalManagedTypes jdbcManagedTypes) { return super.jdbcMappingContext(namingStrategy, customConversions, jdbcManagedTypes); } @Override @Bean @ConditionalOnMissingBean public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations, @Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, JdbcDialect dialect) { return super.jdbcConverter(mappingContext, operations, relationResolver, conversions, dialect); }
@Override @Bean @ConditionalOnMissingBean public JdbcCustomConversions jdbcCustomConversions() { return super.jdbcCustomConversions(); } @Override @Bean @ConditionalOnMissingBean public JdbcAggregateTemplate jdbcAggregateTemplate(ApplicationContext applicationContext, JdbcMappingContext mappingContext, JdbcConverter converter, DataAccessStrategy dataAccessStrategy) { return super.jdbcAggregateTemplate(applicationContext, mappingContext, converter, dataAccessStrategy); } @Override @Bean @ConditionalOnMissingBean public DataAccessStrategy dataAccessStrategyBean(NamedParameterJdbcOperations operations, JdbcConverter jdbcConverter, JdbcMappingContext context, JdbcDialect dialect) { return super.dataAccessStrategyBean(operations, jdbcConverter, context, dialect); } @Override @Bean @ConditionalOnMissingBean public JdbcDialect jdbcDialect(NamedParameterJdbcOperations operations) { DataJdbcDatabaseDialect dialect = this.properties.getDialect(); return (dialect != null) ? dialect.getJdbcDialect(operations.getJdbcOperations()) : super.jdbcDialect(operations); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-jdbc\src\main\java\org\springframework\boot\data\jdbc\autoconfigure\DataJdbcRepositoriesAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(_id, orderedArticleLineId, articleId, pcn, productGroupName, quantity, unit, annotation, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PrescriptedArticleLine {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" orderedArticleLineId: ").append(toIndentedString(orderedArticleLineId)).append("\n"); sb.append(" articleId: ").append(toIndentedString(articleId)).append("\n"); sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n"); sb.append(" productGroupName: ").append(toIndentedString(productGroupName)).append("\n"); sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); sb.append(" unit: ").append(toIndentedString(unit)).append("\n"); sb.append(" annotation: ").append(toIndentedString(annotation)).append("\n"); sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\PrescriptedArticleLine.java
2
请完成以下Java代码
final class PemCertificateParser { private static final String HEADER = "-+BEGIN\\s+.*CERTIFICATE[^-]*-+(?:\\s|\\r|\\n)+"; private static final String BASE64_TEXT = "([a-z0-9+/=\\r\\n]+)"; private static final String FOOTER = "-+END\\s+.*CERTIFICATE[^-]*-+"; private static final Pattern PATTERN = Pattern.compile(HEADER + BASE64_TEXT + FOOTER, Pattern.CASE_INSENSITIVE); private PemCertificateParser() { } /** * Parse certificates from the specified string. * @param text the text to parse * @return the parsed certificates */ @Contract("!null -> !null") static @Nullable List<X509Certificate> parse(@Nullable String text) { if (text == null) { return null; } CertificateFactory factory = getCertificateFactory(); List<X509Certificate> certs = new ArrayList<>(); readCertificates(text, factory, certs::add); Assert.state(!CollectionUtils.isEmpty(certs), "Missing certificates or unrecognized format"); return List.copyOf(certs); } private static CertificateFactory getCertificateFactory() { try {
return CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { throw new IllegalStateException("Unable to get X.509 certificate factory", ex); } } private static void readCertificates(String text, CertificateFactory factory, Consumer<X509Certificate> consumer) { try { Matcher matcher = PATTERN.matcher(text); while (matcher.find()) { String encodedText = matcher.group(1); byte[] decodedBytes = decodeBase64(encodedText); ByteArrayInputStream inputStream = new ByteArrayInputStream(decodedBytes); while (inputStream.available() > 0) { consumer.accept((X509Certificate) factory.generateCertificate(inputStream)); } } } catch (CertificateException ex) { throw new IllegalStateException("Error reading certificate: " + ex.getMessage(), ex); } } private static byte[] decodeBase64(String content) { byte[] bytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); return Base64.getDecoder().decode(bytes); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemCertificateParser.java
1
请在Spring Boot框架中完成以下Java代码
private void updateContextAfterSuccess(@NonNull final Exchange exchange) { final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); final PurchaseOrderRow purchaseOrderRow = exchange.getProperty(PROPERTY_CURRENT_CSV_ROW, PurchaseOrderRow.class); final JsonExternalId externalHeaderId = JsonExternalId.of(purchaseOrderRow.getExternalHeaderId()); if (!importOrdersRouteContext.getPurchaseCandidatesWithError().contains(externalHeaderId)) { importOrdersRouteContext.getPurchaseCandidatesToProcess().add(externalHeaderId); } } private void updateContextAfterError(@NonNull final Exchange exchange) { final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); final PurchaseOrderRow csvRow = exchange.getProperty(PROPERTY_CURRENT_CSV_ROW, PurchaseOrderRow.class); final Exception ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); final RuntimeCamelException augmentedEx = new RuntimeCamelException("Exception processing file " + exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY) + " and row '" + csvRow + "'", ex); exchange.setProperty(Exchange.EXCEPTION_CAUGHT, augmentedEx); if (csvRow == null || Check.isBlank(csvRow.getExternalHeaderId())) { importOrdersRouteContext.errorInUnknownRow(); return; } final JsonExternalId externalHeaderId = JsonExternalId.of(csvRow.getExternalHeaderId()); importOrdersRouteContext.getPurchaseCandidatesToProcess().remove(externalHeaderId); importOrdersRouteContext.getPurchaseCandidatesWithError().add(externalHeaderId); } private void enqueueCandidatesProcessor(@NonNull final Exchange exchange) { final ImportOrdersRouteContext importOrdersRouteContext = ImportUtil.getOrCreateImportOrdersRouteContext(exchange); if (importOrdersRouteContext.isDoNotProcessAtAll()) {
final Object fileName = exchange.getIn().getHeader(Exchange.FILE_NAME_ONLY); throw new RuntimeCamelException("No purchase order candidates from file " + fileName.toString() + " can be imported to metasfresh"); } final JsonPurchaseCandidatesRequest.JsonPurchaseCandidatesRequestBuilder builder = JsonPurchaseCandidatesRequest.builder(); for (final JsonExternalId externalId : importOrdersRouteContext.getPurchaseCandidatesToProcess()) { final JsonPurchaseCandidateReference reference = JsonPurchaseCandidateReference.builder() .externalSystemCode(importOrdersRouteContext.getExternalSystemCode()) .externalHeaderId(externalId) .build(); builder.purchaseCandidate(reference); } exchange.getIn().setBody(builder.build()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\GetPurchaseOrderFromFileRouteBuilder.java
2
请完成以下Java代码
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByProcessDefinitionId(String processDefinitionId) { return getDbSqlSession().selectList("selectHistoricIdentityLinksByProcessDefinition", processDefinitionId); } @SuppressWarnings("unchecked") public List<HistoricIdentityLinkEntity> findHistoricIdentityLinks() { return getDbSqlSession().selectList("selectHistoricIdentityLinks"); } @SuppressWarnings("unchecked") public List<HistoricIdentityLinkEntity> findHistoricIdentityLinkByTaskUserGroupAndType(String taskId, String userId, String groupId, String type) { Map<String, String> parameters = new HashMap<>(); parameters.put("taskId", taskId); parameters.put("userId", userId); parameters.put("groupId", groupId); parameters.put("type", type); return getDbSqlSession().selectList("selectHistoricIdentityLinkByTaskUserGroupAndType", parameters); } @SuppressWarnings("unchecked") public List<HistoricIdentityLinkEntity> findHistoricIdentityLinkByProcessDefinitionUserAndGroup(String processDefinitionId, String userId, String groupId) { Map<String, String> parameters = new HashMap<>(); parameters.put("processDefinitionId", processDefinitionId); parameters.put("userId", userId); parameters.put("groupId", groupId); return getDbSqlSession().selectList("selectHistoricIdentityLinkByProcessDefinitionUserAndGroup", parameters); } public void deleteHistoricIdentityLinksByTaskId(String taskId) { List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId); for (HistoricIdentityLinkEntity identityLink : identityLinks) { deleteHistoricIdentityLink(identityLink); } } public void deleteHistoricIdentityLinksByProcInstance(String processInstanceId) { // Identity links from db List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
// Delete for (HistoricIdentityLinkEntity identityLink : identityLinks) { deleteHistoricIdentityLink(identityLink); } // Identity links from cache List<HistoricIdentityLinkEntity> identityLinksFromCache = Context.getCommandContext().getDbSqlSession().findInCache(HistoricIdentityLinkEntity.class); for (HistoricIdentityLinkEntity identityLinkEntity : identityLinksFromCache) { if (processInstanceId.equals(identityLinkEntity.getProcessInstanceId())) { deleteHistoricIdentityLink(identityLinkEntity); } } } public void deleteHistoricIdentityLinksByProcDef(String processDefId) { getDbSqlSession().delete("deleteHistoricIdentityLinkByProcDef", processDefId); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityManager.java
1
请在Spring Boot框架中完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentDispute {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" availableChoices: ").append(toIndentedString(availableChoices)).append("\n"); sb.append(" buyerProvided: ").append(toIndentedString(buyerProvided)).append("\n"); sb.append(" buyerUsername: ").append(toIndentedString(buyerUsername)).append("\n"); sb.append(" closedDate: ").append(toIndentedString(closedDate)).append("\n"); sb.append(" evidence: ").append(toIndentedString(evidence)).append("\n"); sb.append(" evidenceRequests: ").append(toIndentedString(evidenceRequests)).append("\n"); sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n"); sb.append(" monetaryTransactions: ").append(toIndentedString(monetaryTransactions)).append("\n"); sb.append(" openDate: ").append(toIndentedString(openDate)).append("\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" paymentDisputeId: ").append(toIndentedString(paymentDisputeId)).append("\n"); sb.append(" paymentDisputeStatus: ").append(toIndentedString(paymentDisputeStatus)).append("\n"); sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); sb.append(" resolution: ").append(toIndentedString(resolution)).append("\n"); sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n"); sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n");
sb.append(" revision: ").append(toIndentedString(revision)).append("\n"); sb.append(" sellerResponse: ").append(toIndentedString(sellerResponse)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PaymentDispute.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; BaseDataWithAdditionalInfo<?> that = (BaseDataWithAdditionalInfo<?>) o; return Arrays.equals(additionalInfoBytes, that.additionalInfoBytes); } @Override public int hashCode() { return Objects.hash(super.hashCode(), additionalInfoBytes); } public static JsonNode getJson(Supplier<JsonNode> jsonData, Supplier<byte[]> binaryData) { JsonNode json = jsonData.get(); if (json != null) { return json; } else { byte[] data = binaryData.get(); if (data != null) { try { return mapper.readTree(new ByteArrayInputStream(data));
} catch (IOException e) { log.warn("Can't deserialize json data: ", e); return null; } } else { return null; } } } public static void setJson(JsonNode json, Consumer<JsonNode> jsonConsumer, Consumer<byte[]> bytesConsumer) { jsonConsumer.accept(json); try { bytesConsumer.accept(mapper.writeValueAsBytes(json)); } catch (JsonProcessingException e) { log.warn("Can't serialize json data: ", e); } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\BaseDataWithAdditionalInfo.java
1
请完成以下Java代码
public void mouseDragged(MouseEvent me) { if (selObject == null || !selObject.isUpdateable()) { moved = false; return; } moved = true; if (getCursor() != customCursor) { setCursor(customCursor); } } // mouseDragged /* (non-Javadoc) * @see javax.swing.event.MouseInputAdapter#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent me) { if (startModel != null && moved) { Point p = me.getPoint(); JList<ListItem> endList = yesList; DefaultListModel<ListItem> endModel = yesModel; if (me.getComponent() == yesList) { if (!yesList.contains (p)) { endList = noList; endModel = noModel; } } else { if (noList.contains (p)) {
setCursor(Cursor.getDefaultCursor()); moved = false; return; // move within noList } p = SwingUtilities.convertPoint (noList, p, yesList); } int index = endList.locationToIndex(p); if (index > -1) // && endList.getCellBounds(index, index).contains(p)) { startModel.removeElement(selObject); endModel.add(index, selObject); // startList.clearSelection(); endList.clearSelection(); endList.setSelectedValue(selObject, true); // setIsChanged(true); } } startList = null; startModel = null; selObject = null; moved = false; setCursor(Cursor.getDefaultCursor()); } // mouseReleased } } // VSortTab
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VSortTab.java
1
请完成以下Java代码
public java.math.BigDecimal getStd_MaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_MaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Standard price min Margin. @param Std_MinAmt Minimum margin allowed for a product */ @Override public void setStd_MinAmt (java.math.BigDecimal Std_MinAmt) { set_Value (COLUMNNAME_Std_MinAmt, Std_MinAmt); } /** Get Standard price min Margin. @return Minimum margin allowed for a product */ @Override public java.math.BigDecimal getStd_MinAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_MinAmt); if (bd == null) return Env.ZERO; return bd; } /** * Std_Rounding AD_Reference_ID=155 * Reference name: M_DiscountPriceList RoundingRule */ public static final int STD_ROUNDING_AD_Reference_ID=155; /** Ganze Zahl .00 = 0 */ public static final String STD_ROUNDING_GanzeZahl00 = "0"; /** No Rounding = N */ public static final String STD_ROUNDING_NoRounding = "N"; /** Quarter .25 .50 .75 = Q */ public static final String STD_ROUNDING_Quarter255075 = "Q"; /** Dime .10, .20, .30, ... = D */ public static final String STD_ROUNDING_Dime102030 = "D"; /** Nickel .05, .10, .15, ... = 5 */ public static final String STD_ROUNDING_Nickel051015 = "5";
/** Ten 10.00, 20.00, .. = T */ public static final String STD_ROUNDING_Ten10002000 = "T"; /** Currency Precision = C */ public static final String STD_ROUNDING_CurrencyPrecision = "C"; /** Ending in 9/5 = 9 */ public static final String STD_ROUNDING_EndingIn95 = "9"; /** Set Rundung Standardpreis. @param Std_Rounding Rounding rule for calculated price */ @Override public void setStd_Rounding (java.lang.String Std_Rounding) { set_Value (COLUMNNAME_Std_Rounding, Std_Rounding); } /** Get Rundung Standardpreis. @return Rounding rule for calculated price */ @Override public java.lang.String getStd_Rounding () { return (java.lang.String)get_Value(COLUMNNAME_Std_Rounding); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaLine.java
1
请完成以下Java代码
public void setAuditEventType(String auditEventType) { this.auditEventType = auditEventType; } public Map<String, String> getData() { return data; } public void setData(Map<String, String> data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o; return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } @Override public String toString() { return "PersistentAuditEvent{" + "principal='" + principal + '\'' + ", auditEventDate=" + auditEventDate + ", auditEventType='" + auditEventType + '\'' + '}'; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\PersistentAuditEvent.java
1
请完成以下Java代码
public String bar(String device) { log.info("bar({})", device); counterProvider.withTag("device.type", device) .increment(); String response = timerProvider.withTag("device.type", device) .record(this::invokeSomeLogic); return response; } @Timed("buzz.time") @Counted("buzz.count") public String buzz(@MeterTag("device.type") String device) { log.info("buzz({})", device);
return invokeSomeLogic(); } private String invokeSomeLogic() { long sleepMs = ThreadLocalRandom.current() .nextInt(0, 100); try { Thread.sleep(sleepMs); } catch (InterruptedException e) { throw new RuntimeException(e); } return "dummy response"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-3-observation\src\main\java\com\baeldung\micrometer\tags\dummy\DummyService.java
1
请完成以下Java代码
public class UserUpdateRequest { private final Email emailToUpdate; private final UserName userNameToUpdate; private final String passwordToUpdate; private final Image imageToUpdate; private final String bioToUpdate; public static UserUpdateRequestBuilder builder() { return new UserUpdateRequestBuilder(); } Optional<Email> getEmailToUpdate() { return ofNullable(emailToUpdate); } Optional<UserName> getUserNameToUpdate() { return ofNullable(userNameToUpdate); } Optional<String> getPasswordToUpdate() { return ofNullable(passwordToUpdate); } Optional<Image> getImageToUpdate() { return ofNullable(imageToUpdate); } Optional<String> getBioToUpdate() { return ofNullable(bioToUpdate); } private UserUpdateRequest(UserUpdateRequestBuilder builder) { this.emailToUpdate = builder.emailToUpdate; this.userNameToUpdate = builder.userNameToUpdate; this.passwordToUpdate = builder.passwordToUpdate; this.imageToUpdate = builder.imageToUpdate; this.bioToUpdate = builder.bioToUpdate; } public static class UserUpdateRequestBuilder { private Email emailToUpdate; private UserName userNameToUpdate; private String passwordToUpdate; private Image imageToUpdate; private String bioToUpdate; public UserUpdateRequestBuilder emailToUpdate(Email emailToUpdate) { this.emailToUpdate = emailToUpdate; return this; }
public UserUpdateRequestBuilder userNameToUpdate(UserName userNameToUpdate) { this.userNameToUpdate = userNameToUpdate; return this; } public UserUpdateRequestBuilder passwordToUpdate(String passwordToUpdate) { this.passwordToUpdate = passwordToUpdate; return this; } public UserUpdateRequestBuilder imageToUpdate(Image imageToUpdate) { this.imageToUpdate = imageToUpdate; return this; } public UserUpdateRequestBuilder bioToUpdate(String bioToUpdate) { this.bioToUpdate = bioToUpdate; return this; } public UserUpdateRequest build() { return new UserUpdateRequest(this); } } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserUpdateRequest.java
1
请完成以下Java代码
public String getParentId() { return parentId; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } public Date getStartedBefore() { return startedBefore;
} public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public void setInvolvedGroups(List<String> involvedGroups) { this.involvedGroups = involvedGroups; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
protected Authentication getCurrentAuthentication() { return getProcessEngine().getIdentityService().getCurrentAuthentication(); } /** * Configure the authorization check for the given {@link QueryParameters}. */ protected void configureAuthorizationCheck(QueryParameters query) { Authentication currentAuthentication = getCurrentAuthentication(); AuthorizationCheck authCheck = query.getAuthCheck(); authCheck.getPermissionChecks().clear(); if (isAuthorizationEnabled() && currentAuthentication != null) { authCheck.setAuthorizationCheckEnabled(true); String currentUserId = currentAuthentication.getUserId(); List<String> currentGroupIds = currentAuthentication.getGroupIds(); authCheck.setAuthUserId(currentUserId); authCheck.setAuthGroupIds(currentGroupIds); } } /** * Configure the tenant check for the given {@link QueryParameters}. */ protected void configureTenantCheck(QueryParameters query) { TenantCheck tenantCheck = query.getTenantCheck(); if (isTenantCheckEnabled()) { Authentication currentAuthentication = getCurrentAuthentication(); tenantCheck.setTenantCheckEnabled(true); tenantCheck.setAuthTenantIds(currentAuthentication.getTenantIds()); } else {
tenantCheck.setTenantCheckEnabled(false); tenantCheck.setAuthTenantIds(null); } } /** * Add a new {@link PermissionCheck} with the given values. */ protected void addPermissionCheck(QueryParameters query, Resource resource, String queryParam, Permission permission) { if(!isPermissionDisabled(permission)){ PermissionCheck permCheck = new PermissionCheck(); permCheck.setResource(resource); permCheck.setResourceIdQueryParam(queryParam); permCheck.setPermission(permission); query.getAuthCheck().addAtomicPermissionCheck(permCheck); } } protected boolean isPermissionDisabled(Permission permission) { List<String> disabledPermissions = getProcessEngine().getProcessEngineConfiguration().getDisabledPermissions(); for (String disabledPerm : disabledPermissions) { if (!disabledPerm.equals(permission.getName())) { return true; } } return false; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\plugin\resource\AbstractCockpitPluginResource.java
1
请完成以下Java代码
public ImmutableModelCacheInvalidateRequestFactoriesList build() { return ImmutableModelCacheInvalidateRequestFactoriesList.builder() .factoriesByTableName(factoriesByTableName) .tableNamesToEnableRemoveCacheInvalidation( TableNamesGroup.builder() .groupId(WindowBasedModelCacheInvalidateRequestFactoryGroup.class.getSimpleName()) .tableNames(tableNamesToEnableRemoveCacheInvalidation) .build()) .build(); } public ImmutableFactoryGroupBuilder addAll(@NonNull final Set<ParentChildInfo> parentChildInfos) { parentChildInfos.forEach(this::add); return this; } public ImmutableFactoryGroupBuilder add(@NonNull final ParentChildInfo info) { addForParentTable(info); addForChildTable(info); return this; } private void addForParentTable(final ParentChildInfo info) { final String parentTableName = info.getParentTableName(); factoriesByTableName.put(parentTableName, DirectModelCacheInvalidateRequestFactory.instance); // NOTE: always invalidate parent table name, even if info.isParentNeedsRemoteCacheInvalidation() is false tableNamesToEnableRemoveCacheInvalidation.add(parentTableName); } private void addForChildTable(final ParentChildInfo info) { final String childTableName = info.getChildTableName(); if (childTableName == null || isBlank(childTableName)) { return; }
try { final ParentChildModelCacheInvalidateRequestFactory factory = info.toGenericModelCacheInvalidateRequestFactoryOrNull(); if (factory != null) { factoriesByTableName.put(childTableName, factory); } } catch (final Exception ex) { logger.warn("Failed to create model cache invalidate for {}: {}", childTableName, info, ex); } if (info.isChildNeedsRemoteCacheInvalidation()) { tableNamesToEnableRemoveCacheInvalidation.add(childTableName); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\WindowBasedModelCacheInvalidateRequestFactoryGroup.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Duration getInterval() { return this.interval; } public void setInterval(Duration interval) { this.interval = interval; } public Duration getDelayAfterFailure() { return this.delayAfterFailure; } public void setDelayAfterFailure(Duration delayAfterFailure) { this.delayAfterFailure = delayAfterFailure; } } public static class Ssl {
/** * SSL bundle name. */ private @Nullable String bundle; public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java
2