instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
class RequestUtils { static StringBuilder formatParams(HttpRequest request) { StringBuilder responseData = new StringBuilder(); QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { responseData.append("Parameter: ") .append(key.toUpperCase()) .append(" = ") .append(val.toUpperCase()) .append("\r\n"); } } responseData.append("\r\n"); } return responseData; } static StringBuilder formatBody(HttpContent httpContent) { StringBuilder responseData = new StringBuilder(); ByteBuf content = httpContent.content(); if (content.isReadable()) { responseData.append(content.toString(CharsetUtil.UTF_8) .toUpperCase()); responseData.append("\r\n"); } return responseData; } static StringBuilder evaluateDecoderResult(HttpObject o) { StringBuilder responseData = new StringBuilder(); DecoderResult result = o.decoderResult(); if (!result.isSuccess()) { responseData.append("..Decoder Failure: "); responseData.append(result.cause()); responseData.append("\r\n"); } return responseData; } static StringBuilder prepareLastResponse(HttpRequest request, LastHttpContent trailer) {
StringBuilder responseData = new StringBuilder(); responseData.append("Good Bye!\r\n"); if (!trailer.trailingHeaders() .isEmpty()) { responseData.append("\r\n"); for (CharSequence name : trailer.trailingHeaders() .names()) { for (CharSequence value : trailer.trailingHeaders() .getAll(name)) { responseData.append("P.S. Trailing Header: "); responseData.append(name) .append(" = ") .append(value) .append("\r\n"); } } responseData.append("\r\n"); } return responseData; } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\http\server\RequestUtils.java
1
请完成以下Java代码
public colgroup setVAlign(String valign) { addAttribute("valign",valign); return(this); } /** Sets the char="" attribute. @param character the character to use for alignment. */ public colgroup setChar(String character) { addAttribute("char",character); return(this); } /** Sets the charoff="" attribute. @param char_off When present this attribute specifies the offset of the first occurrence of the alignment character on each line. */ public colgroup setCharOff(int char_off) { addAttribute("charoff",Integer.toString(char_off)); return(this); } /** Sets the charoff="" attribute. @param char_off When present this attribute specifies the offset of the first occurrence of the alignment character on each line. */ public colgroup setCharOff(String char_off) { addAttribute("charoff",char_off); return(this); } /** Sets the lang="" and xml:lang="" attributes @param lang the lang="" and xml:lang="" attributes */ public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public colgroup addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this);
} /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public colgroup addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public colgroup addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public colgroup addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public colgroup removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\colgroup.java
1
请完成以下Java代码
public class WeightRoutePredicateFactory extends AbstractRoutePredicateFactory<WeightConfig> implements ApplicationEventPublisherAware { /** * Weight config group key. */ public static final String GROUP_KEY = WeightConfig.CONFIG_PREFIX + ".group"; /** * Weight config weight key. */ public static final String WEIGHT_KEY = WeightConfig.CONFIG_PREFIX + ".weight"; private static final Log log = LogFactory.getLog(WeightRoutePredicateFactory.class); private @Nullable ApplicationEventPublisher publisher; public WeightRoutePredicateFactory() { super(WeightConfig.class); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(GROUP_KEY, WEIGHT_KEY); } @Override public String shortcutFieldPrefix() { return WeightConfig.CONFIG_PREFIX; } @Override public void beforeApply(WeightConfig config) { if (publisher != null) { publisher.publishEvent(new WeightDefinedEvent(this, config)); } } @Override public Predicate<ServerWebExchange> apply(WeightConfig config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR, Collections.emptyMap()); String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR); if (routeId == null) { return false; } // all calculations and comparison against random num happened in // WeightCalculatorWebFilter String group = config.getGroup(); if (weights.containsKey(group)) {
String chosenRoute = weights.get(group); if (log.isTraceEnabled()) { log.trace("in group weight: " + group + ", current route: " + routeId + ", chosen route: " + chosenRoute); } return routeId.equals(chosenRoute); } else if (log.isTraceEnabled()) { log.trace("no weights found for group: " + group + ", current route: " + routeId); } return false; } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("Weight: %s %s", config.getGroup(), config.getWeight()); } }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\WeightRoutePredicateFactory.java
1
请在Spring Boot框架中完成以下Java代码
public SimpleRabbitListenerContainerFactory retryContainerFactory(ConnectionFactory connectionFactory, RetryOperationsInterceptor retryInterceptor) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); Advice[] adviceChain = { retryInterceptor }; factory.setAdviceChain(adviceChain); return factory; } @Bean public SimpleRabbitListenerContainerFactory retryQueuesContainerFactory(ConnectionFactory connectionFactory, RetryQueuesInterceptor retryInterceptor) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); Advice[] adviceChain = { retryInterceptor }; factory.setAdviceChain(adviceChain); return factory; } @RabbitListener(queues = "blocking-queue", containerFactory = "retryContainerFactory") public void consumeBlocking(String payload) throws Exception { logger.info("Processing message from blocking-queue: {}", payload); throw new Exception("exception occured!"); }
@RabbitListener(queues = "non-blocking-queue", containerFactory = "retryQueuesContainerFactory", ackMode = "MANUAL") public void consumeNonBlocking(String payload) throws Exception { logger.info("Processing message from non-blocking-queue: {}", payload); throw new Exception("Error occured!"); } @RabbitListener(queues = "retry-wait-ended-queue", containerFactory = "defaultContainerFactory") public void consumeRetryWaitEndedMessage(String payload, Message message, Channel channel) throws Exception { MessageProperties props = message.getMessageProperties(); rabbitTemplate().convertAndSend(props.getHeader("x-original-exchange"), props.getHeader("x-original-routing-key"), message); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RabbitConfiguration.java
2
请完成以下Java代码
protected void prepare() { if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } private int createSelection() { final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .createSelection(adPInstanceId); }
@NonNull private IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder() { final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_CloseSelection.java
1
请完成以下Java代码
public class AcquireJobsCmd implements Command<AcquiredJobEntities> { private final AsyncExecutor asyncExecutor; public AcquireJobsCmd(AsyncExecutor asyncExecutor) { this.asyncExecutor = asyncExecutor; } public AcquiredJobEntities execute(CommandContext commandContext) { AcquiredJobEntities acquiredJobs = new AcquiredJobEntities(); List<JobEntity> jobs = commandContext .getJobEntityManager() .findJobsToExecute(new Page(0, asyncExecutor.getMaxAsyncJobsDuePerAcquisition())); for (JobEntity job : jobs) {
lockJob(commandContext, job, asyncExecutor.getAsyncJobLockTimeInMillis()); acquiredJobs.addJob(job); } return acquiredJobs; } protected void lockJob(CommandContext commandContext, JobEntity job, int lockTimeInMillis) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime()); gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis); job.setLockOwner(asyncExecutor.getLockOwner()); job.setLockExpirationTime(gregorianCalendar.getTime()); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AcquireJobsCmd.java
1
请在Spring Boot框架中完成以下Java代码
public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the rule property. * */ public int getRule() { return rule; } /** * Sets the value of the rule property. * */ public void setRule(int value) { this.rule = value; } /** * Gets the value of the language property.
* * @return * possible object is * {@link String } * */ public String getLanguage() { return language; } /** * Sets the value of the language property. * * @param value * allowed object is * {@link String } * */ public void setLanguage(String value) { this.language = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProactiveNotification.java
2
请完成以下Java代码
public void run() { task.log("launching cmd '"+cmdString(cmd)+"' in dir '"+dir+"'"); if (msg!=null) { task.log("waiting for launch completion msg '"+msg+"'..."); } else { task.log("not waiting for a launch completion msg."); } ProcessBuilder processBuilder = new ProcessBuilder(cmd) .redirectErrorStream(true) .directory(dir); InputStream consoleStream = null; try { Process process = processBuilder.start(); consoleStream = process.getInputStream(); BufferedReader consoleReader = new BufferedReader(new InputStreamReader(consoleStream)); String consoleLine = ""; while ( (consoleLine!=null) && (msg==null || consoleLine.indexOf(msg)==-1) ) {
consoleLine = consoleReader.readLine(); if (consoleLine!=null) { task.log(" " + consoleLine); } else { task.log("launched process completed"); } } } catch (Exception e) { throw new BuildException("couldn't launch "+cmdString(cmd), e); } finally { IoUtil.closeSilently(consoleStream); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ant\LaunchThread.java
1
请完成以下Java代码
public void setWithFailures(final Boolean withFailures) { this.withFailures = withFailures; } @CamundaQueryParam(value = "withoutFailures", converter = BooleanConverter.class) public void setWithoutFailures(final Boolean withoutFailures) { this.withoutFailures = withoutFailures; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected BatchStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchStatisticsQuery(); } protected void applyFilters(BatchStatisticsQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(suspended)) { query.suspended(); }
if (FALSE.equals(suspended)) { query.active(); } if (userId != null) { query.createdBy(userId); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (startedAfter != null) { query.startedAfter(startedAfter); } if (TRUE.equals(withFailures)) { query.withFailures(); } if (TRUE.equals(withoutFailures)) { query.withoutFailures(); } } protected void applySortBy(BatchStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } else if (sortBy.equals(SORT_BY_START_TIME_VALUE)) { query.orderByStartTime(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchStatisticsQueryDto.java
1
请完成以下Java代码
public String helloSleuth() { logger.info("Hello Sleuth"); return "success"; } @GetMapping("/same-span") public String helloSleuthSameSpan() throws InterruptedException { logger.info("Same Span"); sleuthService.doSomeWorkSameSpan(); return "success"; } @GetMapping("/new-span") public String helloSleuthNewSpan() throws InterruptedException { logger.info("New Span"); sleuthService.doSomeWorkNewSpan(); return "success"; } @GetMapping("/new-thread") public String helloSleuthNewThread() { logger.info("New Thread"); Runnable runnable = () -> { try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); }
logger.info("I'm inside the new thread - with a new span"); }; executor.execute(runnable); logger.info("I'm done - with the original span"); return "success"; } @GetMapping("/async") public String helloSleuthAsync() throws InterruptedException { logger.info("Before Async Method Call"); sleuthService.asyncMethod(); logger.info("After Async Method Call"); return "success"; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-sleuth\src\main\java\com\baeldung\spring\session\SleuthController.java
1
请完成以下Java代码
private static ITranslatableString retrieveColumnTrl(final POInfoColumn columnInfo) { final IModelTranslationMap adColumnTrlMap = trlRepo.retrieveAll( adColumnPOInfo.getTrlInfo(), AdColumnId.toRepoId(columnInfo.getAD_Column_ID())); final ITranslatableString columnTrl = adColumnTrlMap.getColumnTrl(I_AD_Column.COLUMNNAME_Name, columnInfo.getColumnName()); return columnTrl; } @Value @VisibleForTesting static class SqlWithParams { @NonNull String sql; @NonNull ImmutableList<Object> sqlParams; @VisibleForTesting static SqlWithParams createEmpty() { return new SqlWithParams("", ImmutableList.of()); } @VisibleForTesting SqlWithParams add(@NonNull final SqlWithParams sqlWithParams)
{ StringBuilder completeSQL = new StringBuilder(sql); ImmutableList.Builder<Object> completeParams = ImmutableList.builder().addAll(sqlParams); final boolean firstSQL = completeSQL.length() == 0; if (!firstSQL) { completeSQL.append(" UNION\n"); } completeSQL.append(sqlWithParams.getSql()); completeSQL.append("\n"); completeParams.addAll(sqlWithParams.getSqlParams()); return new SqlWithParams(completeSQL.toString(), completeParams.build()); } @VisibleForTesting SqlWithParams withFinalOrderByClause(@NonNull final String orderBy) { final StringBuilder completeSQL = new StringBuilder(sql).append(orderBy); return new SqlWithParams(completeSQL.toString(), sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogEntryLoader.java
1
请完成以下Java代码
public <T> List<T> getDeployedArtifacts(Class<T> clazz) { for (Class<?> deployedArtifactsClass : deployedArtifacts.keySet()) { if (clazz.isAssignableFrom(deployedArtifactsClass)) { return (List<T>) deployedArtifacts.get(deployedArtifactsClass); } } return null; } // getters and setters //////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @Override public void setResources(Map<String, EventResourceEntity> resources) { this.resources = resources; }
@Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "EventDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityImpl.java
1
请完成以下Java代码
protected ServerResponse prepareResponse(ServerRequest request, Mono<WebGraphQlResponse> responseMono) { Mono<ServerResponse> mono = responseMono.map((response) -> { MediaType contentType = selectResponseMediaType(request); HttpStatus responseStatus = selectResponseStatus(response, contentType); ServerResponse.BodyBuilder builder = ServerResponse.status(responseStatus); builder.headers((headers) -> headers.putAll(response.getResponseHeaders())); builder.contentType(contentType); Map<String, Object> resultMap = response.toMap(); ServerResponse.HeadersBuilder.WriteFunction writer = getWriteFunction(resultMap, contentType); return (writer != null) ? builder.build(writer) : builder.body(resultMap); }); return ServerResponse.async(mono.toFuture()); } protected HttpStatus selectResponseStatus(WebGraphQlResponse response, MediaType responseMediaType) { if (!isHttpOkOnValidationErrors() && !response.getExecutionResult().isDataPresent() && MediaTypes.APPLICATION_GRAPHQL_RESPONSE.equals(responseMediaType)) { return HttpStatus.BAD_REQUEST; } return HttpStatus.OK;
} private static MediaType selectResponseMediaType(ServerRequest request) { ServerRequest.Headers headers = request.headers(); List<MediaType> acceptedMediaTypes; try { acceptedMediaTypes = headers.accept(); } catch (InvalidMediaTypeException ex) { throw new NotAcceptableStatusException("Could not parse " + "Accept header [" + headers.firstHeader(HttpHeaders.ACCEPT) + "]: " + ex.getMessage()); } for (MediaType mediaType : acceptedMediaTypes) { if (SUPPORTED_MEDIA_TYPES.contains(mediaType)) { return mediaType; } } return MediaType.APPLICATION_JSON; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webmvc\GraphQlHttpHandler.java
1
请完成以下Java代码
public String getTaskDeleteReasonLike() { return taskDeleteReasonLike; } public String getTaskAssignee() { return taskAssignee; } public String getTaskAssigneeLike() { return taskAssigneeLike; } public String getTaskId() { return taskId; } public String getTaskInvolvedGroup() { return taskInvolvedGroup; } public String getTaskInvolvedUser() { return taskInvolvedUser; } public String getTaskHadCandidateGroup() { return taskHadCandidateGroup; } public String getTaskHadCandidateUser() { return taskHadCandidateUser; } public String[] getTaskDefinitionKeys() { return taskDefinitionKeys; } public List<TaskQueryVariableValue> getVariables() { return variables; } public Boolean getVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean getVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } public String getTaskOwnerLike() { return taskOwnerLike; } public String getTaskOwner() { return taskOwner; } public Integer getTaskPriority() { return taskPriority; } public String getTaskParentTaskId() { return taskParentTaskId; } public String[] getTenantIds() { return tenantIds; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionName() { return caseDefinitionName; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public Date getStartedAfter() { return startedAfter;
} public Date getStartedBefore() { return startedBefore; } public boolean isTenantIdSet() { return isTenantIdSet; } public List<HistoricTaskInstanceQueryImpl> getQueries() { return queries; } public boolean isOrQueryActive() { return isOrQueryActive; } public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; } @Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请完成以下Spring Boot application配置
#当前项目的端口号,自定义端口 server.port=8013 #当前项目的名称,自己随便取名 spring.application.name=springboot3-web-client-8013 #Server 端地址,这里是本地的8080端口,如果是其它地址修改为对应的地址即可 spring.boot.admin.client.url=http://
localhost:8080 #打开客户端 Actuator 的监控 management.endpoints.web.exposure.include=*
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-admin\springboot3-web-demo\src\main\resources\application.properties
2
请完成以下Java代码
public String getDataType () { return (String)get_Value(COLUMNNAME_DataType); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } public I_AD_Window getPO_Window() throws RuntimeException { return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name) .getPO(getPO_Window_ID(), get_TrxName()); } /** Set PO Window. @param PO_Window_ID Purchase Order Window */ public void setPO_Window_ID (int PO_Window_ID) { if (PO_Window_ID < 1) set_Value (COLUMNNAME_PO_Window_ID, null); else set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID)); } /** Get PO Window. @return Purchase Order Window */ public int getPO_Window_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Query. @param Query SQL */ public void setQuery (String Query) { set_Value (COLUMNNAME_Query, Query); } /** Get Query. @return SQL */ public String getQuery () { return (String)get_Value(COLUMNNAME_Query); } /** Set Search Type. @param SearchType Which kind of search is used (Query or Table) */ public void setSearchType (String SearchType) { set_Value (COLUMNNAME_SearchType, SearchType); } /** Get Search Type. @return Which kind of search is used (Query or Table) */ public String getSearchType () { return (String)get_Value(COLUMNNAME_SearchType); } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ public void setTransactionCode (String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ public String getTransactionCode () { return (String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
1
请完成以下Java代码
public CaseInstanceMigrationDocumentBuilder addCaseInstanceVariable(String variableName, Object variableValue) { this.caseInstanceVariables.put(variableName, variableValue); return this; } @Override public CaseInstanceMigrationDocumentBuilder addCaseInstanceVariables(Map<String, Object> caseInstanceVariables) { this.caseInstanceVariables.putAll(caseInstanceVariables); return this; } @Override public CaseInstanceMigrationDocumentBuilder preUpgradeExpression(String preUpgradeExpression) { this.preUpgradeExpression = preUpgradeExpression; return this; } @Override public CaseInstanceMigrationDocumentBuilder postUpgradeExpression(String postUpgradeExpression) { this.postUpgradeExpression = postUpgradeExpression; return this; }
@Override public CaseInstanceMigrationDocument build() { CaseInstanceMigrationDocumentImpl caseInstanceMigrationDocument = new CaseInstanceMigrationDocumentImpl(); caseInstanceMigrationDocument.setMigrateToCaseDefinitionId(this.migrateToCaseDefinitionId); caseInstanceMigrationDocument.setMigrateToCaseDefinition(this.migrateToCaseDefinitionKey, this.migrateToCaseDefinitionVersion, this.migrateToCaseDefinitionTenantId); caseInstanceMigrationDocument.setActivatePlanItemDefinitionMappings(this.activatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setTerminatePlanItemDefinitionMappings(this.terminatePlanItemDefinitionMappings); caseInstanceMigrationDocument.setMoveToAvailablePlanItemDefinitionMappings(this.moveToAvailablePlanItemDefinitionMappings); caseInstanceMigrationDocument.setWaitingForRepetitionPlanItemDefinitionMappings(this.waitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setRemoveWaitingForRepetitionPlanItemDefinitionMappings(this.removeWaitingForRepetitionPlanItemDefinitionMappings); caseInstanceMigrationDocument.setChangePlanItemIdMappings(this.changePlanItemIdMappings); caseInstanceMigrationDocument.setChangePlanItemIdWithDefinitionIdMappings(this.changePlanItemIdWithDefinitionIdMappings); caseInstanceMigrationDocument.setChangePlanItemDefinitionWithNewTargetIdsMappings(this.changePlanItemDefinitionWithNewTargetIdsMappings); caseInstanceMigrationDocument.setCaseInstanceVariables(this.caseInstanceVariables); caseInstanceMigrationDocument.setPreUpgradeExpression(this.preUpgradeExpression); caseInstanceMigrationDocument.setPostUpgradeExpression(this.postUpgradeExpression); return caseInstanceMigrationDocument; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentBuilderImpl.java
1
请完成以下Java代码
public class MigrationCompensationInstanceVisitor extends MigratingProcessElementInstanceVisitor { @Override protected boolean canMigrate(MigratingProcessElementInstance instance) { return instance instanceof MigratingEventScopeInstance || instance instanceof MigratingCompensationEventSubscriptionInstance; } @Override protected void instantiateScopes( MigratingScopeInstance ancestorScopeInstance, MigratingScopeInstanceBranch executionBranch, List<ScopeImpl> scopesToInstantiate) { if (scopesToInstantiate.isEmpty()) { return; } ExecutionEntity ancestorScopeExecution = ancestorScopeInstance.resolveRepresentativeExecution(); ExecutionEntity parentExecution = ancestorScopeExecution; for (ScopeImpl scope : scopesToInstantiate) { ExecutionEntity compensationScopeExecution = parentExecution.createExecution(); compensationScopeExecution.setScope(true); compensationScopeExecution.setEventScope(true); compensationScopeExecution.setActivity((PvmActivity) scope);
compensationScopeExecution.setActive(false); compensationScopeExecution.activityInstanceStarting(); compensationScopeExecution.enterActivityInstance(); EventSubscriptionEntity eventSubscription = EventSubscriptionEntity.createAndInsert(parentExecution, EventType.COMPENSATE, (ActivityImpl) scope); eventSubscription.setConfiguration(compensationScopeExecution.getId()); executionBranch.visited(new MigratingEventScopeInstance(eventSubscription, compensationScopeExecution, scope)); parentExecution = compensationScopeExecution; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigrationCompensationInstanceVisitor.java
1
请完成以下Java代码
public Movie getMovie(Long movieId) { EntityManager em = HibernateOperations.getEntityManager(); Movie movie = em.find(Movie.class, Long.valueOf(movieId)); return movie; } /** * Method to illustrate the usage of merge() function. */ public void mergeMovie() { EntityManager em = HibernateOperations.getEntityManager(); Movie movie = getMovie(1L); em.detach(movie); movie.setLanguage("Italian"); em.getTransaction() .begin(); em.merge(movie); em.getTransaction()
.commit(); } /** * Method to illustrate the usage of remove() function. */ public void removeMovie() { EntityManager em = HibernateOperations.getEntityManager(); em.getTransaction() .begin(); Movie movie = em.find(Movie.class, Long.valueOf(1L)); em.remove(movie); em.getTransaction() .commit(); } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\operations\HibernateOperations.java
1
请在Spring Boot框架中完成以下Java代码
ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory, ClassPathRestartStrategy classPathRestartStrategy) { DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer(); URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread()); if (urls == null) { urls = new URL[0]; } return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, classPathRestartStrategy, urls); } @Bean FileSystemWatcherFactory getFileSystemWatcherFactory() { return this::newFileSystemWatcher; } private FileSystemWatcher newFileSystemWatcher() { Restart restartProperties = this.properties.getRestart(); FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(), restartProperties.getQuietPeriod()); String triggerFile = restartProperties.getTriggerFile();
if (StringUtils.hasLength(triggerFile)) { watcher.setTriggerFilter(new TriggerFileFilter(triggerFile)); } return watcher; } @Bean ClassPathRestartStrategy classPathRestartStrategy() { return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude()); } @Bean ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory, @Value("${remoteUrl}") String remoteUrl) { String url = remoteUrl + this.properties.getRemote().getContextPath() + "/restart"; return new ClassPathChangeUploader(url, requestFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\RemoteClientConfiguration.java
2
请完成以下Java代码
public CurrencyConversionContext withPrecision(@NonNull final CurrencyPrecision precision) { final CurrencyPrecision precisionOld = getPrecision().orElse(null); if (Objects.equals(precisionOld, precision)) { return this; } else { return toBuilder().precision(Optional.of(precision)).build(); } } public CurrencyConversionContext withFixedConversionRate(@NonNull final FixedConversionRate rate) { return toBuilder() .fixedConversionRates(fixedConversionRates.addingConversionRate(rate)) .build();
} public boolean hasFixedConversionRate( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { return fixedConversionRates.hasMultiplyRate(fromCurrencyId, toCurrencyId); } public BigDecimal getFixedConversionRate( @NonNull final CurrencyId fromCurrencyId, @NonNull final CurrencyId toCurrencyId) { return fixedConversionRates.getMultiplyRate(fromCurrencyId, toCurrencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyConversionContext.java
1
请完成以下Java代码
public class TbRocksDb { protected final String path; private final Options dbOptions; private final WriteOptions writeOptions; protected RocksDB db; static { RocksDB.loadLibrary(); } public TbRocksDb(String path, Options dbOptions, WriteOptions writeOptions) { this.path = path; this.dbOptions = dbOptions; this.writeOptions = writeOptions; } @SneakyThrows public void init() { Files.createDirectories(Path.of(path).getParent()); db = RocksDB.open(dbOptions, path); } @SneakyThrows public void put(String key, byte[] value) { db.put(writeOptions, key.getBytes(StandardCharsets.UTF_8), value); } public void forEach(BiConsumer<String, byte[]> processor) { try (RocksIterator iterator = db.newIterator()) { for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) { String key = new String(iterator.key(), StandardCharsets.UTF_8); processor.accept(key, iterator.value());
} } } @SneakyThrows public void delete(String key) { db.delete(writeOptions, key.getBytes(StandardCharsets.UTF_8)); } public void close() { if (db != null) { db.close(); } } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\util\TbRocksDb.java
1
请完成以下Java代码
public void setFrequency (final int Frequency) { set_Value (COLUMNNAME_Frequency, Frequency); } @Override public int getFrequency() { return get_ValueAsInt(COLUMNNAME_Frequency); } @Override public void setLocalRootLocation (final String LocalRootLocation) { set_Value (COLUMNNAME_LocalRootLocation, LocalRootLocation); } @Override public String getLocalRootLocation() { return get_ValueAsString(COLUMNNAME_LocalRootLocation); } @Override public void setProcessedDirectory (final String ProcessedDirectory) { set_Value (COLUMNNAME_ProcessedDirectory, ProcessedDirectory); } @Override public String getProcessedDirectory() { return get_ValueAsString(COLUMNNAME_ProcessedDirectory); } @Override public void setProductFileNamePattern (final @Nullable String ProductFileNamePattern) { set_Value (COLUMNNAME_ProductFileNamePattern, ProductFileNamePattern); } @Override public String getProductFileNamePattern() { return get_ValueAsString(COLUMNNAME_ProductFileNamePattern); }
@Override public void setPurchaseOrderFileNamePattern (final @Nullable String PurchaseOrderFileNamePattern) { set_Value (COLUMNNAME_PurchaseOrderFileNamePattern, PurchaseOrderFileNamePattern); } @Override public String getPurchaseOrderFileNamePattern() { return get_ValueAsString(COLUMNNAME_PurchaseOrderFileNamePattern); } @Override public void setWarehouseFileNamePattern (final @Nullable String WarehouseFileNamePattern) { set_Value (COLUMNNAME_WarehouseFileNamePattern, WarehouseFileNamePattern); } @Override public String getWarehouseFileNamePattern() { return get_ValueAsString(COLUMNNAME_WarehouseFileNamePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement_LocalFile.java
1
请完成以下Java代码
public abstract class AbstractPrintJobCreate extends JavaProcess { private static final Logger logger = LogManager.getLogger(AbstractPrintJobCreate.class); private final static String MSG_INVOICE_GENERATE_NO_PRINTING_QUEUE_0P = "CreatePrintJobs_No_Printing_Queue_Selected"; private final PrintOutputFacade printOutputFacade = SpringContextHolder.instance.getBean(PrintOutputFacade.class); /** * Create {@link I_C_Printing_Queue} selection by using {@link #getPinstanceId()} as current instance * * @return number of records selected */ protected abstract int createSelection(); @Override protected String doIt() { // NOTE: we need to clone the context which is passed to the other thread because else context (in ZK is enhanced) will be lost when this thread will end // and as a result we will create entries with AD_Client_ID/AD_Org_ID=0 final Properties ctxToUse = (Properties)getCtx().clone(); final List<IPrintingQueueSource> sources = createPrintingQueueSources(ctxToUse); for (final IPrintingQueueSource source : sources) { try { final ContextForAsyncProcessing printJobContext = ContextForAsyncProcessing.builder() .adPInstanceId(getPinstanceId()) .build(); printOutputFacade.print(source,printJobContext); } catch (final RuntimeException ex) { Loggables.withLogger(logger, Level.WARN).addLog("Failed creating print job for IPrintingQueueSource={}; exception={}", source, ex); throw ex; } } return MSG_OK; }
// each one with their own users to print user to print protected List<IPrintingQueueSource> createPrintingQueueSources(final Properties ctxToUse) { // NOTE: we create the selection out of transaction because methods which are polling the printing queue are working out of transaction final int selectionLength = createSelection(); if (selectionLength <= 0) { throw new AdempiereException("@" + MSG_INVOICE_GENERATE_NO_PRINTING_QUEUE_0P + "@"); } final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class); final IPrintingQueueQuery query = printingQueueBL.createPrintingQueueQuery(); query.setFilterByProcessedQueueItems(false); query.setOnlyAD_PInstance_ID(getPinstanceId()); return printingQueueBL.createPrintingQueueSources(ctxToUse, query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\AbstractPrintJobCreate.java
1
请在Spring Boot框架中完成以下Java代码
public class DBLoader implements ApplicationRunner { private final BookRepository bookRepository; @Autowired DBLoader(BookRepository bookRepository){ this.bookRepository = bookRepository; } public void run(ApplicationArguments applicationArguments) throws Exception { String[] templates = { "Up and running with %s", "%s Basics", "%s for Beginners", "%s for Neckbeards", "Under the hood: %s", "Discovering %s", "A short guide to %s", "%s with Baeldung" }; String[] buzzWords = { "Spring REST Data", "Java 9", "Scala", "Groovy", "Hibernate", "Spring HATEOS", "The HAL Browser", "Spring webflux", }; String[] authorFirstName = { "John %s", "Steve %s", "Samantha %s", "Gale %s", "Tom %s" }; String[] authorLastName = { "Giles", "Gill", "Smith", "Armstrong" }; String[] blurbs = { "It was getting dark when the %s %s" , "Scott was nearly there when he heard that a %s %s", "Diana was a lovable Java coder until the %s %s", "The gripping story of a small %s and the day it %s" }; String[] blublMiddles = { "distaster", "dog", "cat", "turtle", "hurricane" }; String[] end = {
"hit the school", "memorised pi to 100 decimal places!", "became a world champion armwrestler", "became a Java REST master!!" }; Random random = new Random(); IntStream.range(0, 100) .forEach(i -> { String template = templates[i % templates.length]; String buzzword = buzzWords[i % buzzWords.length]; String blurbStart = blurbs[i % blurbs.length]; String middle = blublMiddles[i % blublMiddles.length]; String ending = end[i % end.length]; String blurb = String.format(blurbStart, middle, ending); String firstName = authorFirstName[i % authorFirstName.length]; String lastname = authorLastName[i % authorLastName.length]; Book book = new Book(String.format(template, buzzword), String.format(firstName, lastname), blurb, random.nextInt(1000-200) + 200); bookRepository.save(book); System.out.println(book); }); } }
repos\tutorials-master\persistence-modules\spring-data-rest-2\src\main\java\com\baeldung\halbrowser\config\DBLoader.java
2
请完成以下Java代码
public Layer getLayer() { return this.layer; } @Override public boolean contains(T item) { return isIncluded(item) && !isExcluded(item); } private boolean isIncluded(T item) { if (this.includes.isEmpty()) { return true; } for (ContentFilter<T> include : this.includes) { if (include.matches(item)) { return true; } } return false;
} private boolean isExcluded(T item) { if (this.excludes.isEmpty()) { return false; } for (ContentFilter<T> exclude : this.excludes) { if (exclude.matches(item)) { return true; } } return false; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\layer\IncludeExcludeContentSelector.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCustomer { @JsonInclude(JsonInclude.Include.NON_EMPTY) String companyName; @JsonInclude(JsonInclude.Include.NON_EMPTY) String contactName; @JsonInclude(JsonInclude.Include.NON_EMPTY) String contactEmail; @JsonInclude(JsonInclude.Include.NON_EMPTY) String contactPhone; String street; String streetNo; String addressSuffix1; String addressSuffix2; String addressSuffix3; String postal; String city; @JsonInclude(JsonInclude.Include.NON_EMPTY) String countryCode; @JsonInclude(JsonInclude.Include.NON_EMPTY) String deliveryInfo; @JsonInclude(JsonInclude.Include.NON_EMPTY) String language; @JsonInclude(JsonInclude.Include.NON_EMPTY) String shipmentAllocationBestBeforePolicy; boolean company; @JsonCreator @Builder public JsonCustomer(
@JsonProperty("companyName") @Nullable final String companyName, @JsonProperty("contactName") @Nullable final String contactName, @JsonProperty("contactEmail") @Nullable final String contactEmail, @JsonProperty("contactPhone") @Nullable final String contactPhone, @JsonProperty("street") @NonNull final String street, @JsonProperty("streetNo") @NonNull final String streetNo, @JsonProperty("addressSuffix1") final String addressSuffix1, @JsonProperty("addressSuffix2") final String addressSuffix2, @JsonProperty("addressSuffix3") final String addressSuffix3, @JsonProperty("postal") @NonNull final String postal, @JsonProperty("city") @NonNull final String city, @JsonProperty("countryCode") @Nullable final String countryCode, @JsonProperty("deliveryInfo") @Nullable final String deliveryInfo, @JsonProperty("language") @Nullable final String language, @JsonProperty("shipmentAllocationBestBeforePolicy") @Nullable final String shipmentAllocationBestBeforePolicy, @JsonProperty("company") @Nullable final boolean company ) { this.companyName = companyName; this.contactName = contactName; this.contactEmail = contactEmail; this.contactPhone = contactPhone; this.street = street; this.streetNo = streetNo; this.addressSuffix1 = addressSuffix1; this.addressSuffix2 = addressSuffix2; this.addressSuffix3 = addressSuffix3; this.postal = postal; this.city = city; this.countryCode = countryCode; this.deliveryInfo = deliveryInfo; this.language = language; this.shipmentAllocationBestBeforePolicy = shipmentAllocationBestBeforePolicy; this.company = company; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-shipping\src\main\java\de\metas\common\shipping\v1\shipmentcandidate\JsonCustomer.java
2
请完成以下Java代码
protected void configureQuery(ExternalTaskQueryImpl query) { getAuthorizationManager().configureExternalTaskQuery(query); getTenantManager().configureQuery(query); } protected void configureQuery(ListQueryParameterObject parameter) { getAuthorizationManager().configureExternalTaskFetch(parameter); getTenantManager().configureQuery(parameter); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } protected boolean shouldApplyOrdering(boolean usePriority, boolean useCreateTime) { return usePriority || useCreateTime; } protected boolean useCreateTime(List<QueryOrderingProperty> orderingProperties) {
return orderingProperties.stream() .anyMatch(orderingProperty -> CREATE_TIME.getName().equals(orderingProperty.getQueryProperty().getName())); } public void fireExternalTaskAvailableEvent() { Context.getCommandContext() .getTransactionContext() .addTransactionListener(TransactionState.COMMITTED, new TransactionListener() { @Override public void execute(CommandContext commandContext) { ProcessEngineImpl.EXT_TASK_CONDITIONS.signalAll(); } }); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ExternalTaskManager.java
1
请完成以下Java代码
public class X_AD_Org_Mapping extends org.compiere.model.PO implements I_AD_Org_Mapping, org.compiere.model.I_Persistent { private static final long serialVersionUID = 830925188L; /** Standard Constructor */ public X_AD_Org_Mapping (final Properties ctx, final int AD_Org_Mapping_ID, @Nullable final String trxName) { super (ctx, AD_Org_Mapping_ID, trxName); } /** Load Constructor */ public X_AD_Org_Mapping (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Org_Mapping_ID (final int AD_Org_Mapping_ID) { if (AD_Org_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Org_Mapping_ID, AD_Org_Mapping_ID); } @Override public int getAD_Org_Mapping_ID() {
return get_ValueAsInt(COLUMNNAME_AD_Org_Mapping_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org_Mapping.java
1
请完成以下Java代码
public class User { private String name; private String address; private String email; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } public String getName(){ return name; } public void setName(String name){ this.name = name; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot integrated with JSP\SpringJSPUpdate\src\main\java\spring\jsp\User.java
1
请完成以下Java代码
public void migrateScope(ActivityExecution scopeExecution) { } @Override public void onParseMigratingInstance(MigratingInstanceParseContext parseContext, MigratingActivityInstance migratingInstance) { ExecutionEntity execution = migratingInstance.resolveRepresentativeExecution(); for (TaskEntity task : execution.getTasks()) { migratingInstance.addMigratingDependentInstance(new MigratingUserTaskInstance(task, migratingInstance)); parseContext.consume(task); Collection<VariableInstanceEntity> variables = task.getVariablesInternal(); if (variables != null) { for (VariableInstanceEntity variable : variables) { // we don't need to represent task variables in the migrating instance structure because // they are migrated by the MigratingTaskInstance as well parseContext.consume(variable); } } }
} // getters public TaskDefinition getTaskDefinition() { return taskDecorator.getTaskDefinition(); } public ExpressionManager getExpressionManager() { return taskDecorator.getExpressionManager(); } public TaskDecorator getTaskDecorator() { return taskDecorator; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\UserTaskActivityBehavior.java
1
请完成以下Java代码
public List<int[]> generate(int n, int r) { List<int[]> combinations = new ArrayList<>(); int[] combination = new int[r]; // initialize with lowest lexicographic combination for (int i = 0; i < r; i++) { combination[i] = i; } while (combination[r - 1] < n) { combinations.add(combination.clone()); // generate next combination in lexicographic order int t = r - 1; while (t != 0 && combination[t] == n - r + t) { t--; } combination[t]++;
for (int i = t + 1; i < r; i++) { combination[i] = combination[i - 1] + 1; } } return combinations; } public static void main(String[] args) { IterativeCombinationGenerator generator = new IterativeCombinationGenerator(); List<int[]> combinations = generator.generate(N, R); System.out.println(combinations.size()); for (int[] combination : combinations) { System.out.println(Arrays.toString(combination)); } } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\combination\IterativeCombinationGenerator.java
1
请完成以下Java代码
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Region. @param RegionName Name der Region */ @Override public void setRegionName (java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } /** Get Region. @return Name der Region */ @Override public java.lang.String getRegionName () { return (java.lang.String)get_Value(COLUMNNAME_RegionName); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag)
*/ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Postal.java
1
请完成以下Java代码
public int getC_NonBusinessDay_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_NonBusinessDay_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum. @param Date1 Date when business is not conducted */ @Override public void setDate1 (java.sql.Timestamp Date1) { set_Value (COLUMNNAME_Date1, Date1); } /** Get Datum. @return Date when business is not conducted */ @Override public java.sql.Timestamp getDate1 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_Date1); } /** Set Enddatum. @param EndDate Last effective date (inclusive) */ @Override public void setEndDate (java.sql.Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get Enddatum. @return Last effective date (inclusive) */ @Override public java.sql.Timestamp getEndDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_EndDate); } /** * Frequency AD_Reference_ID=540870 * Reference name: C_NonBusinessDay_Frequency */ public static final int FREQUENCY_AD_Reference_ID=540870; /** Weekly = W */ public static final String FREQUENCY_Weekly = "W"; /** Yearly = Y */ public static final String FREQUENCY_Yearly = "Y"; /** Set Häufigkeit. @param Frequency Häufigkeit von Ereignissen */ @Override public void setFrequency (java.lang.String Frequency) { set_Value (COLUMNNAME_Frequency, Frequency); } /** Get Häufigkeit. @return Häufigkeit von Ereignissen */ @Override public java.lang.String getFrequency () { return (java.lang.String)get_Value(COLUMNNAME_Frequency); } /** Set Repeat. @param IsRepeat Repeat */
@Override public void setIsRepeat (boolean IsRepeat) { set_Value (COLUMNNAME_IsRepeat, Boolean.valueOf(IsRepeat)); } /** Get Repeat. @return Repeat */ @Override public boolean isRepeat () { Object oo = get_Value(COLUMNNAME_IsRepeat); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_NonBusinessDay.java
1
请在Spring Boot框架中完成以下Java代码
public class StaticJWTController extends BaseController { @Autowired SecretService secretService; @RequestMapping(value = "/static-builder", method = GET) public JwtResponse fixedBuilder() throws UnsupportedEncodingException { String jws = Jwts.builder() .setIssuer("Stormpath") .setSubject("msilverman") .claim("name", "Micah Silverman") .claim("scope", "admins") .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @RequestMapping(value = "/parser", method = GET) public JwtResponse parser(@RequestParam String jwt) throws UnsupportedEncodingException {
Jws<Claims> jws = Jwts.parser() .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(jwt); return new JwtResponse(jws); } @RequestMapping(value = "/parser-enforce", method = GET) public JwtResponse parserEnforce(@RequestParam String jwt) throws UnsupportedEncodingException { Jws<Claims> jws = Jwts.parser() .requireIssuer("Stormpath") .require("hasMotorcycle", true) .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(jwt); return new JwtResponse(jws); } }
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\controller\StaticJWTController.java
2
请完成以下Java代码
private void waitForLimitReset(@NonNull final Duration resetAfter) { final int maxTimeToWaitMs = sysConfigBL.getIntValue(MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getName(), MAX_TIME_TO_WAIT_FOR_LIMIT_RESET.getDefaultValue() ); if (resetAfter.get(MILLIS) > maxTimeToWaitMs) { throw new AdempiereException("Limit Reset is too far in the future! aborting!") .appendParametersToMessage() .setParameter("ResetAfter", resetAfter) .setParameter("MaxMsToWaitForLimitReset", maxTimeToWaitMs); } try { Loggables.withLogger(log, Level.DEBUG) .addLog("*** Waiting for limit reset!Time to wait: {}.", resetAfter); Thread.sleep(resetAfter.get(MILLIS));
} catch (final InterruptedException e) { throw new AdempiereException(e.getMessage(), e); } } private RestTemplate restTemplate() { return new RestTemplateBuilder() .errorHandler(responseErrorHandler) .setConnectTimeout(Duration.ofMillis(sysConfigBL.getIntValue(CONNECTION_TIMEOUT.getName(), CONNECTION_TIMEOUT.getDefaultValue()))) .setReadTimeout(Duration.ofMillis(sysConfigBL.getIntValue(READ_TIMEOUT.getName(),READ_TIMEOUT.getDefaultValue()))) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.issue.tracking.everhour\src\main\java\de\metas\issue\tracking\everhour\api\rest\RestService.java
1
请完成以下Java代码
public final Stream<IView> streamAllViews() { return Stream.empty(); } @Override public final void invalidateView(final ViewId viewId) { final PricingConditionsView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PricingConditionsView createView(@NonNull final CreateViewRequest request) { final PricingConditionsRowData rowsData = createPricingConditionsRowData(request); return createView(rowsData); } protected abstract PricingConditionsRowData createPricingConditionsRowData(CreateViewRequest request); private PricingConditionsView createView(final PricingConditionsRowData rowsData) { return PricingConditionsView.builder() .viewId(ViewId.random(windowId)) .rowsData(rowsData) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_CopyRowToEditable.class)) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_SaveEditableRow.class)) .filterDescriptors(filtersFactory.getFilterDescriptorsProvider()) .build(); } protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData() { return PricingConditionsRowsLoader.builder() .lookups(lookups); } @Override
public PricingConditionsView filterView( @NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo_IGNORED) { return PricingConditionsView.cast(view) .filter(filtersFactory.extractFilters(filterViewRequest)); } private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable() .anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } protected final DocumentFilterList extractFilters(final CreateViewRequest request) { return filtersFactory.extractFilters(request); } @lombok.Value(staticConstructor = "of") private static final class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
1
请在Spring Boot框架中完成以下Java代码
private JsonRfq toJsonRfq(@NonNull final Rfq rfq, @NonNull final Locale locale) { final Product product = productSuppliesService.getProductById(rfq.getProduct_id()); final BigDecimal pricePromisedUserEntered = rfq.getPricePromisedUserEntered(); return JsonRfq.builder() .rfqId(rfq.getIdAsString()) .productName(product.getName(locale)) .packingInfo(product.getPackingInfo(locale)) .dateStart(rfq.getDateStart()) .dateEnd(rfq.getDateEnd()) .dateClose(rfq.getDateClose()) .qtyRequested(renderQty(rfq.getQtyRequested(), rfq.getQtyCUInfo(), locale)) .qtyPromised(renderQty(rfq.getQtyPromisedUserEntered(), rfq.getQtyCUInfo(), locale)) .price(pricePromisedUserEntered) .priceRendered(renderPrice(pricePromisedUserEntered, rfq.getCurrencyCode(), locale)) .quantities(toJsonRfqQtysList(rfq, locale)) .confirmedByUser(rfq.isConfirmedByUser()) .build(); } private static ArrayList<JsonRfqQty> toJsonRfqQtysList( @NonNull final Rfq rfq, @NonNull final Locale locale) { final ArrayList<JsonRfqQty> jsonRfqQtys = new ArrayList<>(); for (final LocalDate date : rfq.generateAllDaysSet()) { final RfqQty rfqQty = rfq.getRfqQtyByDate(date); final JsonRfqQty jsonRfqQty = rfqQty != null ? toJsonRfqQty(rfqQty, rfq.getQtyCUInfo(), locale) : toZeroJsonRfqQty(date, rfq.getQtyCUInfo(), locale); jsonRfqQtys.add(jsonRfqQty); } return jsonRfqQtys; } private static JsonRfqQty toJsonRfqQty( @NonNull final RfqQty rfqQty, @NonNull final String uom, @NonNull final Locale locale) { final BigDecimal qtyPromised = rfqQty.getQtyPromisedUserEntered(); return JsonRfqQty.builder()
.date(rfqQty.getDatePromised()) .dayCaption(DateUtils.getDayName(rfqQty.getDatePromised(), locale)) .qtyPromised(qtyPromised) .qtyPromisedRendered(renderQty(qtyPromised, uom, locale)) .confirmedByUser(rfqQty.isConfirmedByUser()) .build(); } private static JsonRfqQty toZeroJsonRfqQty( @NonNull final LocalDate date, @NonNull final String uom, @NonNull final Locale locale) { return JsonRfqQty.builder() .date(date) .dayCaption(DateUtils.getDayName(date, locale)) .qtyPromised(BigDecimal.ZERO) .qtyPromisedRendered(renderQty(BigDecimal.ZERO, uom, locale)) .confirmedByUser(true) .build(); } private static String renderQty( @NonNull final BigDecimal qty, @NonNull final String uom, @NonNull final Locale locale) { final NumberFormat formatter = NumberFormat.getNumberInstance(locale); return formatter.format(qty) + " " + uom; } private static String renderPrice( @NonNull final BigDecimal price, @NonNull final String currencyCode, @NonNull final Locale locale) { final NumberFormat formatter = NumberFormat.getNumberInstance(locale); return formatter.format(price) + " " + currencyCode; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\rfq\RfQRestController.java
2
请在Spring Boot框架中完成以下Java代码
public class ProcessEngineResource { @Autowired @Qualifier("processEngine") protected ProcessEngine engine; @Autowired(required=false) protected BpmnRestApiInterceptor restApiInterceptor; @ApiOperation(value = "Get engine info", tags = { "Engine" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates the engine info is returned."), }) @GetMapping(value = "/management/engine", produces = "application/json") public EngineInfoResponse getEngineInfo() { if (restApiInterceptor != null) { restApiInterceptor.accessManagementInfo(); } EngineInfoResponse response = new EngineInfoResponse(); try { EngineInfo engineInfo = ProcessEngines.getProcessEngineInfo(engine.getName()); if (engineInfo != null) {
response.setName(engineInfo.getName()); response.setResourceUrl(engineInfo.getResourceUrl()); response.setException(engineInfo.getException()); } else { // Revert to using process-engine directly response.setName(engine.getName()); } } catch (Exception e) { throw new FlowableException("Error retrieving process info", e); } response.setVersion(ProcessEngine.class.getPackage().getImplementationVersion()); return response; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\ProcessEngineResource.java
2
请完成以下Java代码
public CompletableFuture<Void> incrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) { return commandGateway.send(new IncrementProductCountCommand(orderId, productId)); } @PostMapping("/order/{order-id}/product/{product-id}/decrement") public CompletableFuture<Void> decrementProduct(@PathVariable("order-id") String orderId, @PathVariable("product-id") String productId) { return commandGateway.send(new DecrementProductCountCommand(orderId, productId)); } @PostMapping("/order/{order-id}/confirm") public CompletableFuture<Void> confirmOrder(@PathVariable("order-id") String orderId) { return commandGateway.send(new ConfirmOrderCommand(orderId)); } @PostMapping("/order/{order-id}/ship") public CompletableFuture<Void> shipOrder(@PathVariable("order-id") String orderId) { return commandGateway.send(new ShipOrderCommand(orderId)); } @GetMapping("/all-orders") public CompletableFuture<List<OrderResponse>> findAllOrders() {
return orderQueryService.findAllOrders(); } @GetMapping(path = "/all-orders-streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<OrderResponse> allOrdersStreaming() { return orderQueryService.allOrdersStreaming(); } @GetMapping("/total-shipped/{product-id}") public Integer totalShipped(@PathVariable("product-id") String productId) { return orderQueryService.totalShipped(productId); } @GetMapping(path = "/order-updates/{order-id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<OrderResponse> orderUpdates(@PathVariable("order-id") String orderId) { return orderQueryService.orderUpdates(orderId); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\gui\OrderRestEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
public ServletRegistrationBean registerServlet() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new RegisterServlet(), "/registerServlet"); servletRegistrationBean.addInitParameter("name", "registerServlet"); servletRegistrationBean.addInitParameter("sex", "man"); servletRegistrationBean.setIgnoreRegistrationFailure(true); return servletRegistrationBean; } @Bean public ServletContextInitializer servletContextInitializer() { return (servletContext) -> { ServletRegistration initServlet = servletContext.addServlet("initServlet", InitServlet.class); initServlet.addMapping("/initServlet"); initServlet.setInitParameter("name", "initServlet"); initServlet.setInitParameter("sex", "man"); }; } @Bean public RestTemplate defaultRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(5)) .basicAuthentication("test", "test") .build(); } @Bean public RestClient defaultRestClient(RestClient.Builder restClientBuilder) { ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS .withConnectTimeout(Duration.ofSeconds(3)) .withReadTimeout(Duration.ofSeconds(3)); ClientHttpRequestFactory requestFactory = ClientHttpRequestFactories.get(settings); return restClientBuilder .baseUrl("http://localhost:8080") .defaultHeader("Authorization", "Bearer test") .requestFactory(requestFactory) .build(); } }
repos\spring-boot-best-practice-master\spring-boot-web\src\main\java\cn\javastack\springboot\web\config\WebConfig.java
2
请完成以下Java代码
public int getSortNo() { return getPreconditionsResolution().getSortNo().orElse(this.sortNo); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get().getValue(); } public Duration getPreconditionsResolutionCalcDuration() { return preconditionsResolutionSupplier.get().getDuration(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public boolean isEnabled() { final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution(); return preconditionsResolution.isAccepted(); } public boolean isEnabledOrNotSilent() { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_AD_Process.Table_Name, processId == null ? null : processId.toAdProcessIdOrNull())) { final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution(); return preconditionsResolution.isAccepted() || !preconditionsResolution.isInternal(); } } public boolean isInternal() { final ProcessPreconditionsResolution preconditionsResolution = getPreconditionsResolution(); return preconditionsResolution.isInternal(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } public Map<String, Object> getDebugProperties() {
final ImmutableMap.Builder<String, Object> debugProperties = ImmutableMap.builder(); if (debugProcessClassname != null) { debugProperties.put("debug-classname", debugProcessClassname); } return debugProperties.build(); } public boolean isDisplayedOn(@NonNull final DisplayPlace displayPlace) { return getDisplayPlaces().contains(displayPlace); } @Value private static class ValueAndDuration<T> { public static <T> ValueAndDuration<T> fromSupplier(final Supplier<T> supplier) { final Stopwatch stopwatch = Stopwatch.createStarted(); final T value = supplier.get(); final Duration duration = Duration.ofNanos(stopwatch.stop().elapsed(TimeUnit.NANOSECONDS)); return new ValueAndDuration<>(value, duration); } T value; Duration duration; private ValueAndDuration(final T value, final Duration duration) { this.value = value; this.duration = duration; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\descriptor\WebuiRelatedProcessDescriptor.java
1
请完成以下Java代码
private HUQRCode toHUQRCode(final @NotNull ScannedCode scannedCode) { final IHUQRCode parsedHUQRCode = huQRCodesService.parse(scannedCode); if (parsedHUQRCode instanceof HUQRCode) { return (HUQRCode)parsedHUQRCode; } else { throw new AdempiereException("Cannot convert " + scannedCode + " to actual HUQRCode") .setParameter("parsedHUQRCode", parsedHUQRCode) .setParameter("parsedHUQRCode type", parsedHUQRCode.getClass().getSimpleName()); } } @PostMapping("/nextEligibleLineToPack") public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(@RequestBody @NonNull final JsonGetNextEligibleLineRequest request) { assertApplicationAccess(); return pickingMobileApplication.getNextEligibleLineToPack(request, getLoggedUserId()); } @PostMapping("/job/{wfProcessId}/pickAll") public WFProcess pickAllAndComplete(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess();
final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); return pickingMobileApplication.pickAll(wfProcessId, getLoggedUserId()); } @GetMapping("/job/{wfProcessId}/qtyAvailable") public JsonPickingJobQtyAvailable getQtyAvailable(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final PickingJobQtyAvailable qtyAvailable = pickingMobileApplication.getQtyAvailable(wfProcessId, getLoggedUserId()); return JsonPickingJobQtyAvailable.of(qtyAvailable); } @PostMapping("/job/{wfProcessId}/complete") public WFProcess complete(@PathVariable("wfProcessId") final String wfProcessIdStr) { assertApplicationAccess(); return pickingMobileApplication.complete(WFProcessId.ofString(wfProcessIdStr), getLoggedUserId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\PickingRestController.java
1
请完成以下Java代码
public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Truck extends Vehicle { private double payloadCapacity; public Truck() {
} public Truck(String make, String model, double payloadCapacity) { super(make, model); this.payloadCapacity = payloadCapacity; } public double getPayloadCapacity() { return payloadCapacity; } public void setPayloadCapacity(double payloadCapacity) { this.payloadCapacity = payloadCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\TypeInfoAnnotatedStructure.java
1
请完成以下Java代码
public HistoricDetailAssignmentEntity createHistoricDetailAssignment() { return new HistoricDetailAssignmentEntityImpl(); } @Override public HistoricDetailTransitionInstanceEntity createHistoricDetailTransitionInstance() { return new HistoricDetailTransitionInstanceEntityImpl(); } @Override public HistoricDetailVariableInstanceUpdateEntity createHistoricDetailVariableInstanceUpdate() { return new HistoricDetailVariableInstanceUpdateEntityImpl(); } @Override @SuppressWarnings("unchecked") public List<HistoricDetailEntity> findHistoricDetailsByProcessInstanceId(String processInstanceId) { return getDbSqlSession().selectList("selectHistoricDetailByProcessInstanceId", processInstanceId); } @Override @SuppressWarnings("unchecked") public List<HistoricDetailEntity> findHistoricDetailsByTaskId(String taskId) { return getDbSqlSession().selectList("selectHistoricDetailByTaskId", taskId); } @Override public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) { return (Long) getDbSqlSession().selectOne( "selectHistoricDetailCountByQueryCriteria", historicVariableUpdateQuery ); } @Override @SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByQueryCriteria( HistoricDetailQueryImpl historicVariableUpdateQuery, Page page ) { return getDbSqlSession().selectList("selectHistoricDetailsByQueryCriteria", historicVariableUpdateQuery, page); } @Override
@SuppressWarnings("unchecked") public List<HistoricDetail> findHistoricDetailsByNativeQuery( Map<String, Object> parameterMap, int firstResult, int maxResults ) { return getDbSqlSession().selectListWithRawParameter( "selectHistoricDetailByNativeQuery", parameterMap, firstResult, maxResults ); } @Override public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) { return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByNativeQuery", parameterMap); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricDetailDataManager.java
1
请完成以下Java代码
public void executeV5Job(Job job) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.executeJob(job); } @Override public void executeV5JobWithLockAndRetry(final Job job) { // Retrieving the compatibility handler needs to be done outside of the executeJobWithLockAndRetry call, // as it shouldn't be wrapped in a transaction. Flowable5CompatibilityHandler compatibilityHandler = processEngineConfiguration.getCommandExecutor().execute(new Command<>() { @Override public Flowable5CompatibilityHandler execute(CommandContext commandContext) { return CommandContextUtil.getProcessEngineConfiguration(commandContext).getFlowable5CompatibilityHandler(); } }); // Note: no transaction (on purpose)
compatibilityHandler.executeJobWithLockAndRetry(job); } @Override public void deleteV5Job(String jobId) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.deleteJob(jobId); } @Override public void handleFailedV5Job(AbstractRuntimeJobEntity job, Throwable exception) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.handleFailedJob(job, exception); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\DefaultInternalJobCompatibilityManager.java
1
请完成以下Java代码
public class OnlCgformDemoController { /** * Online表单 http 增强,list增强示例 * @param params * @return */ @PostMapping("/enhanceJavaListHttp") public Result<?> enhanceJavaListHttp(@RequestBody JSONObject params) { log.info(" --- params:" + params.toJSONString()); JSONArray dataList = params.getJSONArray("dataList"); List<DictModel> dict = virtualDictData(); for (int i = 0; i < dataList.size(); i++) { JSONObject record = dataList.getJSONObject(i); String province = record.getString("province"); if (province == null) { continue; } String text = dict.stream() .filter(p -> province.equals(p.getValue())) .map(DictModel::getText) .findAny() .orElse(province); record.put("province", text); } Result<?> res = Result.OK(dataList); res.setCode(1); return res; } /** * 模拟字典数据 * * @return */ private List<DictModel> virtualDictData() { List<DictModel> dict = new ArrayList<>(); dict.add(new DictModel("bj", "北京")); dict.add(new DictModel("sd", "山东")); dict.add(new DictModel("ah", "安徽")); return dict; } /** * Online表单 http 增强,add、edit增强示例 * @param params * @return */ @PostMapping("/enhanceJavaHttp") public Result<?> enhanceJavaHttp(@RequestBody JSONObject params) {
log.info(" --- params:" + params.toJSONString()); String tableName = params.getString("tableName"); JSONObject record = params.getJSONObject("record"); /* * 业务场景一: 获取提交表单数据,进行其他业务关联操作 * (比如:根据入库单,同步更改库存) */ log.info(" --- tableName:" + tableName); log.info(" --- 行数据:" + record.toJSONString()); /* * 业务场景二: 保存数据之前进行数据的校验 * 直接返回错误状态即可 */ String phone = record.getString("phone"); if (oConvertUtils.isEmpty(phone)) { return Result.error("手机号不能为空!"); } /* * 业务场景三: 保存数据之对数据的处理 * 直接操作 record 即可 */ record.put("phone", "010-" + phone); /* 其他业务场景自行实现 */ // 返回场景一: 不对 record 做任何修改的情况下,可以直接返回 code, // 返回 0 = 丢弃当前数据 // 返回 1 = 新增当前数据 // 返回 2 = 修改当前数据 TODO(?)存疑 // return Result.OK(1); // 返回场景二: 需要对 record 做修改的情况下,需要返回一个JSONObject对象(或者Map也行) JSONObject res = new JSONObject(); res.put("code", 1); // 将 record 返回以进行修改 res.put("record", record); // TODO 不要 code 的概念 return Result.OK(res); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\online\OnlCgformDemoController.java
1
请完成以下Java代码
public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public void setCountEnqueued (final int CountEnqueued) { set_ValueNoCheck (COLUMNNAME_CountEnqueued, CountEnqueued); } @Override public int getCountEnqueued() { return get_ValueAsInt(COLUMNNAME_CountEnqueued); } @Override public void setCountProcessed (final int CountProcessed) { set_ValueNoCheck (COLUMNNAME_CountProcessed, CountProcessed); } @Override public int getCountProcessed() { return get_ValueAsInt(COLUMNNAME_CountProcessed); }
@Override public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor() { return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class); } @Override public void setC_Queue_PackageProcessor(final de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor) { set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor); } @Override public void setC_Queue_PackageProcessor_ID (final int C_Queue_PackageProcessor_ID) { if (C_Queue_PackageProcessor_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, C_Queue_PackageProcessor_ID); } @Override public int getC_Queue_PackageProcessor_ID() { return get_ValueAsInt(COLUMNNAME_C_Queue_PackageProcessor_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_RV_Async_batch_statistics.java
1
请在Spring Boot框架中完成以下Java代码
private void addDefaultPackPermission(String packCode, String permission) { if (oConvertUtils.isEmpty(packCode)) { return; } //查询当前匹配非默认套餐包的其他默认套餐包 LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>(); query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT); query.eq(SysTenantPack::getPackCode, packCode); List<SysTenantPack> otherDefaultPacks = sysTenantPackMapper.selectList(query); for (SysTenantPack pack : otherDefaultPacks) { //新增套餐包用户菜单权限 this.addPermission(pack.getId(), permission); } } /** * 根据套餐包的code 删除其他关联默认套餐包下的角色与菜单的关系 * * @param packCode * @param permissionId */ private void deleteDefaultPackPermission(String packCode, String permissionId) { if (oConvertUtils.isEmpty(packCode)) { return; } //查询当前匹配非默认套餐包的其他默认套餐包 LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>(); query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT); query.eq(SysTenantPack::getPackCode, packCode); List<SysTenantPack> defaultPacks = sysTenantPackMapper.selectList(query); for (SysTenantPack pack : defaultPacks) { //删除套餐权限 deletePackPermission(pack.getId(), permissionId); } }
/** * 同步同 packCode 下的相关套餐包数据 * * @param sysTenantPack */ private void syncRelatedPackDataByDefaultPack(SysTenantPack sysTenantPack) { //查询与默认套餐相同code的套餐 LambdaQueryWrapper<SysTenantPack> query = new LambdaQueryWrapper<>(); query.ne(SysTenantPack::getPackType, CommonConstant.TENANT_PACK_DEFAULT); query.eq(SysTenantPack::getPackCode, sysTenantPack.getPackCode()); List<SysTenantPack> relatedPacks = sysTenantPackMapper.selectList(query); for (SysTenantPack pack : relatedPacks) { //更新自定义套餐 pack.setPackName(sysTenantPack.getPackName()); pack.setStatus(sysTenantPack.getStatus()); pack.setRemarks(sysTenantPack.getRemarks()); pack.setIzSysn(sysTenantPack.getIzSysn()); sysTenantPackMapper.updateById(pack); //同步默认套餐报下的所有用户已 if (oConvertUtils.isNotEmpty(sysTenantPack.getIzSysn()) && CommonConstant.STATUS_1.equals(sysTenantPack.getIzSysn())) { this.addPackUserByPackTenantId(pack.getTenantId(), pack.getId()); } } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTenantPackServiceImpl.java
2
请完成以下Java代码
public void addArtifactToMap(Artifact artifact) { if (artifact != null && StringUtils.isNotEmpty(artifact.getId())) { artifactMap.put(artifact.getId(), artifact); if (getParentContainer() != null) { getParentContainer().addArtifactToMap(artifact); } } } @Override public void removeArtifact(String artifactId) { Artifact artifact = getArtifact(artifactId); if (artifact != null) { artifactList.remove(artifact); } } @Override public SubProcess clone() { SubProcess clone = new SubProcess(); clone.setValues(this); return clone; } public void setValues(SubProcess otherElement) { super.setValues(otherElement); /* * This is required because data objects in Designer have no DI info and are added as properties, not flow elements * * Determine the differences between the 2 elements' data object */ for (ValuedDataObject thisObject : getDataObjects()) { boolean exists = false; for (ValuedDataObject otherObject : otherElement.getDataObjects()) { if (thisObject.getId().equals(otherObject.getId())) { exists = true; break; } } if (!exists) { // missing object removeFlowElement(thisObject.getId());
} } dataObjects = new ArrayList<>(); if (otherElement.getDataObjects() != null && !otherElement.getDataObjects().isEmpty()) { for (ValuedDataObject dataObject : otherElement.getDataObjects()) { ValuedDataObject clone = dataObject.clone(); dataObjects.add(clone); // add it to the list of FlowElements // if it is already there, remove it first so order is same as // data object list removeFlowElement(clone.getId()); addFlowElement(clone); } } flowElementList.clear(); for (FlowElement flowElement : otherElement.getFlowElements()) { addFlowElement(flowElement.clone()); } artifactList.clear(); for (Artifact artifact : otherElement.getArtifacts()) { addArtifact(artifact.clone()); } } public List<ValuedDataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<ValuedDataObject> dataObjects) { this.dataObjects = dataObjects; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SubProcess.java
1
请在Spring Boot框架中完成以下Java代码
public PgaTourService manage(GolfTournament golfTournament) { GolfTournament currentGolfTournament = this.golfTournament; Assert.state(currentGolfTournament == null, () -> String.format("Can only manage 1 golf tournament at a time; currently managing [%s]", currentGolfTournament)); this.golfTournament = golfTournament; return this; } // tag::play[] @Scheduled(initialDelay = 5000L, fixedDelay = 2500L) public void play() { GolfTournament golfTournament = this.golfTournament; if (isNotFinished(golfTournament)) { playHole(golfTournament); finish(golfTournament); } } // end::play[] private synchronized void playHole(@NonNull GolfTournament golfTournament) { GolfCourse golfCourse = golfTournament.getGolfCourse(); Set<Integer> occupiedHoles = new HashSet<>(); for (GolfTournament.Pairing pairing : golfTournament) { int hole = pairing.nextHole(); if (!occupiedHoles.contains(hole)) { if (golfCourse.isValidHoleNumber(hole)) { occupiedHoles.add(hole); pairing.setHole(hole); updateScore(this::calculateRunningScore, pairing.getPlayerOne()); updateScore(this::calculateRunningScore, pairing.getPlayerTwo()); } } } }
private Golfer updateScore(@NonNull Function<Integer, Integer> scoreFunction, @NonNull Golfer player) { player.setScore(scoreFunction.apply(player.getScore())); this.golferService.update(player); return player; } private int calculateFinalScore(@Nullable Integer scoreRelativeToPar) { int finalScore = scoreRelativeToPar != null ? scoreRelativeToPar : 0; int parForCourse = getGolfTournament() .map(GolfTournament::getGolfCourse) .map(GolfCourse::getParForCourse) .orElse(GolfCourse.STANDARD_PAR_FOR_COURSE); return parForCourse + finalScore; } private int calculateRunningScore(@Nullable Integer currentScore) { int runningScore = currentScore != null ? currentScore : 0; int scoreDelta = this.random.nextInt(SCORE_DELTA_BOUND); scoreDelta *= this.random.nextBoolean() ? -1 : 1; return runningScore + scoreDelta; } private void finish(@NonNull GolfTournament golfTournament) { for (GolfTournament.Pairing pairing : golfTournament) { if (pairing.signScorecard()) { updateScore(this::calculateFinalScore, pairing.getPlayerOne()); updateScore(this::calculateFinalScore, pairing.getPlayerTwo()); } } } } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\PgaTourService.java
2
请完成以下Java代码
public String getContentType() { return null; } @Override public boolean isEmpty() { return input == null || input.length == 0; } @Override public long getSize() { return input.length; } @Override public byte[] getBytes() {
return input; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(input); } @Override public void transferTo(File destination) throws IOException, IllegalStateException { try(FileOutputStream fos = new FileOutputStream(destination)) { fos.write(input); } } }
repos\tutorials-master\spring-web-modules\spring-mvc-file\src\main\java\com\baeldung\file\CustomMultipartFile.java
1
请完成以下Java代码
public void handleCompleteForInvoice(final I_C_Invoice invoice) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(invoice)) { // FIXME 06162: Save invoice before processing (e.g DocStatus needs to be accurate) Services.get(IInvoiceDAO.class).save(invoice); Services.get(IInvoiceCandBL.class).handleCompleteForInvoice(invoice); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_REVERSECORRECT }) public void handleReversalForInvoice(final I_C_Invoice invoice) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(invoice)) { Services.get(IInvoiceCandBL.class).handleReversalForInvoice(invoice); } if (invoice.getReversal_ID() > 0) { invoiceWithDetailsService.copyDetailsToReversal(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()), InvoiceId.ofRepoId(invoice.getReversal_ID())); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_VOID }) public void handleVoidingForInvoice(final I_C_Invoice invoice) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(invoice))
{ Services.get(IInvoiceCandBL.class).handleVoidingForInvoice(invoice); } } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void closePartiallyInvoiced_InvoiceCandidates(final I_C_Invoice invoice) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(invoice)) { Services.get(IInvoiceCandBL.class).closePartiallyInvoiced_InvoiceCandidates(invoice); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REVERSECORRECT, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL }) public void candidatesUnProcess(final I_C_Invoice invoice) { try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(invoice)) { Services.get(IInvoiceCandBL.class).candidates_unProcess(invoice); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Invoice.java
1
请在Spring Boot框架中完成以下Java代码
public NotificationSettings saveNotificationSettings(@RequestBody @Valid NotificationSettings notificationSettings, @AuthenticationPrincipal SecurityUser user) throws ThingsboardException { accessControlService.checkPermission(user, Resource.ADMIN_SETTINGS, Operation.WRITE); TenantId tenantId = user.isSystemAdmin() ? TenantId.SYS_TENANT_ID : user.getTenantId(); notificationSettingsService.saveNotificationSettings(tenantId, notificationSettings); return notificationSettings; } @ApiOperation(value = "Get notification settings (getNotificationSettings)", notes = "Retrieves notification settings for this tenant or sysadmin." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @GetMapping("/notification/settings") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") public NotificationSettings getNotificationSettings(@AuthenticationPrincipal SecurityUser user) throws ThingsboardException { accessControlService.checkPermission(user, Resource.ADMIN_SETTINGS, Operation.READ); TenantId tenantId = user.isSystemAdmin() ? TenantId.SYS_TENANT_ID : user.getTenantId(); return notificationSettingsService.findNotificationSettings(tenantId); } @ApiOperation(value = "Get available delivery methods (getAvailableDeliveryMethods)", notes = "Returns the list of delivery methods that are properly configured and are allowed to be used for sending notifications." + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @GetMapping("/notification/deliveryMethods") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") public List<NotificationDeliveryMethod> getAvailableDeliveryMethods(@AuthenticationPrincipal SecurityUser user) throws ThingsboardException { return notificationCenter.getAvailableDeliveryMethods(user.getTenantId()); }
@PostMapping("/notification/settings/user") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") public UserNotificationSettings saveUserNotificationSettings(@RequestBody @Valid UserNotificationSettings settings, @AuthenticationPrincipal SecurityUser user) { return notificationSettingsService.saveUserNotificationSettings(user.getTenantId(), user.getId(), settings); } @GetMapping("/notification/settings/user") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") public UserNotificationSettings getUserNotificationSettings(@AuthenticationPrincipal SecurityUser user) { return notificationSettingsService.getUserNotificationSettings(user.getTenantId(), user.getId(), true); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\NotificationController.java
2
请完成以下Java代码
public class MessageFlowParser implements BpmnXMLConstants { protected static final Logger LOGGER = LoggerFactory.getLogger(MessageFlowParser.class.getName()); public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception { String id = xtr.getAttributeValue(null, ATTRIBUTE_ID); if (StringUtils.isNotEmpty(id)) { MessageFlow messageFlow = new MessageFlow(); messageFlow.setId(id); String name = xtr.getAttributeValue(null, ATTRIBUTE_NAME); if (StringUtils.isNotEmpty(name)) { messageFlow.setName(name); } String sourceRef = xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SOURCE_REF); if (StringUtils.isNotEmpty(sourceRef)) {
messageFlow.setSourceRef(sourceRef); } String targetRef = xtr.getAttributeValue(null, ATTRIBUTE_FLOW_TARGET_REF); if (StringUtils.isNotEmpty(targetRef)) { messageFlow.setTargetRef(targetRef); } String messageRef = xtr.getAttributeValue(null, ATTRIBUTE_MESSAGE_REF); if (StringUtils.isNotEmpty(messageRef)) { messageFlow.setMessageRef(messageRef); } model.addMessageFlow(messageFlow); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\MessageFlowParser.java
1
请完成以下Java代码
public <T> List<T> getSelectedModels(final Class<T> modelClass) { // backward compatibility return streamSelectedModels(modelClass) .collect(ImmutableList.toImmutableList()); } @NonNull @Override public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass) { return Stream.of(getSelectedModel(modelClass)); } @Override public int getSingleSelectedRecordId() { return gridTab.getRecord_ID();
} @Override public SelectionSize getSelectionSize() { // backward compatibility return SelectionSize.ofSize(1); } @Override public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass) { return gridTab.createCurrentRecordsQueryFilter(recordClass); } } } // GridTab
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getLicencePic() { return licencePic; } public void setLicencePic(String licencePic) { this.licencePic = licencePic; } public Timestamp getRegisterTime() { return registerTime; } public void setRegisterTime(Timestamp registerTime) { this.registerTime = registerTime; } public UserTypeEnum getUserTypeEnum() {
return userTypeEnum; } public void setUserTypeEnum(UserTypeEnum userTypeEnum) { this.userTypeEnum = userTypeEnum; } public UserStateEnum getUserStateEnum() { return userStateEnum; } public void setUserStateEnum(UserStateEnum userStateEnum) { this.userStateEnum = userStateEnum; } public RoleEntity getRoleEntity() { return roleEntity; } public void setRoleEntity(RoleEntity roleEntity) { this.roleEntity = roleEntity; } @Override public String toString() { return "UserEntity{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", phone='" + phone + '\'' + ", mail='" + mail + '\'' + ", licencePic='" + licencePic + '\'' + ", registerTime=" + registerTime + ", userTypeEnum=" + userTypeEnum + ", userStateEnum=" + userStateEnum + ", roleEntity=" + roleEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\UserEntity.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (getSelectedRowIds().isMoreThanOneDocumentId()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final I_DD_OrderLine ddOrderLine = ddOrderService.getLineById(DDOrderLineId.ofRepoId(getRecord_ID())); final IView husToMove = createHUEditor(ddOrderLine); getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder() .viewId(husToMove.getViewId().getViewId()) .profileId(WINDOW_ID_STRING) .target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private IView createHUEditor(final I_DD_OrderLine orderLine) { final IHUQueryBuilder huQuery = createHUQuery(orderLine);
final CreateViewRequest request = CreateViewRequest.builder(WINDOW_ID, JSONViewDataType.includedView) .addStickyFilters(HUIdsFilterHelper.createFilter(huQuery)) .setParentViewId(getView().getViewId()) .setParentRowId(getSelectedRowIds().getSingleDocumentId()) .build(); return viewsRepo.createView(request); } private IHUQueryBuilder createHUQuery(final I_DD_OrderLine orderLine) { return handlingUnitsDAO .createHUQueryBuilder() .onlyNotLocked() // not already locked (NOTE: those which were enqueued to Transportation Order are locked) .addOnlyInLocatorId(orderLine.getM_Locator_ID()) .addOnlyWithProductId(ProductId.ofRepoId(orderLine.getM_Product_ID())) .setOnlyActiveHUs(true) .addHUStatusToInclude(X_M_HU.HUSTATUS_Active); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\ddorder\process\WEBUI_MoveHUs_HUEditor_Launcher.java
1
请完成以下Java代码
public int getRevisionNext() { return revision + 1; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public boolean isSuspended() { return SuspensionState.SUSPENDED.getStateCode() == suspensionState; } @Override public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } @Override public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } @Override public String getJobConfiguration() { return jobConfiguration; } public void setJobConfiguration(String jobConfiguration) { this.jobConfiguration = jobConfiguration; } @Override public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int state) {
this.suspensionState = state; } public Long getOverridingJobPriority() { return jobPriority; } public void setJobPriority(Long jobPriority) { this.jobPriority = jobPriority; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionEntity.java
1
请完成以下Java代码
private Period parse(String value) { return this.factory.apply(Integer.parseInt(value)); } private String print(Period value) { return intValue(value) + this.suffix; } private boolean isZero(Period value) { return intValue(value) == 0; } private int intValue(Period value) { Assert.state(this.intValue != null, () -> "intValue cannot be extracted from " + name()); return this.intValue.apply(value); }
private static Unit fromChronoUnit(@Nullable ChronoUnit chronoUnit) { if (chronoUnit == null) { return Unit.DAYS; } for (Unit candidate : values()) { if (candidate.chronoUnit == chronoUnit) { return candidate; } } throw new IllegalArgumentException("Unsupported unit " + chronoUnit); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\PeriodStyle.java
1
请在Spring Boot框架中完成以下Java代码
private ImmutableMap<HUQRCodeRepoId, I_M_HU_QRCode> getByIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeId) { return queryBL.createQueryBuilder(I_M_HU_QRCode.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID, huQrCodeId) .create() .stream() .collect(ImmutableMap.toImmutableMap(huQrCode -> HUQRCodeRepoId.ofRepoId(huQrCode.getM_HU_QRCode_ID()), Function.identity())); } @NonNull private Optional<I_M_HU_QRCode> getByUniqueId(final @NonNull HUQRCodeUniqueId uniqueId) { return queryByQRCode(uniqueId) .create() .firstOnlyOptional(I_M_HU_QRCode.class); } private void removeAssignment(@NonNull final I_M_HU_QRCode qrCode, @NonNull final ImmutableSet<HuId> huIdsToRemove) { streamAssignmentForQrAndHuIds(ImmutableSet.of(HUQRCodeRepoId.ofRepoId(qrCode.getM_HU_QRCode_ID())), huIdsToRemove) .forEach(InterfaceWrapperHelper::delete); } @NonNull private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrIds(@NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds) { return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMN_M_HU_QRCode_ID, huQrCodeIds) .create() .stream(); } @NonNull private Stream<I_M_HU_QRCode_Assignment> streamAssignmentForQrAndHuIds( @NonNull final ImmutableSet<HUQRCodeRepoId> huQrCodeIds,
@NonNull final ImmutableSet<HuId> huIds) { return queryBL.createQueryBuilder(I_M_HU_QRCode_Assignment.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_QRCode_ID, huQrCodeIds) .addInArrayFilter(I_M_HU_QRCode_Assignment.COLUMNNAME_M_HU_ID, huIds) .create() .stream(); } private static HUQRCode toHUQRCode(final I_M_HU_QRCode record) { return HUQRCode.fromGlobalQRCodeJsonString(record.getRenderedQRCode()); } public Stream<HUQRCode> streamQRCodesLike(@NonNull final String like) { return queryBL.createQueryBuilder(I_M_HU_QRCode.class) .addOnlyActiveRecordsFilter() .addStringLikeFilter(I_M_HU_QRCode.COLUMNNAME_RenderedQRCode, like, false) .orderBy(I_M_HU_QRCode.COLUMNNAME_M_HU_QRCode_ID) .create() .stream() .map(HUQRCodesRepository::toHUQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesRepository.java
2
请在Spring Boot框架中完成以下Java代码
public SpringRabbitTracing springRabbitTracing(Tracing tracing) { return SpringRabbitTracing.newBuilder(tracing) .remoteServiceName("demo-mq-rabbit") // 远程 RabbitMQ 服务名,可自定义 .build(); } @Bean public BeanPostProcessor rabbitmqBeanPostProcessor(SpringRabbitTracing springRabbitTracing) { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 如果是 RabbitTemplate ,针对 RabbitMQ Producer if (bean instanceof RabbitTemplate) { return springRabbitTracing.decorateRabbitTemplate((RabbitTemplate) bean); } // 如果是 SimpleRabbitListenerContainerFactory ,针对 RabbitMQ Consumer if (bean instanceof SimpleRabbitListenerContainerFactory) { return springRabbitTracing.decorateSimpleRabbitListenerContainerFactory((SimpleRabbitListenerContainerFactory) bean); } return bean; } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-rabbitmq\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class PmsRoleDaoImpl extends PermissionBaseDaoImpl<PmsRole> implements PmsRoleDao { /** * 获取所有角色列表,以供添加操作员时选择. * * @return roleList . */ public List<PmsRole> listAll() { return super.getSessionTemplate().selectList(getStatement("listAll")); } /** * 判断此权限是否关联有角色 * * @param permissionId * @return */ public List<PmsRole> listByPermissionId(Long permissionId) {
return super.getSessionTemplate().selectList(getStatement("listByPermissionId"), permissionId); } /** * 根据角色名或者角色编号查询角色 * * @param roleName * @param roleCode * @return */ public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("roleName", roleName); paramMap.put("roleCode", roleCode); return super.getSessionTemplate().selectOne(getStatement("getByRoleNameOrRoleCode"), paramMap); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsRoleDaoImpl.java
2
请完成以下Java代码
public void setC_DocType_Invoicing_Pool_ID (final int C_DocType_Invoicing_Pool_ID) { if (C_DocType_Invoicing_Pool_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocType_Invoicing_Pool_ID, C_DocType_Invoicing_Pool_ID); } @Override public int getC_DocType_Invoicing_Pool_ID() { return get_ValueAsInt(COLUMNNAME_C_DocType_Invoicing_Pool_ID); } @Override public void setIsOnDistinctICTypes (final boolean IsOnDistinctICTypes) { set_Value (COLUMNNAME_IsOnDistinctICTypes, IsOnDistinctICTypes); } @Override public boolean isOnDistinctICTypes() { return get_ValueAsBoolean(COLUMNNAME_IsOnDistinctICTypes); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @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 setNegative_Amt_C_DocType_ID (final int Negative_Amt_C_DocType_ID) { if (Negative_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Negative_Amt_C_DocType_ID, Negative_Amt_C_DocType_ID); } @Override public int getNegative_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Negative_Amt_C_DocType_ID); } @Override public void setPositive_Amt_C_DocType_ID (final int Positive_Amt_C_DocType_ID) { if (Positive_Amt_C_DocType_ID < 1) set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, null); else set_Value (COLUMNNAME_Positive_Amt_C_DocType_ID, Positive_Amt_C_DocType_ID); } @Override public int getPositive_Amt_C_DocType_ID() { return get_ValueAsInt(COLUMNNAME_Positive_Amt_C_DocType_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocType_Invoicing_Pool.java
1
请完成以下Java代码
private Quote map(String response) { try (final Jsonb jsonb = JsonbBuilder.create()) { final Map qrw = jsonb.fromJson(response, Map.class); return parseResult(qrw); } catch (Exception e) { System.out.println("Error while trying to read response"); return null; } } private static Quote parseResult(Map qrw) { Quote quote = null; if (qrw != null) { final Map quoteSummary = (Map) qrw.get("quoteSummary"); if (quoteSummary != null) { final List<Map> result = (List<Map>) quoteSummary.get("result"); if (result != null) { final Map resultArray = result.get(0); if (resultArray != null) { final Map summaryDetail = (Map) resultArray.get("summaryDetail"); if (summaryDetail != null) { quote = constructQuote(summaryDetail); } } } } } return quote; } private static Quote constructQuote(Map summaryDetail) { final String currency = (String) summaryDetail.get("currency"); final Map ask = (Map) summaryDetail.get("ask"); final Map bid = (Map) summaryDetail.get("bid"); final BigDecimal askPrice = (BigDecimal) ask.get("raw");
final BigDecimal bidPrice = (BigDecimal) bid.get("raw"); if (askPrice != null && bidPrice != null) { return new Quote(currency, askPrice, bidPrice); } return null; } String doGetRequest(String url) { System.out.println(url); Request request = new Request.Builder() .url(url) .build(); Response response; try { response = client.newCall(request).execute(); return response.body().string(); } catch (IOException e) { return null; } } }
repos\tutorials-master\core-java-modules\java-spi\exchange-rate-impl\src\main\java\com\baeldung\rate\impl\YahooQuoteManagerImpl.java
1
请完成以下Java代码
public HuId getPickFromHUId() {return getPickFromHU().getId();} public boolean isPicked() {return pickedTo != null;} public boolean isNotPicked() {return pickedTo == null;} public void assertPicked() { if (!isPicked()) { throw new AdempiereException("PickFrom was not picked: " + this); } } public PickingJobStepPickFrom assertNotPicked() { if (isPicked()) { throw new AdempiereException("PickFrom already picked: " + this);
} return this; } public PickingJobStepPickFrom withPickedEvent(@NonNull final PickingJobStepPickedTo pickedTo) { return withPickedTo(pickedTo); } public PickingJobStepPickFrom withUnPickedEvent(@NonNull PickingJobStepUnpickInfo unpickEvent) { return withPickedTo(pickedTo != null ? pickedTo.removing(unpickEvent.getUnpickedHUs()) : null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFrom.java
1
请完成以下Java代码
public DataInput newInstance(ModelTypeInstanceContext instanceContext) { return new DataInputImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); isCollectionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_COLLECTION) .defaultValue(false) .build(); typeBuilder.build(); } public DataInputImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); }
public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); } public boolean isCollection() { return isCollectionAttribute.getValue(this); } public void setCollection(boolean isCollection) { isCollectionAttribute.setValue(this, isCollection); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataInputImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OverrideDubboConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplicationListener */ final Logger logger = LoggerFactory.getLogger(getClass()); ConfigurableEnvironment environment = event.getEnvironment(); boolean override = environment.getProperty(OVERRIDE_CONFIG_FULL_PROPERTY_NAME, boolean.class, DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); if (override) { SortedMap<String, Object> dubboProperties = filterDubboProperties(environment);
ConfigUtils.getProperties().putAll(dubboProperties); if (logger.isInfoEnabled()) { logger.info("Dubbo Config was overridden by externalized configuration {}", dubboProperties); } } else { if (logger.isInfoEnabled()) { logger.info("Disable override Dubbo Config caused by property {} = {}", OVERRIDE_CONFIG_FULL_PROPERTY_NAME, override); } } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\OverrideDubboConfigApplicationListener.java
2
请完成以下Java代码
public static <T, R, K> Collector<T, ?, R> collectUsingMapAccumulator(@NonNull final Function<T, K> keyMapper, @NonNull final Function<Map<K, T>, R> finisher) { final Supplier<Map<K, T>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, T>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), item); final BinaryOperator<Map<K, T>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R, K, V> Collector<T, ?, R> collectUsingMapAccumulator( @NonNull final Function<T, K> keyMapper, @NonNull final Function<T, V> valueMapper, @NonNull final Function<Map<K, V>, R> finisher) { final Supplier<Map<K, V>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, V>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), valueMapper.apply(item)); final BinaryOperator<Map<K, V>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; };
return Collector.of(supplier, accumulator, combiner, finisher); } public static <R, K, V> Collector<Map.Entry<K, V>, ?, R> collectUsingMapAccumulator(@NonNull final Function<Map<K, V>, R> finisher) { return collectUsingMapAccumulator(Map.Entry::getKey, Map.Entry::getValue, finisher); } public static <T> Collector<T, ?, Optional<ImmutableSet<T>>> toOptionalImmutableSet() { return Collectors.collectingAndThen( ImmutableSet.toImmutableSet(), set -> !set.isEmpty() ? Optional.of(set) : Optional.empty()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GuavaCollectors.java
1
请在Spring Boot框架中完成以下Java代码
class MongoDatabaseFactoryDependentConfiguration { @Bean @ConditionalOnMissingBean(MongoOperations.class) MongoTemplate mongoTemplate(MongoDatabaseFactory factory, MongoConverter converter) { return new MongoTemplate(factory, converter); } @Bean @ConditionalOnMissingBean(GridFsOperations.class) GridFsTemplate gridFsTemplate(DataMongoProperties properties, MongoDatabaseFactory factory, MongoTemplate mongoTemplate) { return new GridFsTemplate(new GridFsMongoDatabaseFactory(factory, properties), mongoTemplate.getConverter(), properties.getGridfs().getBucket()); } /** * {@link MongoDatabaseFactory} decorator to respect {@link Gridfs#getDatabase()} if * set. */ static class GridFsMongoDatabaseFactory implements MongoDatabaseFactory { private final MongoDatabaseFactory mongoDatabaseFactory; private final DataMongoProperties properties; GridFsMongoDatabaseFactory(MongoDatabaseFactory mongoDatabaseFactory, DataMongoProperties properties) { Assert.notNull(mongoDatabaseFactory, "'mongoDatabaseFactory' must not be null"); Assert.notNull(properties, "'properties' must not be null"); this.mongoDatabaseFactory = mongoDatabaseFactory; this.properties = properties; } @Override public MongoDatabase getMongoDatabase() throws DataAccessException { String gridFsDatabase = getGridFsDatabase();
if (StringUtils.hasText(gridFsDatabase)) { return this.mongoDatabaseFactory.getMongoDatabase(gridFsDatabase); } return this.mongoDatabaseFactory.getMongoDatabase(); } @Override public MongoDatabase getMongoDatabase(String dbName) throws DataAccessException { return this.mongoDatabaseFactory.getMongoDatabase(dbName); } @Override public PersistenceExceptionTranslator getExceptionTranslator() { return this.mongoDatabaseFactory.getExceptionTranslator(); } @Override public ClientSession getSession(ClientSessionOptions options) { return this.mongoDatabaseFactory.getSession(options); } @Override public MongoDatabaseFactory withSession(ClientSession session) { return this.mongoDatabaseFactory.withSession(session); } private @Nullable String getGridFsDatabase() { return this.properties.getGridfs().getDatabase(); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\MongoDatabaseFactoryDependentConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers("/app/**/*.{js,html}") .antMatchers("/i18n/**") .antMatchers("/content/**") .antMatchers("/h2-console/**") .antMatchers("/swagger-ui/index.html") .antMatchers("/test/**"); } @Override public void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) .exceptionHandling() .authenticationEntryPoint(problemSupport) .accessDeniedHandler(problemSupport) .and() .headers() .frameOptions() .disable() .and() .sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/books/purchase/**").authenticated() .antMatchers("/api/register").permitAll() .antMatchers("/api/activate").permitAll() .antMatchers("/api/authenticate").permitAll() .antMatchers("/api/account/reset-password/init").permitAll() .antMatchers("/api/account/reset-password/finish").permitAll() .antMatchers("/api/**").authenticated() .antMatchers("/management/health").permitAll() .antMatchers("/management/info").permitAll() .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) .and() .apply(securityConfigurerAdapter()); } private JWTConfigurer securityConfigurerAdapter() { return new JWTConfigurer(tokenProvider); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\SecurityConfiguration.java
2
请完成以下Java代码
public class MigratingProcessInstanceValidationReportImpl implements MigratingProcessInstanceValidationReport { protected String processInstanceId; protected List<MigratingActivityInstanceValidationReport> activityInstanceReports = new ArrayList<MigratingActivityInstanceValidationReport>(); protected List<MigratingTransitionInstanceValidationReport> transitionInstanceReports = new ArrayList<MigratingTransitionInstanceValidationReport>(); protected List<String> failures = new ArrayList<String>(); public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public void addActivityInstanceReport(MigratingActivityInstanceValidationReport instanceReport) { activityInstanceReports.add(instanceReport); } public void addTransitionInstanceReport(MigratingTransitionInstanceValidationReport instanceReport) { transitionInstanceReports.add(instanceReport); } public List<MigratingActivityInstanceValidationReport> getActivityInstanceReports() { return activityInstanceReports; } @Override public List<MigratingTransitionInstanceValidationReport> getTransitionInstanceReports() { return transitionInstanceReports; } public void addFailure(String failure) { failures.add(failure); } public List<String> getFailures() { return failures; }
public boolean hasFailures() { return !failures.isEmpty() || !activityInstanceReports.isEmpty() || !transitionInstanceReports.isEmpty(); } public void writeTo(StringBuilder sb) { sb.append("Cannot migrate process instance '") .append(processInstanceId) .append("':\n"); for (String failure : failures) { sb.append("\t").append(failure).append("\n"); } for (MigratingActivityInstanceValidationReport report : activityInstanceReports) { sb.append("\tCannot migrate activity instance '") .append(report.getActivityInstanceId()) .append("':\n"); for (String failure : report.getFailures()) { sb.append("\t\t").append(failure).append("\n"); } } for (MigratingTransitionInstanceValidationReport report : transitionInstanceReports) { sb.append("\tCannot migrate transition instance '") .append(report.getTransitionInstanceId()) .append("':\n"); for (String failure : report.getFailures()) { sb.append("\t\t").append(failure).append("\n"); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingProcessInstanceValidationReportImpl.java
1
请完成以下Java代码
private static boolean hasMultipleAvailabilityRowsPerLineRow( @NonNull final Multimap<PurchaseRow, PurchaseRow> lineRows2availabilityRows) { return lineRows2availabilityRows .asMap() .entrySet() .stream() .anyMatch(lineRow2availabilityRows -> lineRow2availabilityRows.getValue().size() > 1); } public void updateLineAndGroupRow(@NonNull final PurchaseRow lineRow, @NonNull final PurchaseRow availabilityRow) { final PurchaseRowId lineRowId = lineRow.getRowId(); final PurchaseRowChangeRequest lineChangeRequest = createPurchaseRowChangeRequest(availabilityRow); patchViewRow(lineRowId, lineChangeRequest); } private Multimap<PurchaseRow, PurchaseRow> extractLineRow2availabilityRows() { final PurchaseView view = getView(); final ListMultimap<PurchaseRow, PurchaseRow> lineRow2AvailabilityRows = getSelectedRowIds().stream() .map(PurchaseRowId::fromDocumentId) // map to PurchaseRowIds .filter(PurchaseRowId::isAvailabilityRowId) .filter(availabilityRowId -> availabilityRowId.getAvailabilityType().equals(Type.AVAILABLE)) .map(availabilityRowId -> ImmutablePair.of( // map to pair (availabilityRowId, availabilityRow) availabilityRowId, view.getById(availabilityRowId.toDocumentId()))) .filter(availabilityRowId2row -> isPositive(availabilityRowId2row.getRight().getQtyToPurchase())) .map(availabilityRowId2row -> ImmutablePair.of( // map to pair (lineRow, availabilityRow) view.getById(availabilityRowId2row.getLeft().toLineRowId().toDocumentId()), availabilityRowId2row.getRight())) .filter(lineRow2availabilityRow -> !lineRow2availabilityRow.getLeft().isProcessed()) .collect(Multimaps.toMultimap( IPair::getLeft,
IPair::getRight, MultimapBuilder.hashKeys().arrayListValues()::build)); return ImmutableMultimap.copyOf(lineRow2AvailabilityRows); } private static final boolean isPositive(final Quantity qty) { return qty != null && qty.signum() > 0; } private static PurchaseRowChangeRequest createPurchaseRowChangeRequest(final PurchaseRow availabilityRow) { final PurchaseRowChangeRequestBuilder requestBuilder = PurchaseRowChangeRequest.builder(); if (availabilityRow.getDatePromised() != null) { requestBuilder.purchaseDatePromised(availabilityRow.getDatePromised()); } requestBuilder.qtyToPurchase(availabilityRow.getQtyToPurchase()); return requestBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\process\WEBUI_SalesOrder_Apply_Availability_Row.java
1
请完成以下Java代码
public String getReversalPropagationType() { return getPropagationType(); // same } /** * Gets the the attribute specified within the given <code>propagationContext</code> and calls {@link #setStorageValue(IAttributeStorage, I_M_Attribute, Object)} with that attribute, the given * <code>attributeSet</code> and the given <code>value</code>. Does no propagation (neither up nor down). * */ @Override public void propagateValue(final IHUAttributePropagationContext propagationContext, final IAttributeStorage attributeSet, final Object value) { // // Just set the value and nothing more final I_M_Attribute attribute = propagationContext.getAttribute();
if (propagationContext.isUpdateStorageValue() && attributeSet.hasAttribute(attribute)) { setStorageValue(propagationContext, attributeSet, attribute, value); } } @Override public String toString() { return "NoPropagationHUAttributePropagator []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\propagation\impl\NoPropagationHUAttributePropagator.java
1
请完成以下Java代码
public java.lang.String getFirstname() { return get_ValueAsString(COLUMNNAME_Firstname); } @Override public void setIsDefaultContact (final boolean IsDefaultContact) { set_Value (COLUMNNAME_IsDefaultContact, IsDefaultContact); } @Override public boolean isDefaultContact() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultContact); } /** * IsInvoiceEmailEnabled AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISINVOICEEMAILENABLED_AD_Reference_ID=319; /** Yes = Y */ public static final String ISINVOICEEMAILENABLED_Yes = "Y"; /** No = N */ public static final String ISINVOICEEMAILENABLED_No = "N"; @Override public void setIsInvoiceEmailEnabled (final @Nullable java.lang.String IsInvoiceEmailEnabled) { set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled); } @Override public java.lang.String getIsInvoiceEmailEnabled() { return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled); } @Override public void setIsMembershipContact (final boolean IsMembershipContact) { set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact); } @Override public boolean isMembershipContact() { return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact); } @Override public void setIsNewsletter (final boolean IsNewsletter) { set_Value (COLUMNNAME_IsNewsletter, IsNewsletter); } @Override public boolean isNewsletter() { return get_ValueAsBoolean(COLUMNNAME_IsNewsletter); } @Override public void setLastname (final @Nullable java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return get_ValueAsString(COLUMNNAME_Lastname); }
@Override public void setPhone (final @Nullable java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } @Override public java.lang.String getPhone() { return get_ValueAsString(COLUMNNAME_Phone); } @Override public void setPhone2 (final @Nullable java.lang.String Phone2) { set_Value (COLUMNNAME_Phone2, Phone2); } @Override public java.lang.String getPhone2() { return get_ValueAsString(COLUMNNAME_Phone2); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java
1
请完成以下Java代码
protected LoginResponse sendLoginRequest(final LoginRequest loginRequest) throws LoginFailedPrintConnectionEndpointException { final byte[] data = beanEncoder.encode(loginRequest); final Map<String, String> params = new HashMap<>(); params.put(Context.CTX_SessionId, "0"); // no session final URL url = getURL(PRTRestServiceConstants.PATH_Login, params); final PostMethod httpPost = new PostMethod(url.toString()); addApiTokenIfAvailable(httpPost); final RequestEntity entity = new ByteArrayRequestEntity(data, beanEncoder.getContentType()); httpPost.setRequestEntity(entity); int result = -1; InputStream in = null; try { result = executeHttpPost(httpPost); in = httpPost.getResponseBodyAsStream(); if (result != 200) { final String errorMsg = in == null ? "code " + result : Util.toString(in); throw new PrintConnectionEndpointException("Error " + result + " while posting on " + url + ": " + errorMsg); } final LoginResponse loginResponse = beanEncoder.decodeStream(in, LoginResponse.class); return loginResponse; } catch (final Exception e) { log.info("Exception " + e); throw e instanceof LoginFailedPrintConnectionEndpointException ? (LoginFailedPrintConnectionEndpointException)e : new LoginFailedPrintConnectionEndpointException("Cannot POST to " + url, e);
} finally { Util.close(in); in = null; } } private void addApiTokenIfAvailable(final PostMethod httpPost) { final String apiToken = getContext().getProperty(Context.CTX_Login_ApiToken); if (apiToken != null && apiToken.trim().length() > 0) { httpPost.setRequestHeader("Authorization", apiToken.trim()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\RestHttpPrintConnectionEndpoint.java
1
请完成以下Java代码
public static BigDecimal calculatePriceEnteredFromPriceActualAndDiscount( @NonNull final BigDecimal priceActual, @NonNull final BigDecimal discount, final int precision) { final BigDecimal multiplier = Env.ONEHUNDRED .add(discount) .divide(Env.ONEHUNDRED, 12, RoundingMode.HALF_UP); return priceActual .multiply(multiplier) .setScale(precision, RoundingMode.HALF_UP); } public void applyTo(final I_C_OrderLine orderLine) { logger.debug("Applying {} to {}", this, orderLine); orderLine.setPriceEntered(priceEntered); orderLine.setDiscount(discount.toBigDecimal()); orderLine.setPriceActual(priceActual); orderLine.setPriceLimit(priceLimit); orderLine.setPriceLimitNote(buildPriceLimitNote()); } private String buildPriceLimitNote() { final ITranslatableString msg; if (priceLimitEnforced) { msg = TranslatableStrings.builder()
.appendADMessage(AdMessageKey.of("Enforced")) .append(": ") .append(priceLimitEnforcedExplanation) .build(); } else { msg = TranslatableStrings.builder() .appendADMessage(AdMessageKey.of("NotEnforced")) .append(": ") .append(priceLimitNotEnforcedExplanation) .build(); } final String adLanguage = Language.getBaseAD_Language(); return msg.translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLinePriceAndDiscount.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { set_Value (COLUMNNAME_ProductName, ProductName); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setProductValue (final @Nullable java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities.java
1
请完成以下Java代码
public void output(OutputStream out) { if (doctype != null) { doctype.output(out); try { out.write('\n'); } catch ( Exception e) {} } // XhtmlDocument is just a convient wrapper for html call html.output html.output(out); } /** Write the container to the PrinteWriter */ public void output(PrintWriter out) { if (doctype != null) { doctype.output(out); try { out.write('\n'); } catch ( Exception e) {} } // XhtmlDocument is just a convient wrapper for html call html.output html.output(out); } /** Override the toString() method so that it prints something meaningful. */ public final String toString() { StringBuffer sb = new StringBuffer();
if ( getCodeset() != null ) { if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return (sb.toString()); } else { if (doctype != null) sb.append (doctype.toString()); sb.append (html.toString()); return(sb.toString()); } } /** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { StringBuffer sb = new StringBuffer(); if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return(sb.toString()); } /** Allows the document to be cloned. Doesn't return an instance of document returns instance of html. NOTE: If you have a doctype set, then it will be lost. Feel free to submit a patch to fix this. It isn't trivial. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlDocument.java
1
请完成以下Java代码
private class InfoProductDetailTab { private final IInfoProductDetail detail; private final Component component; private final String titleTrl; private Object refreshKeyLast; public InfoProductDetailTab(String title, final IInfoProductDetail detail, final Component component) { super(); this.titleTrl = Services.get(IMsgBL.class).translate(Env.getCtx(), title); this.detail = detail; if(component instanceof JTable) { // Wrap the JTable in a scroll pane, else the table header won't be visible // see http://stackoverflow.com/questions/2320812/jtable-wont-show-column-headers this.component = new CScrollPane(component); } else { this.component = component; } } public String getTitleTrl() { return titleTrl; } public Component getComponent() { return component; } /** * Refresh (always) */ public void refresh() { final int M_Product_ID = getM_Product_ID(); final int M_Warehouse_ID = getM_Warehouse_ID(); final int M_PriceList_Version_ID = getM_PriceList_Version_ID(); final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID(); final boolean onlyIfStale = false; refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); } /** * Refresh only if stale */ private void refreshIfStale() { final int M_Product_ID = getM_Product_ID();
final int M_Warehouse_ID = getM_Warehouse_ID(); final int M_PriceList_Version_ID = getM_PriceList_Version_ID(); final int M_AttributeSetInstance_ID = getM_AttributeSetInstance_ID(); final boolean onlyIfStale = true; refresh(onlyIfStale, M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); } private void refresh(boolean onlyIfStale, int M_Product_ID, int M_Warehouse_ID, int M_AttributeSetInstance_ID, int M_PriceList_Version_ID) { final ArrayKey refreshKey = Util.mkKey(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); if (!onlyIfStale || !isStale(refreshKey)) { detail.refresh(M_Product_ID, M_Warehouse_ID, M_AttributeSetInstance_ID, M_PriceList_Version_ID); } this.refreshKeyLast = refreshKey; } private boolean isStale(final ArrayKey refreshKey) { return !Check.equals(refreshKey, refreshKeyLast); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductDetails.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set 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); }
/** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType.java
1
请完成以下Java代码
public class ESR_Complete_Process extends JavaProcess { private final IESRImportBL esrImportBL = Services.get(IESRImportBL.class); ESRImportId esrImportId ; @Override protected void prepare() { if (I_ESR_Import.Table_Name.equals(getTableName())) { esrImportId = ESRImportId.ofRepoId(getRecord_ID()); } } @Override @RunOutOfTrx protected String doIt() throws Exception { final I_ESR_Import esrImport = esrImportBL.getById(esrImportId); Check.errorUnless(esrImport.isValid(), "The document can not be processed, since it is not valid."); final String description = getProcessInfo().getTitle() + " #" + getPinstanceId().getRepoId(); esrImportBL.complete(esrImport, description); return ""; } @Override protected void postProcess(final boolean success)
{ if (success) { final I_ESR_Import esrImport = esrImportBL.getById(esrImportId); final boolean processed = Services.get(IESRImportBL.class).isProcessed(esrImport); if (processed) { getResult().addSummary(Services.get(IMsgBL.class).parseTranslation(getCtx(), "@ESR_Complete_Process_postProcess@")); } else { getResult().addSummary(Services.get(IMsgBL.class).parseTranslation(getCtx(), "@" + ESRConstants.ERR_ESR_LINE_WITH_NO_PAYMENT_ACTION + "@")); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\ESR_Complete_Process.java
1
请完成以下Java代码
public List<CmmnSentryDeclaration> getEntryCriteria() { return entryCriteria; } public void setEntryCriteria(List<CmmnSentryDeclaration> entryCriteria) { this.entryCriteria = entryCriteria; } public void addEntryCriteria(CmmnSentryDeclaration entryCriteria) { this.entryCriteria.add(entryCriteria); } // exitCriteria public List<CmmnSentryDeclaration> getExitCriteria() { return exitCriteria; } public void setExitCriteria(List<CmmnSentryDeclaration> exitCriteria) { this.exitCriteria = exitCriteria; } public void addExitCriteria(CmmnSentryDeclaration exitCriteria) { this.exitCriteria.add(exitCriteria); } // variable listeners /** * Returns a map of all variable listeners defined on this activity or any of * its parents activities. The map's key is the id of the respective activity * the listener is defined on. */ public Map<String, List<VariableListener<?>>> getVariableListeners(String eventName, boolean includeCustomListeners) { Map<String, Map<String, List<VariableListener<?>>>> listenerCache; if (includeCustomListeners) { if (resolvedVariableListeners == null) { resolvedVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>();
} listenerCache = resolvedVariableListeners; } else { if (resolvedBuiltInVariableListeners == null) { resolvedBuiltInVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>(); } listenerCache = resolvedBuiltInVariableListeners; } Map<String, List<VariableListener<?>>> resolvedListenersForEvent = listenerCache.get(eventName); if (resolvedListenersForEvent == null) { resolvedListenersForEvent = new HashMap<String, List<VariableListener<?>>>(); listenerCache.put(eventName, resolvedListenersForEvent); CmmnActivity currentActivity = this; while (currentActivity != null) { List<VariableListener<?>> localListeners = null; if (includeCustomListeners) { localListeners = currentActivity.getVariableListenersLocal(eventName); } else { localListeners = currentActivity.getBuiltInVariableListenersLocal(eventName); } if (localListeners != null && !localListeners.isEmpty()) { resolvedListenersForEvent.put(currentActivity.getId(), localListeners); } currentActivity = currentActivity.getParent(); } } return resolvedListenersForEvent; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnActivity.java
1
请完成以下Java代码
public int getPA_DashboardContent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Goal getPA_Goal() throws RuntimeException { return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1) set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */ public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set ZUL File Path. @param ZulFilePath Absolute path to zul file */ public void setZulFilePath (String ZulFilePath) { set_Value (COLUMNNAME_ZulFilePath, ZulFilePath); } /** Get ZUL File Path. @return Absolute path to zul file */ public String getZulFilePath () { return (String)get_Value(COLUMNNAME_ZulFilePath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java
1
请完成以下Java代码
public ExecutionEntity createAttachableExecution() { ExecutionEntity scopeExecution = resolveRepresentativeExecution(); ExecutionEntity attachableExecution = scopeExecution; if (currentScope.getActivityBehavior() instanceof ModificationObserverBehavior) { ModificationObserverBehavior behavior = (ModificationObserverBehavior) currentScope.getActivityBehavior(); attachableExecution = (ExecutionEntity) behavior.createInnerInstance(scopeExecution); } else { if (!scopeExecution.getNonEventScopeExecutions().isEmpty() || scopeExecution.getActivity() != null) { attachableExecution = (ExecutionEntity) scopeExecution.createConcurrentExecution(); attachableExecution.setActive(false); scopeExecution.forceUpdate(); } } return attachableExecution; } @Override public void destroyAttachableExecution(ExecutionEntity execution) {
if (currentScope.getActivityBehavior() instanceof ModificationObserverBehavior) { ModificationObserverBehavior behavior = (ModificationObserverBehavior) currentScope.getActivityBehavior(); behavior.destroyInnerInstance(execution); } else { if (execution.isConcurrent()) { execution.remove(); execution.getParent().tryPruneLastConcurrentChild(); execution.getParent().forceUpdate(); } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingActivityInstance.java
1
请完成以下Java代码
public class GetClassNamesFromJar { public static Set<String> getClassNamesFromJarFile(File givenFile) throws IOException { Set<String> classNames = new HashSet<>(); try (JarFile jarFile = new JarFile(givenFile)) { Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry jarEntry = e.nextElement(); if (jarEntry.getName().endsWith(".class")) { String className = jarEntry.getName() .replace("/", ".") .replace(".class", ""); classNames.add(className); } } return classNames;
} } public static Set<Class> getClassesFromJarFile(File jarFile) throws IOException, ClassNotFoundException { Set<String> classNames = getClassNamesFromJarFile(jarFile); Set<Class> classes = new HashSet<>(classNames.size()); try (URLClassLoader cl = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarFile + "!/") })) { for (String name : classNames) { Class clazz = cl.loadClass(name); // Loading the class by its name classes.add(clazz); } } return classes; } }
repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\jar\GetClassNamesFromJar.java
1
请完成以下Java代码
public class StartEvent extends Event { protected String initiator; protected String formKey; protected boolean isInterrupting; protected List<FormProperty> formProperties = new ArrayList<FormProperty>(); public String getInitiator() { return initiator; } public void setInitiator(String initiator) { this.initiator = initiator; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public boolean isInterrupting() { return isInterrupting; } public void setInterrupting(boolean isInterrupting) { this.isInterrupting = isInterrupting; } public List<FormProperty> getFormProperties() { return formProperties; } public void setFormProperties(List<FormProperty> formProperties) { this.formProperties = formProperties; } public StartEvent clone() { StartEvent clone = new StartEvent(); clone.setValues(this);
return clone; } public void setValues(StartEvent otherEvent) { super.setValues(otherEvent); setInitiator(otherEvent.getInitiator()); setFormKey(otherEvent.getFormKey()); setInterrupting(otherEvent.isInterrupting); formProperties = new ArrayList<FormProperty>(); if (otherEvent.getFormProperties() != null && !otherEvent.getFormProperties().isEmpty()) { for (FormProperty property : otherEvent.getFormProperties()) { formProperties.add(property.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\StartEvent.java
1
请完成以下Java代码
public void migrateHistoricCaseInstancesOfCaseDefinition(String caseDefinitionId, HistoricCaseInstanceMigrationDocument historicCaseInstanceMigrationDocument) { commandExecutor.execute(new HistoricCaseInstanceMigrationCmd(historicCaseInstanceMigrationDocument, caseDefinitionId, configuration)); } @Override public void migrateCaseInstancesOfCaseDefinition(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId, CaseInstanceMigrationDocument caseInstanceMigrationDocument) { commandExecutor.execute(new CaseInstanceMigrationCmd(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, caseInstanceMigrationDocument, configuration)); } @Override public void migrateHistoricCaseInstancesOfCaseDefinition(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId, HistoricCaseInstanceMigrationDocument historicCaseInstanceMigrationDocument) { commandExecutor.execute(new HistoricCaseInstanceMigrationCmd(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, historicCaseInstanceMigrationDocument, configuration)); } @Override public Batch batchMigrateCaseInstancesOfCaseDefinition(String caseDefinitionId, CaseInstanceMigrationDocument caseInstanceMigrationDocument) { return commandExecutor.execute(new CaseInstanceMigrationBatchCmd(caseInstanceMigrationDocument, caseDefinitionId, configuration)); } @Override public Batch batchMigrateHistoricCaseInstancesOfCaseDefinition(String caseDefinitionId, HistoricCaseInstanceMigrationDocument historicCaseInstanceMigrationDocument) {
return commandExecutor.execute(new HistoricCaseInstanceMigrationBatchCmd(historicCaseInstanceMigrationDocument, caseDefinitionId, configuration)); } @Override public Batch batchMigrateCaseInstancesOfCaseDefinition(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId, CaseInstanceMigrationDocument caseInstanceMigrationDocument) { return commandExecutor.execute(new CaseInstanceMigrationBatchCmd(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, caseInstanceMigrationDocument, configuration)); } @Override public Batch batchMigrateHistoricCaseInstancesOfCaseDefinition(String caseDefinitionKey, int caseDefinitionVersion, String caseDefinitionTenantId, HistoricCaseInstanceMigrationDocument historicCaseInstanceMigrationDocument) { return commandExecutor.execute(new HistoricCaseInstanceMigrationBatchCmd(caseDefinitionKey, caseDefinitionVersion, caseDefinitionTenantId, historicCaseInstanceMigrationDocument, configuration)); } @Override public CaseInstanceBatchMigrationResult getResultsOfBatchCaseInstanceMigration(String migrationBatchId) { return commandExecutor.execute(new GetCaseInstanceMigrationBatchResultCmd(migrationBatchId)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CmmnMigrationServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderLine { @Nullable OrderLineId id; @NonNull OrderId orderId; @NonNull BPartnerId bPartnerId; @NonNull ProductId productId; @NonNull AttributeSetInstanceId asiId; @NonNull ProductPrice priceActual; @NonNull Quantity orderedQty;
@NonNull WarehouseId warehouseId; int line; @NonNull PaymentTermId paymentTermId; // Note: i think that the following two should go to "Order" once we have it. @NonNull OrgId orgId; /** note: besides the name "datePromised", it's also in the application dictionary declared as date+time, and some businesses need it that way. */ @NonNull ZonedDateTime datePromised; @NonNull SOTrx soTrx; @Nullable HUPIItemProductId huPIItemProductId; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLine.java
2
请完成以下Java代码
public abstract class AbstractKafkaBackOffManagerFactory implements KafkaBackOffManagerFactory, ApplicationContextAware { private @Nullable ApplicationContext applicationContext; private @Nullable ListenerContainerRegistry listenerContainerRegistry; /** * Creates an instance that will retrieve the {@link ListenerContainerRegistry} from * the {@link ApplicationContext}. */ public AbstractKafkaBackOffManagerFactory() { this.listenerContainerRegistry = null; } /** * Creates an instance with the provided {@link ListenerContainerRegistry}, * which will be used to fetch the {@link MessageListenerContainer} to back off. * @param listenerContainerRegistry the listenerContainerRegistry to use. */ public AbstractKafkaBackOffManagerFactory(@Nullable ListenerContainerRegistry listenerContainerRegistry) { this.listenerContainerRegistry = listenerContainerRegistry; } /** * Sets the {@link ListenerContainerRegistry}, that will be used to fetch the * {@link MessageListenerContainer} to back off. * * @param listenerContainerRegistry the listenerContainerRegistry to use. */ public void setListenerContainerRegistry(ListenerContainerRegistry listenerContainerRegistry) { this.listenerContainerRegistry = listenerContainerRegistry; } @Override public KafkaConsumerBackoffManager create() { return doCreateManager(getListenerContainerRegistry()); } protected abstract KafkaConsumerBackoffManager doCreateManager(ListenerContainerRegistry registry); protected ListenerContainerRegistry getListenerContainerRegistry() { return this.listenerContainerRegistry != null
? this.listenerContainerRegistry : getListenerContainerFromContext(); } private ListenerContainerRegistry getListenerContainerFromContext() { Assert.notNull(this.applicationContext, "ApplicationContext not set."); return this.applicationContext.getBean(KafkaListenerConfigUtils.KAFKA_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME, ListenerContainerRegistry.class); } protected <T> T getBean(String beanName, Class<T> beanClass) { return Objects.requireNonNull(this.applicationContext).getBean(beanName, beanClass); } @Override public final void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\AbstractKafkaBackOffManagerFactory.java
1
请完成以下Java代码
public boolean isVisible() { return visible; } public void setVisible(boolean visible) { if (this.visible == visible) { return; } final boolean visibleOld = this.visible; this.visible = visible; pcs.firePropertyChange(PROPERTY_Visible, visibleOld, visible); } @Override public Method getReadMethod() { return readMethod; } @Override public Method getWriteMethod() { return writeMethod; } void setWriteMethod(final Method writeMethod) { this.writeMethod = writeMethod; } void setSeqNo(final int seqNo) { this.seqNo = seqNo; } @Override public int getSeqNo() { return seqNo; } @Override public String getLookupTableName() { return lookupTableName; } void setLookupTableName(final String lookupTableName) { this.lookupTableName = lookupTableName; } @Override public String getLookupColumnName() { return lookupColumnName; } void setLookupColumnName(final String lookupColumnName) { this.lookupColumnName = lookupColumnName; } @Override public String getPrototypeValue() {
return prototypeValue; } void setPrototypeValue(final String prototypeValue) { this.prototypeValue = prototypeValue; } public int getDisplayType(final int defaultDisplayType) { return displayType > 0 ? displayType : defaultDisplayType; } public int getDisplayType() { return displayType; } void setDisplayType(int displayType) { this.displayType = displayType; } public boolean isSelectionColumn() { return selectionColumn; } public void setSelectionColumn(boolean selectionColumn) { this.selectionColumn = selectionColumn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java
1
请完成以下Java代码
public void setC_UOM_To_ID (int C_UOM_To_ID) { if (C_UOM_To_ID < 1) set_Value (COLUMNNAME_C_UOM_To_ID, null); else set_Value (COLUMNNAME_C_UOM_To_ID, Integer.valueOf(C_UOM_To_ID)); } /** Get Ziel-Maßeinheit. @return Maßeinheit, in die eine bestimmte Menge konvertiert werden soll */ @Override public int getC_UOM_To_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_To_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Divisor. @param DivideRate Der Divisor ist der Kehrwert des Umrechnungsfaktors. */ @Override public void setDivideRate (java.math.BigDecimal DivideRate) { set_Value (COLUMNNAME_DivideRate, DivideRate); } /** Get Divisor. @return Der Divisor ist der Kehrwert des Umrechnungsfaktors. */ @Override public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ziel ist Catch-Maßeinheit. @param IsCatchUOMForProduct Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public void setIsCatchUOMForProduct (boolean IsCatchUOMForProduct) { set_Value (COLUMNNAME_IsCatchUOMForProduct, Boolean.valueOf(IsCatchUOMForProduct)); } /** Get Ziel ist Catch-Maßeinheit. @return Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public boolean isCatchUOMForProduct () { Object oo = get_Value(COLUMNNAME_IsCatchUOMForProduct); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UOM_Conversion.java
1
请完成以下Spring Boot application配置
server.port=8082 spring.security.oauth2.client.registration.github.client-id=368238083842-3d4gc7p54rs6bponn0qhn4nmf6apf24a.apps.googleusercontent.com spring.security.oauth2.client.registration.github.client-secret=2RM2QkEaf3A8-iCNqSfdG8wP spring.security.oauth2.client.registration.github.scope=read:user,user:email spring.security.oauth2.client.provider.github.token-uri=https://github.com/login/oauth/access_token spring.se
curity.oauth2.client.provider.github.authorization-uri=https://github.com/login/oauth/authorize spring.security.oauth2.client.provider.github.user-info-uri=https://api.github.com/user
repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\resources\application-oauth2-extractors-github.properties
2
请完成以下Java代码
public FirebaseSignInResponse login(String emailId, String password) { FirebaseSignInRequest requestBody = new FirebaseSignInRequest(emailId, password, true); return sendSignInRequest(requestBody); } public RefreshTokenResponse exchangeRefreshToken(String refreshToken) { RefreshTokenRequest requestBody = new RefreshTokenRequest(REFRESH_TOKEN_GRANT_TYPE, refreshToken); return sendRefreshTokenRequest(requestBody); } private FirebaseSignInResponse sendSignInRequest(FirebaseSignInRequest firebaseSignInRequest) { try { return RestClient.create(SIGN_IN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(firebaseSignInRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(FirebaseSignInResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_CREDENTIALS_ERROR)) { throw new InvalidLoginCredentialsException("Invalid login credentials provided"); } throw exception; } } private RefreshTokenResponse sendRefreshTokenRequest(RefreshTokenRequest refreshTokenRequest) { try { return RestClient.create(REFRESH_TOKEN_BASE_URL) .post() .uri(uriBuilder -> uriBuilder .queryParam(API_KEY_PARAM, webApiKey) .build()) .body(refreshTokenRequest) .contentType(MediaType.APPLICATION_JSON) .retrieve() .body(RefreshTokenResponse.class); } catch (HttpClientErrorException exception) { if (exception.getResponseBodyAsString().contains(INVALID_REFRESH_TOKEN_ERROR)) {
throw new InvalidRefreshTokenException("Invalid refresh token provided"); } throw exception; } } record FirebaseSignInRequest(String email, String password, boolean returnSecureToken) { } record FirebaseSignInResponse(String idToken, String refreshToken) { } record RefreshTokenRequest(String grant_type, String refresh_token) { } record RefreshTokenResponse(String id_token) { } }
repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\auth\FirebaseAuthClient.java
1
请在Spring Boot框架中完成以下Java代码
public void setPaymentDueDate(ExtendedDateType value) { this.paymentDueDate = 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;sequence&gt; * &lt;element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}AdditionalReference" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "additionalReference" }) public static class RelatedReferences { @XmlElement(name = "AdditionalReference") protected List<ReferenceType> additionalReference; /** * Other references if no dedicated field is available.Gets the value of the additionalReference 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 additionalReference property. *
* <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } } }
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\REMADVListLineItemExtensionType.java
2
请完成以下Java代码
public void setDocBaseType (java.lang.String DocBaseType) { set_Value (COLUMNNAME_DocBaseType, DocBaseType); } /** Get Document BaseType. @return Logical type of document */ @Override public java.lang.String getDocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_DocBaseType); } /** Set Standard. @param IsDefault Default value */ @Override public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Standard. @return Default value */ @Override public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo);
} return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocLine_Sort.java
1
请在Spring Boot框架中完成以下Java代码
private C_AllocationHdr_Builder newC_AllocationHdr_Builder(final AllocationLineCandidate candidate) { return allocationBL.newBuilder() .orgId(candidate.getOrgId()) .currencyId(candidate.getCurrencyId()) .dateTrx(candidate.getDateTrx()) .dateAcct(candidate.getDateAcct()) .manual(true); // flag it as manually created by user } @Nullable private PaymentAllocationId createAndComplete(final C_AllocationHdr_Builder allocationBuilder) { final I_C_AllocationHdr allocationHdr = allocationBuilder.createAndComplete(); if (allocationHdr == null) { return null; } // final ImmutableList<I_C_AllocationLine> lines = allocationBuilder.getC_AllocationLines(); updateCounter_AllocationLine_ID(lines); return PaymentAllocationId.ofRepoId(allocationHdr.getC_AllocationHdr_ID()); } /** * Sets the counter allocation line - that means the mathcing line * The id is set only if we have 2 line: credit memo - invoice; purchase invoice - sales invoice; incoming payment - outgoing payment * * @param lines */ private void updateCounter_AllocationLine_ID(final ImmutableList<I_C_AllocationLine> lines) { if (lines.size() != 2)
{ return; } // final I_C_AllocationLine al1 = lines.get(0); final I_C_AllocationLine al2 = lines.get(1); al1.setCounter_AllocationLine_ID(al2.getC_AllocationLine_ID()); allocationDAO.save(al1); // al2.setCounter_AllocationLine_ID(al1.getC_AllocationLine_ID()); allocationDAO.save(al2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationLineCandidateSaver.java
2
请完成以下Java代码
public Long getId() { return this.id; } public String getUsername() { return this.username; } public String getEmail() { return this.email; } public Profile getProfile() { return this.profile; } public List<Post> getPosts() { return this.posts; } public List<Group> getGroups() { return this.groups; } public void setId(Long id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setEmail(String email) { this.email = email; } public void setProfile(Profile profile) { this.profile = profile; } public void setPosts(List<Post> posts) { this.posts = posts;
} public void setGroups(List<Group> groups) { this.groups = groups; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(id, user.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", profile=" + this.getProfile() + ", posts=" + this.getPosts() + ", groups=" + this.getGroups() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\User.java
1
请完成以下Java代码
public class TbLogNode implements TbNode { private ScriptEngine scriptEngine; private boolean standard; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { var config = TbNodeUtils.convert(configuration, TbLogNodeConfiguration.class); standard = isStandard(config); scriptEngine = standard ? null : createScriptEngine(ctx, config); } ScriptEngine createScriptEngine(TbContext ctx, TbLogNodeConfiguration config) { return ctx.createScriptEngine(config.getScriptLang(), ScriptLanguage.TBEL.equals(config.getScriptLang()) ? config.getTbelScript() : config.getJsScript()); } @Override public void onMsg(TbContext ctx, TbMsg msg) { if (!log.isInfoEnabled()) { ctx.tellSuccess(msg); return; } if (standard) { logStandard(ctx, msg); return; } Futures.addCallback(scriptEngine.executeToStringAsync(msg), new FutureCallback<>() { @Override public void onSuccess(@Nullable String result) { log.info(result); ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }, MoreExecutors.directExecutor()); //usually js responses runs on js callback executor } boolean isStandard(TbLogNodeConfiguration conf) { Objects.requireNonNull(conf, "node config is null"); final TbLogNodeConfiguration defaultConfig = new TbLogNodeConfiguration().defaultConfiguration(); if (conf.getScriptLang() == null || conf.getScriptLang().equals(ScriptLanguage.JS)) { return defaultConfig.getJsScript().equals(conf.getJsScript()); } else if (conf.getScriptLang().equals(ScriptLanguage.TBEL)) { return defaultConfig.getTbelScript().equals(conf.getTbelScript()); } else { log.warn("No rule to define isStandard script for script language [{}], assuming that is non-standard", conf.getScriptLang());
return false; } } void logStandard(TbContext ctx, TbMsg msg) { log.info(toLogMessage(msg)); ctx.tellSuccess(msg); } String toLogMessage(TbMsg msg) { return "\n" + "Incoming message:\n" + msg.getData() + "\n" + "Incoming metadata:\n" + JacksonUtil.toString(msg.getMetaData().getData()); } @Override public void destroy() { if (scriptEngine != null) { scriptEngine.destroy(); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbLogNode.java
1
请完成以下Java代码
public class TestSecurityManager implements org.apache.geode.security.SecurityManager { @Override public Object authenticate(Properties credentials) throws AuthenticationFailedException { String username = credentials.getProperty(GeodeConstants.USERNAME); String password = credentials.getProperty(GeodeConstants.PASSWORD); if (!String.valueOf(username).equals(password)) { throw new AuthenticationFailedException(String.format("User [%s] could not be authenticated", username)); } return User.create(username); } public static class User implements Comparable<User>, Principal, Serializable { public static User create(String name) { return new User(name); } private final String name; public User(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Username is required"); } this.name = name; } public String getName() { return this.name; } @Override public int compareTo(User user) { return this.getName().compareTo(user.getName()); } @Override public boolean equals(Object obj) { if (this == obj) { return true;
} if (!(obj instanceof User)) { return false; } User that = (User) obj; return this.getName().equals(that.getName()); } @Override public int hashCode() { int hashValue = 17; hashValue = 37 * hashValue + getName().hashCode(); return hashValue; } @Override public String toString() { return getName(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\security\TestSecurityManager.java
1