instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public synchronized void run() { log.info("{} starting to reset expired jobs"); Thread.currentThread().setName("activiti-reset-expired-jobs"); while (!isInterrupted) { try { List<JobEntity> expiredJobs = asyncExecutor .getProcessEngineConfiguration() .getCommandExecutor() .execute(new FindExpiredJobsCmd(asyncExecutor.getResetExpiredJobsPageSize())); List<String> expiredJobIds = new ArrayList<String>(expiredJobs.size()); for (JobEntity expiredJob : expiredJobs) { expiredJobIds.add(expiredJob.getId()); } if (expiredJobIds.size() > 0) { asyncExecutor .getProcessEngineConfiguration() .getCommandExecutor() .execute(new ResetExpiredJobsCmd(expiredJobIds)); } } catch (Throwable e) { if (e instanceof ActivitiOptimisticLockingException) { log.debug("Optmistic lock exception while resetting locked jobs", e); } else { log.error("exception during resetting expired jobs", e.getMessage(), e); } } // Sleep try { synchronized (MONITOR) { if (!isInterrupted) { isWaiting.set(true); MONITOR.wait(asyncExecutor.getResetExpiredJobsInterval()); } }
} catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("async reset expired jobs wait interrupted"); } } finally { isWaiting.set(false); } } log.info("{} stopped resetting expired jobs"); } public void stop() { synchronized (MONITOR) { isInterrupted = true; if (isWaiting.compareAndSet(true, false)) { MONITOR.notifyAll(); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ResetExpiredJobsRunnable.java
1
请在Spring Boot框架中完成以下Java代码
public static class SecurityPermitAllConfig { private final String adminContextPath; public SecurityPermitAllConfig(AdminServerProperties adminServerProperties) { this.adminContextPath = adminServerProperties.getContextPath(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll()) .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers( PathPatternRequestMatcher.withDefaults() .matcher(POST, this.adminContextPath + "/instances"), PathPatternRequestMatcher.withDefaults() .matcher(DELETE, this.adminContextPath + "/instances/*"), PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**"))); return http.build(); } } @Profile("secure") @Configuration(proxyBeanMethods = false) public static class SecuritySecureConfig { private final String adminContextPath; public SecuritySecureConfig(AdminServerProperties adminServerProperties) { this.adminContextPath = adminServerProperties.getContextPath(); }
@Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); successHandler.setDefaultTargetUrl(this.adminContextPath + "/"); http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/assets/**")) .permitAll() .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/login")) .permitAll() .anyRequest() .authenticated()) .formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login") .successHandler(successHandler)) .logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout")) .httpBasic(Customizer.withDefaults()) .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers( PathPatternRequestMatcher.withDefaults() .matcher(POST, this.adminContextPath + "/instances"), PathPatternRequestMatcher.withDefaults() .matcher(DELETE, this.adminContextPath + "/instances/*"), PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**"))); return http.build(); } } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-consul\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminConsulApplication.java
2
请完成以下Java代码
public BigDecimal getBalance() { return BigDecimal.ZERO; } /** * Create Facts (the accounting logic) for * MMI. * * <pre> * Inventory * Inventory DR CR * InventoryDiff DR CR (or Charge) * </pre> * * @param as account schema * @return Fact */ @Override public List<Fact> createFacts(final AcctSchema as) { setC_Currency_ID(as.getCurrencyId()); final Fact fact = new Fact(this, as, PostingType.Actual); getDocLines().forEach(line -> createFactsForInventoryLine(fact, line)); return ImmutableList.of(fact); } /** * <pre> * Inventory * Inventory DR CR * InventoryDiff DR CR (or Charge) * </pre> */ private void createFactsForInventoryLine(final Fact fact, final DocLine_Inventory line) { final AcctSchema as = fact.getAcctSchema(); final CostAmount costs = line.getCreateCosts(as);
// // Inventory DR/CR fact.createLine() .setDocLine(line) .setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(costs.toMoney()) .setQty(line.getQty()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); // // Charge/InventoryDiff CR/DR final Account invDiff = line.getInvDifferencesAccount(as, costs.toBigDecimal().negate()); final FactLine cr = fact.createLine() .setDocLine(line) .setAccount(invDiff) .setAmtSourceDrOrCr(costs.toMoney().negate()) .setQty(line.getQty().negate()) .locatorId(line.getM_Locator_ID()) .buildAndAdd(); if (line.getC_Charge_ID().isPresent()) // explicit overwrite for charge { cr.setAD_Org_ID(line.getOrgId()); } } } // Doc_Inventory
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Inventory.java
1
请完成以下Java代码
public int getEventSubscriptionCount() { return eventSubscriptionCount; } public void setEventSubscriptionCount(int eventSubscriptionCount) { this.eventSubscriptionCount = eventSubscriptionCount; } public int getTaskCount() { return taskCount; } public void setTaskCount(int taskCount) { this.taskCount = taskCount; } public int getJobCount() { return jobCount; } public void setJobCount(int jobCount) { this.jobCount = jobCount; } public int getTimerJobCount() { return timerJobCount; } public void setTimerJobCount(int timerJobCount) { this.timerJobCount = timerJobCount; } public int getSuspendedJobCount() { return suspendedJobCount; } public void setSuspendedJobCount(int suspendedJobCount) { this.suspendedJobCount = suspendedJobCount; } public int getDeadLetterJobCount() { return deadLetterJobCount; } public void setDeadLetterJobCount(int deadLetterJobCount) { this.deadLetterJobCount = deadLetterJobCount; } public int getVariableCount() { return variableCount; } public void setVariableCount(int variableCount) { this.variableCount = variableCount; } public int getIdentityLinkCount() { return identityLinkCount; }
public void setIdentityLinkCount(int identityLinkCount) { this.identityLinkCount = identityLinkCount; } @Override public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } @Override public Integer getAppVersion() { return appVersion; } //toString ///////////////////////////////////////////////////////////////// public String toString() { if (isProcessInstanceType()) { return "ProcessInstance[" + getId() + "]"; } else { StringBuilder strb = new StringBuilder(); if (isScope) { strb.append("Scoped execution[ id '" + getId() + "' ]"); } else if (isMultiInstanceRoot) { strb.append("Multi instance root execution[ id '" + getId() + "' ]"); } else { strb.append("Execution[ id '" + getId() + "' ]"); } if (activityId != null) { strb.append(" - activity '" + activityId); } if (parentId != null) { strb.append(" - parent '" + parentId + "'"); } return strb.toString(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java
1
请完成以下Java代码
public static void closeMigrationScriptFiles() { getWriter().close(); } public static void setMigrationScriptDirectory(@NonNull final Path path) { MigrationScriptFileLogger.setMigrationScriptDirectory(path); } public static Path getMigrationScriptDirectory() { return MigrationScriptFileLogger.getMigrationScriptDirectory(); } private static boolean isSkipLogging(@NonNull final Sql sql) { return sql.isEmpty() || isSkipLogging(sql.getSqlCommand()); } private static boolean isSkipLogging(@NonNull final String sqlCommand) { // Always log DDL (flagged) commands if (sqlCommand.startsWith(DDL_PREFIX)) { return false; } final String sqlCommandUC = sqlCommand.toUpperCase().trim(); // // Don't log selects if (sqlCommandUC.startsWith("SELECT ")) { return true; } // // Don't log DELETE FROM Some_Table WHERE AD_Table_ID=? AND Record_ID=? if (sqlCommandUC.startsWith("DELETE FROM ") && sqlCommandUC.endsWith(" WHERE AD_TABLE_ID=? AND RECORD_ID=?")) {
return true; } // // Check that INSERT/UPDATE/DELETE statements are about our ignored tables final ImmutableSet<String> exceptionTablesUC = Services.get(IMigrationLogger.class).getTablesToIgnoreUC(Env.getClientIdOrSystem()); for (final String tableNameUC : exceptionTablesUC) { if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("DELETE FROM " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("DELETE " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("UPDATE " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + "(")) return true; } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLoggerHolder.java
1
请完成以下Java代码
public class IntermediateConditionalEventBehavior extends IntermediateCatchEventActivityBehavior implements ConditionalEventBehavior { protected final ConditionalEventDefinition conditionalEvent; public IntermediateConditionalEventBehavior(ConditionalEventDefinition conditionalEvent, boolean isAfterEventBasedGateway) { super(isAfterEventBasedGateway); this.conditionalEvent = conditionalEvent; } @Override public ConditionalEventDefinition getConditionalEventDefinition() { return conditionalEvent; } @Override public void execute(final ActivityExecution execution) throws Exception { if (isAfterEventBasedGateway || conditionalEvent.tryEvaluate(execution)) { leave(execution); } }
@Override public void leaveOnSatisfiedCondition(final EventSubscriptionEntity eventSubscription, final VariableEvent variableEvent) { PvmExecutionImpl execution = eventSubscription.getExecution(); if (execution != null && !execution.isEnded() && variableEvent != null && conditionalEvent.tryEvaluate(variableEvent, execution) && execution.isActive() && execution.isScope()) { if (isAfterEventBasedGateway) { final ActivityImpl activity = eventSubscription.getActivity(); execution.executeEventHandlerActivity(activity); } else { leave(execution); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\IntermediateConditionalEventBehavior.java
1
请完成以下Java代码
@Nullable PreFilterExpressionAttribute resolveAttribute(Method method, @Nullable Class<?> targetClass) { PreFilter preFilter = findPreFilterAnnotation(method, targetClass); if (preFilter == null) { return null; } Expression preFilterExpression = getExpressionHandler().getExpressionParser() .parseExpression(preFilter.value()); return new PreFilterExpressionAttribute(preFilterExpression, preFilter.filterTarget()); } void setTemplateDefaults(AnnotationTemplateExpressionDefaults defaults) { this.scanner = SecurityAnnotationScanners.requireUnique(PreFilter.class, defaults); } private @Nullable PreFilter findPreFilterAnnotation(Method method, @Nullable Class<?> targetClass) { Class<?> targetClassToUse = targetClass(method, targetClass); return this.scanner.scan(method, targetClassToUse);
} static final class PreFilterExpressionAttribute extends ExpressionAttribute { private final String filterTarget; private PreFilterExpressionAttribute(Expression expression, String filterTarget) { super(expression); this.filterTarget = filterTarget; } String getFilterTarget() { return this.filterTarget; } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreFilterExpressionAttributeRegistry.java
1
请完成以下Java代码
private ITranslatableString extractPlant(final @NotNull DDOrderReference ddOrderReference) { final ResourceId plantId = ddOrderReference.getPlantId(); return plantId != null ? TranslatableStrings.anyLanguage(sourceDocService.getPlantName(plantId)) : TranslatableStrings.empty(); } private static ITranslatableString extractQty(final @NotNull DDOrderReference ddOrderReference) { final Quantity qty = ddOrderReference.getQty(); return qty != null ? TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build() : TranslatableStrings.empty(); } private ITranslatableString extractProductValueAndName(final @NotNull DDOrderReference ddOrderReference) { final ProductId productId = ddOrderReference.getProductId(); return productId != null ? TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId)) : TranslatableStrings.empty(); } private @NotNull ITranslatableString extractGTIN(final @NotNull DDOrderReference ddOrderReference) { return Optional.ofNullable(ddOrderReference.getProductId()) .flatMap(productService::getGTIN) .map(GTIN::getAsString) .map(TranslatableStrings::anyLanguage) .orElse(TranslatableStrings.empty()); } @NonNull private ITranslatableString extractSourceDoc(@NonNull final DDOrderReference ddOrderReference) { ImmutablePair<ITranslatableString, String> documentTypeAndNo; if (ddOrderReference.getSalesOrderId() != null) { documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getSalesOrderId());
} else if (ddOrderReference.getPpOrderId() != null) { documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getPpOrderId()); } else { return TranslatableStrings.empty(); } return TranslatableStrings.builder() .append(documentTypeAndNo.getLeft()) .append(" ") .append(documentTypeAndNo.getRight()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionLauncherCaptionProvider.java
1
请完成以下Java代码
public I_R_Request createRequestFromDDOrderLine(@NonNull final I_DD_OrderLine ddOrderLine) { final I_DD_Order ddOrder = ddOrderLine.getDD_Order(); final RequestTypeId requestTypeId = getRequestTypeId(SOTrx.ofBoolean(ddOrder.isSOTrx())); final RequestCandidate requestCandidate = RequestCandidate.builder() .summary(ddOrderLine.getDescription()) // TODO: Decide what to put here .confidentialType(RequestConfidentialType.Internal) .orgId(OrgId.ofRepoId(ddOrderLine.getAD_Org_ID())) .productId(ProductId.ofRepoId(ddOrderLine.getM_Product_ID())) .recordRef(TableRecordReference.of(ddOrder)) .requestTypeId(requestTypeId) .partnerId(BPartnerId.ofRepoId(ddOrder.getC_BPartner_ID())) .userId(UserId.ofRepoIdOrNull(ddOrder.getAD_User_ID())) .dateDelivered(TimeUtil.asZonedDateTime(ddOrder.getDatePromised())) .build(); return createRequest(requestCandidate); } @Override public I_R_Request createRequestFromOrder(@NonNull final I_C_Order order) { final Optional<RequestTypeId> requestType = orderBL.getRequestTypeForCreatingNewRequestsAfterComplete(order); final RequestCandidate requestCandidate = RequestCandidate.builder() .summary(order.getDescription() != null ? order.getDescription() : " ")
.confidentialType(RequestConfidentialType.Internal) .orgId(OrgId.ofRepoId(order.getAD_Org_ID())) .recordRef(TableRecordReference.of(order)) .requestTypeId(requestType.orElseGet(() -> getRequestTypeId(SOTrx.ofBoolean(order.isSOTrx())))) .partnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID())) .userId(UserId.ofRepoIdOrNull(order.getAD_User_ID())) .dateDelivered(TimeUtil.asZonedDateTime(order.getDatePromised())) .build(); return createRequest(requestCandidate); } @Override public I_R_Request createRequest(final RequestCandidate requestCandidate) { return requestsRepo.createRequest(requestCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\api\impl\RequestBL.java
1
请在Spring Boot框架中完成以下Java代码
public String getPaymentReference() { return paymentReference; } /** * Sets the value of the paymentReference property. * * @param value * allowed object is * {@link String } * */ public void setPaymentReference(String value) { this.paymentReference = value; } /** * Indicates whether the payment is payable on a consolidator platform. In this case the attribute must be set to true. * * @return * possible object is * {@link Boolean }
* */ public Boolean isConsolidatorPayable() { return consolidatorPayable; } /** * Sets the value of the consolidatorPayable property. * * @param value * allowed object is * {@link Boolean } * */ public void setConsolidatorPayable(Boolean value) { this.consolidatorPayable = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\UniversalBankTransactionType.java
2
请完成以下Java代码
public class TbSplitArrayMsgNode implements TbNode { @Override public void init(TbContext ctx, TbNodeConfiguration configuration) {} @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { JsonNode jsonNode = JacksonUtil.toJsonNode(msg.getData()); if (jsonNode.isArray()) { ArrayNode data = (ArrayNode) jsonNode; if (data.isEmpty()) { ctx.ack(msg); } else if (data.size() == 1) { ctx.tellSuccess(msg.transform() .data(JacksonUtil.toString(data.get(0))) .build()); } else { TbMsgCallbackWrapper wrapper = new MultipleTbMsgsCallbackWrapper(data.size(), new TbMsgCallback() { @Override public void onSuccess() { ctx.ack(msg); }
@Override public void onFailure(RuleEngineException e) { ctx.tellFailure(msg, e); } }); data.forEach(msgNode -> { TbMsg outMsg = msg.transform() .data(JacksonUtil.toString(msgNode)) .build(); ctx.enqueueForTellNext(outMsg, TbNodeConnectionType.SUCCESS, wrapper::onSuccess, wrapper::onFailure); }); } } else { ctx.tellFailure(msg, new RuntimeException("Msg data is not a JSON Array!")); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\transform\TbSplitArrayMsgNode.java
1
请完成以下Java代码
protected void deleteCachedEntities(DbSqlSession dbSqlSession, Collection<CachedEntity> cachedObjects, CachedEntityMatcher<EntityImpl> cachedEntityMatcher, Object parameter) { if (cachedObjects != null && cachedEntityMatcher != null) { for (CachedEntity cachedObject : cachedObjects) { EntityImpl cachedEntity = (EntityImpl) cachedObject.getEntity(); boolean entityMatches = cachedEntityMatcher.isRetained(null, cachedObjects, cachedEntity, parameter); if (cachedEntity.isInserted() && entityMatches) { dbSqlSession.delete(cachedEntity); } if (entityMatches) { cachedEntity.setDeleted(true); } } } } protected List<List<String>> createSafeInValuesList(Collection<String> values) { // need to split into different parts due to some dbs not supporting more than MAX_ENTRIES_IN_CLAUSE for in() return CollectionUtil.partition(values, MAX_ENTRIES_IN_CLAUSE); } protected void executeChangeWithInClause(List<EntityImpl> entities, Consumer<List<EntityImpl>> consumer) { // need to split into different parts due to some dbs not supporting more than MAX_ENTRIES_IN_CLAUSE for in() CollectionUtil.consumePartitions(entities, MAX_ENTRIES_IN_CLAUSE, consumer); } protected void bulkDeleteEntities(String statement, List<EntityImpl> entities) { executeChangeWithInClause(entities, entitiesParameter -> {
getDbSqlSession().delete(statement, entitiesParameter, getManagedEntityClass()); }); } protected void bulkUpdateEntities(String statement, Map<String, Object> parameters, String collectionNameInSqlStatement, List<EntityImpl> entities) { executeChangeWithInClause(entities, entitiesParameter -> { Map<String, Object> copyParameters = new HashMap<>(parameters); copyParameters.put(collectionNameInSqlStatement, entitiesParameter); getDbSqlSession().directUpdate(statement, copyParameters); }); } protected boolean isEntityInserted(DbSqlSession dbSqlSession, String entityLogicalName, String entityId) { Class<?> executionEntityClass = dbSqlSession.getDbSqlSessionFactory().getLogicalNameToClassMapping().get(entityLogicalName); return executionEntityClass != null && dbSqlSession.isEntityInserted(executionEntityClass, entityId); } protected abstract IdGenerator getIdGenerator(); }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\AbstractDataManager.java
1
请完成以下Java代码
public String toString() { String name = config.getName(); return filterToStringCreator(DedupeResponseHeaderGatewayFilterFactory.this) .append(name != null ? name : "", config.getStrategy()) .toString(); } }; } public enum Strategy { /** * Default: Retain the first value only. */ RETAIN_FIRST, /** * Retain the last value only. */ RETAIN_LAST, /** * Retain all unique values in the order of their first encounter. */ RETAIN_UNIQUE } void dedupe(HttpHeaders headers, Config config) { String names = config.getName(); Strategy strategy = config.getStrategy(); if (headers == null || names == null || strategy == null) { return; } for (String name : names.split(" ")) { dedupe(headers, name.trim(), strategy); } } private void dedupe(HttpHeaders headers, String name, Strategy strategy) { List<String> values = headers.get(name); if (values == null || values.size() <= 1) {
return; } switch (strategy) { case RETAIN_FIRST: headers.set(name, values.get(0)); break; case RETAIN_LAST: headers.set(name, values.get(values.size() - 1)); break; case RETAIN_UNIQUE: headers.put(name, new ArrayList<>(new LinkedHashSet<>(values))); break; default: break; } } public static class Config extends AbstractGatewayFilterFactory.NameConfig { private Strategy strategy = Strategy.RETAIN_FIRST; public Strategy getStrategy() { return strategy; } public Config setStrategy(Strategy strategy) { this.strategy = strategy; return this; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\DedupeResponseHeaderGatewayFilterFactory.java
1
请完成以下Java代码
public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } public String getVersionTag() { return versionTag; } public boolean isStartableInTasklist() { return isStartableInTasklist; } public boolean isNotStartableInTasklist() { return isNotStartableInTasklist; } public boolean isStartablePermissionCheck() { return startablePermissionCheck; } public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) { this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks; } public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() { return processDefinitionCreatePermissionChecks; }
public boolean isShouldJoinDeploymentTable() { return shouldJoinDeploymentTable; } public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) { processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks()); } public List<String> getCandidateGroups() { if (cachedCandidateGroups != null) { return cachedCandidateGroups; } if(authorizationUserId != null) { List<Group> groups = Context.getCommandContext() .getReadOnlyIdentityProvider() .createGroupQuery() .groupMember(authorizationUserId) .list(); cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList()); } return cachedCandidateGroups; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricTaskLogEntryResponse { protected Long logNumber; protected String type; protected String taskId; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date timeStamp; protected String userId; protected String data; protected String executionId; protected String processInstanceId; protected String processDefinitionId; protected String scopeId; protected String scopeDefinitionId; protected String subScopeId; protected String scopeType; protected String tenantId; public Long getLogNumber() { return logNumber; } public void setLogNumber(Long logNumber) { this.logNumber = logNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getData() { return data; } public void setData(String data) { this.data = data; }
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryResponse.java
2
请完成以下Java代码
public static LocalToRemoteSyncResult upserted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.UPSERTED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult inserted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.INSERTED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult updated(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.UPDATED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult deleted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.DELETED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult error( @NonNull final DataRecord datarecord, @NonNull final String errorMessage) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.ERROR) .errorMessage(errorMessage) .build(); } public enum LocalToRemoteStatus { INSERTED_ON_REMOTE, UPDATED_ON_REMOTE,
UPSERTED_ON_REMOTE, DELETED_ON_REMOTE, UNCHANGED, ERROR; } LocalToRemoteStatus localToRemoteStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private LocalToRemoteSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final LocalToRemoteStatus localToRemoteStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.localToRemoteStatus = localToRemoteStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\LocalToRemoteSyncResult.java
1
请完成以下Java代码
public void setPointsSum_ToSettle (final @Nullable BigDecimal PointsSum_ToSettle) { set_ValueNoCheck (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference()
{ return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Overview_V.java
1
请完成以下Java代码
public class DummyNode<T> implements LinkedListNode<T> { private DoublyLinkedList<T> list; public DummyNode(DoublyLinkedList<T> list) { this.list = list; } @Override public boolean hasElement() { return false; } @Override public boolean isEmpty() { return true; } @Override public T getElement() throws NullPointerException { throw new NullPointerException(); } @Override public void detach() { return; } @Override
public DoublyLinkedList<T> getListReference() { return list; } @Override public LinkedListNode<T> setPrev(LinkedListNode<T> next) { return next; } @Override public LinkedListNode<T> setNext(LinkedListNode<T> prev) { return prev; } @Override public LinkedListNode<T> getPrev() { return this; } @Override public LinkedListNode<T> getNext() { return this; } @Override public LinkedListNode<T> search(T value) { return this; } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\DummyNode.java
1
请完成以下Java代码
public class SchedulerUtils { private static final ConcurrentMap<String, ZoneId> tzMap = new ConcurrentHashMap<>(); public static ZoneId getZoneId(String tz) { return tzMap.computeIfAbsent(tz == null || tz.isEmpty() ? "UTC" : tz, ZoneId::of); } public static long getStartOfCurrentHour() { return getStartOfCurrentHour(UTC); } public static long getStartOfCurrentHour(ZoneId zoneId) { return LocalDateTime.now(UTC).atZone(zoneId).truncatedTo(ChronoUnit.HOURS).toInstant().toEpochMilli(); } public static long getStartOfCurrentMonth() { return getStartOfCurrentMonth(UTC);
} public static long getStartOfCurrentMonth(ZoneId zoneId) { return LocalDate.now(UTC).withDayOfMonth(1).atStartOfDay(zoneId).toInstant().toEpochMilli(); } public static long getStartOfNextMonth() { return getStartOfNextMonth(UTC); } public static long getStartOfNextMonth(ZoneId zoneId) { return LocalDate.now(UTC).with(TemporalAdjusters.firstDayOfNextMonth()).atStartOfDay(zoneId).toInstant().toEpochMilli(); } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\tools\SchedulerUtils.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getPassportNumber() { return passportNumber; } public void setPassportNumber(String passportNumber) { this.passportNumber = passportNumber; } @Override public String toString() { return String.format("Student [id=%s, name=%s, passportNumber=%s]", id, name, passportNumber); } }
repos\Spring-Boot-Advanced-Projects-main\spring-boot jpa-with-hibernate-and-h2\src\main\java\com\alanbinu\springboot\jpa\hibernate\h2\example\student\Student.java
1
请完成以下Java代码
public static void setTimeSource(@NonNull final TimeSource newTimeSource) { timeSource = newTimeSource; } public static void setFixedTimeSource(@NonNull final ZonedDateTime date) { setTimeSource(FixedTimeSource.ofZonedDateTime(date)); } /** * @param zonedDateTime ISO 8601 date time format (see {@link ZonedDateTime#parse(CharSequence)}). * e.g. 2018-02-28T13:13:13+01:00[Europe/Berlin] */ public static void setFixedTimeSource(@NonNull final String zonedDateTime) { setTimeSource(FixedTimeSource.ofZonedDateTime(ZonedDateTime.parse(zonedDateTime))); } public static long millis() { return getTimeSource().millis(); } public static ZoneId zoneId() { return getTimeSource().zoneId(); } public static GregorianCalendar asGregorianCalendar() { final GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(millis()); return cal; } public static Date asDate() { return new Date(millis()); } public static Timestamp asTimestamp() { return new Timestamp(millis()); } /** * Same as {@link #asTimestamp()} but the returned date will be truncated to DAY. */ public static Timestamp asDayTimestamp() { final GregorianCalendar cal = asGregorianCalendar(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Timestamp(cal.getTimeInMillis()); } public static Instant asInstant()
{ return Instant.ofEpochMilli(millis()); } public static LocalDateTime asLocalDateTime() { return asZonedDateTime().toLocalDateTime(); } @NonNull public static LocalDate asLocalDate() { return asLocalDate(zoneId()); } @NonNull public static LocalDate asLocalDate(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId).toLocalDate(); } public static ZonedDateTime asZonedDateTime() { return asZonedDateTime(zoneId()); } public static ZonedDateTime asZonedDateTimeAtStartOfDay() { return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS); } public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId) .toLocalDate() .atTime(LocalTime.MAX) .atZone(zoneId); } public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId) { return asInstant().atZone(zoneId); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
1
请完成以下Java代码
private HttpServer customizeSslConfiguration(HttpServer httpServer, Ssl ssl) { SslServerCustomizer customizer = new SslServerCustomizer(getHttp2(), ssl.getClientAuth(), getSslBundle(), getServerNameSslBundles()); addBundleUpdateHandler(null, ssl.getBundle(), customizer); ssl.getServerNameBundles() .forEach((serverNameSslBundle) -> addBundleUpdateHandler(serverNameSslBundle.serverName(), serverNameSslBundle.bundle(), customizer)); return customizer.apply(httpServer); } private void addBundleUpdateHandler(@Nullable String serverName, @Nullable String bundleName, SslServerCustomizer customizer) { if (StringUtils.hasText(bundleName)) { SslBundles sslBundles = getSslBundles(); Assert.state(sslBundles != null, "'sslBundles' must not be null"); sslBundles.addBundleUpdateHandler(bundleName, (sslBundle) -> customizer.updateSslBundle(serverName, sslBundle)); } } private HttpProtocol[] listProtocols() { List<HttpProtocol> protocols = new ArrayList<>(); protocols.add(HttpProtocol.HTTP11); if (getHttp2() != null && getHttp2().isEnabled()) { if (getSsl() != null && getSsl().isEnabled()) { protocols.add(HttpProtocol.H2); } else {
protocols.add(HttpProtocol.H2C); } } return protocols.toArray(new HttpProtocol[0]); } private InetSocketAddress getListenAddress() { if (getAddress() != null) { return new InetSocketAddress(getAddress().getHostAddress(), getPort()); } return new InetSocketAddress(getPort()); } private HttpServer applyCustomizers(HttpServer server) { for (NettyServerCustomizer customizer : this.serverCustomizers) { server = customizer.apply(server); } return server; } }
repos\spring-boot-4.0.1\module\spring-boot-reactor-netty\src\main\java\org\springframework\boot\reactor\netty\NettyReactiveWebServerFactory.java
1
请在Spring Boot框架中完成以下Java代码
class DeliveryLocationBasedAggregation { @NonNull private final DeliveryLocationBasedAggregationKey key; private boolean partiallyPickedBefore = false; @NonNull private final PickingJobCandidateProductsCollector productsCollector = new PickingJobCandidateProductsCollector(); @NonNull private final HashSet<ShipmentScheduleAndJobScheduleId> scheduleIds = new HashSet<>(); public DeliveryLocationBasedAggregation(@NonNull final DeliveryLocationBasedAggregationKey key) { this.key = key; } public void add(@NonNull final ScheduledPackageable item) { this.partiallyPickedBefore = this.partiallyPickedBefore || item.isPartiallyPickedOrDelivered(); this.productsCollector.collect(item); this.scheduleIds.add(item.getId()); }
public PickingJobCandidate toPickingJobCandidate() { return PickingJobCandidate.builder() .aggregationType(PickingJobAggregationType.DELIVERY_LOCATION) .preparationDate(key.getPreparationDate()) .customerName(key.getCustomerName()) .deliveryBPLocationId(key.getDeliveryBPLocationId()) .warehouseTypeId(key.getWarehouseTypeId()) .partiallyPickedBefore(partiallyPickedBefore) .products(productsCollector.toProducts()) .scheduleIds(ShipmentScheduleAndJobScheduleIdSet.ofCollection(scheduleIds)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\retrieve\DeliveryLocationBasedAggregation.java
2
请完成以下Java代码
public Map<String, Feature> features() { return features; } @ReadOperation public Feature feature(@Selector String name) { return features.get(name); } @WriteOperation public void configureFeature(@Selector String name, Feature feature) { features.put(name, feature); } @DeleteOperation public void deleteFeature(@Selector String name) { features.remove(name);
} public static class Feature { private Boolean enabled; public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\actuator\FeaturesEndpoint.java
1
请完成以下Java代码
public class QualityInvoiceLineGroup implements IQualityInvoiceLineGroup { private IQualityInvoiceLine invoiceableLine; private IQualityInvoiceLine invoiceableLineOverride; private final QualityInvoiceLineGroupType qualityInvoiceLineGroupType; private final List<IQualityInvoiceLine> detailsBefore = new ArrayList<>(); private final List<IQualityInvoiceLine> detailsAfter = new ArrayList<>(); public QualityInvoiceLineGroup(final QualityInvoiceLineGroupType qualityInvoiceLineGroupType) { Check.assumeNotNull(qualityInvoiceLineGroupType, "Param 'qualityInvoiceLineGroupType' is not null"); this.qualityInvoiceLineGroupType = qualityInvoiceLineGroupType; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("QualityInvoiceLineGroup["); sb.append("\n\tType: ").append(qualityInvoiceLineGroupType); sb.append("\n\tinvoiceableLine: ").append(invoiceableLine); if (!detailsBefore.isEmpty()) { sb.append("\n\tDetails(before)"); for (final IQualityInvoiceLine detail : detailsBefore) { sb.append("\n\t\t").append(detail); } } if (!detailsAfter.isEmpty()) { sb.append("\n\tDetails(after)"); for (final IQualityInvoiceLine detail : detailsAfter) { sb.append("\n\t\t").append(detail); } } sb.append("\n]"); return sb.toString(); } @Override public void setInvoiceableLine(final IQualityInvoiceLine invoiceableLine) { this.invoiceableLine = invoiceableLine; setThisAsParentIfPossible(invoiceableLine); } @Override public IQualityInvoiceLine getInvoiceableLine() { Check.assumeNotNull(invoiceableLine, "invoiceableLine not null"); return invoiceableLine; } @Override public void setInvoiceableLineOverride(final IQualityInvoiceLine invoiceableLineOverride) { this.invoiceableLineOverride = invoiceableLineOverride; setThisAsParentIfPossible(invoiceableLineOverride);
} private void setThisAsParentIfPossible(IQualityInvoiceLine invoiceableLineOverride) { if (invoiceableLineOverride instanceof QualityInvoiceLine) { ((QualityInvoiceLine)invoiceableLineOverride).setGroup(this); } } @Override public IQualityInvoiceLine getInvoiceableLineOverride() { return invoiceableLineOverride; } @Override public QualityInvoiceLineGroupType getQualityInvoiceLineGroupType() { return qualityInvoiceLineGroupType; } @Override public void addDetailBefore(final IQualityInvoiceLine line) { Check.assumeNotNull(line, "line not null"); detailsBefore.add(line); setThisAsParentIfPossible(line); } @Override public List<IQualityInvoiceLine> getDetailsBefore() { return detailsBefore; } @Override public void addDetailAfter(final IQualityInvoiceLine line) { Check.assumeNotNull(line, "line not null"); detailsAfter.add(line); setThisAsParentIfPossible(line); } @Override public List<IQualityInvoiceLine> getDetailsAfter() { return detailsAfter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\invoicing\impl\QualityInvoiceLineGroup.java
1
请在Spring Boot框架中完成以下Java代码
public class BaseCommonServiceImpl implements BaseCommonService { @Resource private BaseCommonMapper baseCommonMapper; @Override public void addLog(LogDTO logDTO) { if(oConvertUtils.isEmpty(logDTO.getId())){ logDTO.setId(String.valueOf(IdWorker.getId())); } //保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)JT-238 try { logDTO.setCreateTime(new Date()); baseCommonMapper.saveLog(logDTO); } catch (Exception e) { log.warn(" LogContent length : "+logDTO.getLogContent().length()); log.warn(e.getMessage()); } } @Override public void addLog(String logContent, Integer logType, Integer operatetype, LoginUser user) { LogDTO sysLog = new LogDTO(); sysLog.setId(String.valueOf(IdWorker.getId())); //注解上的描述,操作日志内容 sysLog.setLogContent(logContent); sysLog.setLogType(logType); sysLog.setOperateType(operatetype); try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IpUtils.getIpAddr(request)); try { //设置客户端 if(BrowserUtils.isDesktop(request)){ sysLog.setClientType(ClientTerminalTypeEnum.PC.getKey()); }else{
sysLog.setClientType(ClientTerminalTypeEnum.APP.getKey()); } } catch (Exception e) { //e.printStackTrace(); } } catch (Exception e) { sysLog.setIp("127.0.0.1"); } //获取登录用户信息 if(user==null){ try { user = (LoginUser) SecurityUtils.getSubject().getPrincipal(); } catch (Exception e) { //e.printStackTrace(); } } if(user!=null){ sysLog.setUserid(user.getUsername()); sysLog.setUsername(user.getRealname()); } sysLog.setCreateTime(new Date()); //保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)JT-238 try { baseCommonMapper.saveLog(sysLog); } catch (Exception e) { log.warn(" LogContent length : "+sysLog.getLogContent().length()); log.warn(e.getMessage()); } } @Override public void addLog(String logContent, Integer logType, Integer operateType) { addLog(logContent, logType, operateType, null); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\modules\base\service\impl\BaseCommonServiceImpl.java
2
请完成以下Java代码
public abstract class HistoryTaskListener implements TaskListener { protected final HistoryEventProducer eventProducer; protected HistoryLevel historyLevel; public HistoryTaskListener(HistoryEventProducer historyEventProducer) { this.eventProducer = historyEventProducer; } public void notify(DelegateTask task) { // get the event handler final HistoryEventHandler historyEventHandler = Context.getProcessEngineConfiguration() .getHistoryEventHandler(); ExecutionEntity execution = ((TaskEntity) task).getExecution(); if (execution != null) { // delegate creation of the history event to the producer HistoryEvent historyEvent = createHistoryEvent(task, execution); if(historyEvent != null) {
// pass the event to the handler historyEventHandler.handleEvent(historyEvent); } } } protected void ensureHistoryLevelInitialized() { if (historyLevel == null) { historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); } } protected abstract HistoryEvent createHistoryEvent(DelegateTask task, ExecutionEntity execution); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\parser\HistoryTaskListener.java
1
请完成以下Java代码
private String getExceptionTypeAndMessage(Throwable ex) { String message = ex.getMessage(); return ex.getClass().getName() + (StringUtils.hasText(message) ? ": " + message : ""); } private FailureAnalysis getFailureAnalysis(String description, BindException cause, @Nullable FailureAnalysis missingParametersAnalysis) { StringBuilder action = new StringBuilder("Update your application's configuration"); Collection<String> validValues = findValidValues(cause); if (!validValues.isEmpty()) { action.append(String.format(". The following values are valid:%n")); validValues.forEach((value) -> action.append(String.format("%n %s", value))); } if (missingParametersAnalysis != null) { action.append(String.format("%n%n%s", missingParametersAnalysis.getAction()));
} return new FailureAnalysis(description, action.toString(), cause); } private Collection<String> findValidValues(BindException ex) { ConversionFailedException conversionFailure = findCause(ex, ConversionFailedException.class); if (conversionFailure != null) { Object[] enumConstants = conversionFailure.getTargetType().getType().getEnumConstants(); if (enumConstants != null) { return Stream.of(enumConstants).map(Object::toString).collect(Collectors.toCollection(TreeSet::new)); } } return Collections.emptySet(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\BindFailureAnalyzer.java
1
请完成以下Java代码
public static TextEncryptor delux(CharSequence password, CharSequence salt) { return new HexEncodingTextEncryptor(stronger(password, salt)); } /** * Creates a text encryptor that uses "standard" password-based encryption. Encrypted * text is hex-encoded. * @param password the password used to generate the encryptor's secret key; should * not be shared * @see Encryptors#standard(CharSequence, CharSequence) */ public static TextEncryptor text(CharSequence password, CharSequence salt) { return new HexEncodingTextEncryptor(standard(password, salt)); } /** * Creates a text encryptor that performs no encryption. Useful for developer testing * environments where working with plain text strings is desired for simplicity. */ public static TextEncryptor noOpText() { return NoOpTextEncryptor.INSTANCE; }
private static final class NoOpTextEncryptor implements TextEncryptor { static final TextEncryptor INSTANCE = new NoOpTextEncryptor(); @Override public String encrypt(String text) { return text; } @Override public String decrypt(String encryptedText) { return encryptedText; } } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\Encryptors.java
1
请完成以下Java代码
public void setServers(List<String> servers) { this.servers = servers; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Component getComponent() { return component; } public void setComponent(Component component) { this.component = component; } public Map<String, String> getMap() { return map; } public void setMap(Map<String, String> map) { this.map = map; } public List<String> getExternal() { return external; } public void setExternal(List<String> external) { this.external = external; } public class Component { private Idm idm = new Idm(); private Service service = new Service(); public Idm getIdm() { return idm; } public void setIdm(Idm idm) { this.idm = idm; } public Service getService() { return service; } public void setService(Service service) { this.service = service; } } public class Idm { private String url; private String user; private String password; private String description; public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } public class Service { private String url; private String token; private String description; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yaml\YAMLConfig.java
1
请完成以下Java代码
public ESRImportEnqueuer loggable(@NonNull final ILoggable loggable) { this.loggable = loggable; return this; } private void addLog(final String msg, final Object... msgParameters) { loggable.addLog(msg, msgParameters); } private static class ZipFileResource extends AbstractResource { private final byte[] data; private final String filename; @Builder private ZipFileResource( @NonNull final byte[] data, @NonNull final String filename) { this.data = data; this.filename = filename; } @Override public String getFilename() {
return filename; } @Override public String getDescription() { return null; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(data); } public byte[] getData() { return data; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRImportEnqueuer.java
1
请完成以下Java代码
private static RequestMatcher createRequestMatcher() { final RequestMatcher defaultRequestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI); final RequestMatcher multipleIssuersRequestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, "/**" + DEFAULT_OIDC_PROVIDER_CONFIGURATION_ENDPOINT_URI); return (request) -> AuthorizationServerContextHolder.getContext() .getAuthorizationServerSettings() .isMultipleIssuersAllowed() ? multipleIssuersRequestMatcher.matches(request) : defaultRequestMatcher.matches(request); } private static Consumer<List<String>> clientAuthenticationMethods() { return (authenticationMethods) -> { authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()); authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue()); authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue()); authenticationMethods.add(ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue()); authenticationMethods.add(ClientAuthenticationMethod.TLS_CLIENT_AUTH.getValue()); authenticationMethods.add(ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH.getValue()); }; } private static Consumer<List<String>> dPoPSigningAlgorithms() {
return (algs) -> { algs.add(JwsAlgorithms.RS256); algs.add(JwsAlgorithms.RS384); algs.add(JwsAlgorithms.RS512); algs.add(JwsAlgorithms.PS256); algs.add(JwsAlgorithms.PS384); algs.add(JwsAlgorithms.PS512); algs.add(JwsAlgorithms.ES256); algs.add(JwsAlgorithms.ES384); algs.add(JwsAlgorithms.ES512); }; } private static String asUrl(String issuer, String endpoint) { return UriComponentsBuilder.fromUriString(issuer).path(endpoint).build().toUriString(); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcProviderConfigurationEndpointFilter.java
1
请完成以下Java代码
public void setDecisionDefinitionVersion(int decisionDefinitionVersion) { this.decisionDefinitionVersion = decisionDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedDecisionInstanceCount() { return finishedDecisionInstanceCount; } public void setFinishedDecisionInstanceCount(long finishedDecisionInstanceCount) { this.finishedDecisionInstanceCount = finishedDecisionInstanceCount; } public long getCleanableDecisionInstanceCount() { return cleanableDecisionInstanceCount; } public void setCleanableDecisionInstanceCount(long cleanableDecisionInstanceCount) { this.cleanableDecisionInstanceCount = cleanableDecisionInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public String toString() { return this.getClass().getSimpleName() + "[decisionDefinitionId = " + decisionDefinitionId + ", decisionDefinitionKey = " + decisionDefinitionKey + ", decisionDefinitionName = " + decisionDefinitionName + ", decisionDefinitionVersion = " + decisionDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedDecisionInstanceCount = " + finishedDecisionInstanceCount + ", cleanableDecisionInstanceCount = " + cleanableDecisionInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricDecisionInstanceReportResultEntity.java
1
请完成以下Java代码
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; FilterInvocation filterInvocation = new FilterInvocation(request, response, chain); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(filterInvocation); if (attributes != null) { this.logger.debug(LogMessage.format("Request: %s; ConfigAttributes: %s", filterInvocation, attributes)); this.channelDecisionManager.decide(filterInvocation, attributes); @Nullable HttpServletResponse channelResponse = filterInvocation.getResponse(); Assert.notNull(channelResponse, "HttpServletResponse is required"); if (channelResponse.isCommitted()) { return; } } chain.doFilter(request, response); } protected @Nullable ChannelDecisionManager getChannelDecisionManager() {
return this.channelDecisionManager; } protected FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager) { this.channelDecisionManager = channelDecisionManager; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) { this.securityMetadataSource = filterInvocationSecurityMetadataSource; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelProcessingFilter.java
1
请完成以下Java代码
public class UserRegistrationDto { @NotEmpty private String firstName; @NotEmpty private String lastName; @NotEmpty private String password; @Email @NotEmpty private String confirmPassword; @Email @NotEmpty private String email; @AssertTrue private String confirmEmail; private Boolean terms; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getConfirmEmail() { return confirmEmail; } public void setConfirmEmail(String confirmEmail) { this.confirmEmail = confirmEmail; } public Boolean getTerms() { return terms; } public void setTerms(Boolean terms) { this.terms = terms; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\web\dto\UserRegistrationDto.java
1
请在Spring Boot框架中完成以下Java代码
public class WebApplicationSecurity { public static void main(String... args) { Config config = Config.create(); Map<String, MyUser> users = new HashMap<>(); users.put("user", new MyUser("user", "user".toCharArray(), Collections.singletonList("ROLE_USER"))); users.put("admin", new MyUser("admin", "admin".toCharArray(), Arrays.asList("ROLE_USER", "ROLE_ADMIN"))); SecureUserStore store = user -> Optional.ofNullable(users.get(user)); HttpBasicAuthProvider httpBasicAuthProvider = HttpBasicAuthProvider.builder() .realm("myRealm") .subjectType(SubjectType.USER) .userStore(store) .build(); //1. Using Builder Pattern or Config Pattern Security security = Security.builder() .addAuthenticationProvider(httpBasicAuthProvider)
.build(); //Security security = Security.create(config); //2. WebSecurity from Security or from Config // WebSecurity webSecurity = WebSecurity.create(security).securityDefaults(WebSecurity.authenticate()); WebSecurity webSecurity = WebSecurity.create(config); Routing routing = Routing.builder() .register(webSecurity) .get("/user", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_USER")) .get("/admin", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_ADMIN")) .build(); WebServer webServer = WebServer.create(routing, config.get("server")); webServer.start().thenAccept(ws -> System.out.println("Server started at: http://localhost:" + ws.port()) ); } }
repos\tutorials-master\microservices-modules\helidon\helidon-se\src\main\java\com\baeldung\helidon\se\security\WebApplicationSecurity.java
2
请完成以下Java代码
protected ColorUIResource getPrimary1() { return LOGO_TEXT_COLOR; } @Override protected ColorUIResource getPrimary3() { // used for: // * standard scrollbar thumb's background color - NOTE: we replace it with our scrollbarUI // * panel backgrounds // return new ColorUIResource(247, 255, 238); // very very light green return getWhite(); } @Override protected ColorUIResource getSecondary3() { return getPrimary3(); } protected ColorUIResource getRed() { return COLOR_RED; } @Override public ColorUIResource getFocusColor() { return LOGO_TEXT_COLOR; } /** * Table header border. * * This is a slightly changed version of {@link javax.swing.plaf.metal.MetalBorders.TableHeaderBorder}. * * @author tsa
* */ public static class TableHeaderBorder extends javax.swing.border.AbstractBorder { private static final long serialVersionUID = 1L; private final Insets editorBorderInsets = new Insets(2, 2, 2, 2); private final Color borderColor; public TableHeaderBorder(final Color borderColor) { super(); this.borderColor = borderColor; } @Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int w, final int h) { g.translate(x, y); g.setColor(borderColor); g.drawLine(w - 1, 0, w - 1, h - 1); // right line g.drawLine(1, h - 1, w - 1, h - 1); // bottom line // g.setColor(MetalLookAndFeel.getControlHighlight()); // g.drawLine(0, 0, w - 2, 0); // top line // g.drawLine(0, 0, 0, h - 2); // left line g.translate(-x, -y); } @Override public Insets getBorderInsets(final Component c, final Insets insets) { insets.set(editorBorderInsets.top, editorBorderInsets.left, editorBorderInsets.bottom, editorBorderInsets.right); return insets; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshTheme.java
1
请在Spring Boot框架中完成以下Java代码
public Result<List<SysDataLog>> queryCompareList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataId1 = req.getParameter("dataId1"); String dataId2 = req.getParameter("dataId2"); List<String> idList = new ArrayList<String>(); idList.add(dataId1); idList.add(dataId2); try { List<SysDataLog> list = (List<SysDataLog>) service.listByIds(idList); result.setResult(list); result.setSuccess(true); } catch (Exception e) { log.error(e.getMessage(),e); } return result; } /** * 查询版本信息 * @param req * @return */ @RequestMapping(value = "/queryDataVerList", method = RequestMethod.GET) public Result<List<SysDataLog>> queryDataVerList(HttpServletRequest req) { Result<List<SysDataLog>> result = new Result<>(); String dataTable = req.getParameter("dataTable"); String dataId = req.getParameter("dataId"); QueryWrapper<SysDataLog> queryWrapper = new QueryWrapper<SysDataLog>(); queryWrapper.eq("data_table", dataTable);
queryWrapper.eq("data_id", dataId); // 代码逻辑说明: 新增查询条件-type String type = req.getParameter("type"); if (oConvertUtils.isNotEmpty(type)) { queryWrapper.eq("type", type); } // 按时间倒序排 queryWrapper.orderByDesc("create_time"); List<SysDataLog> list = service.list(queryWrapper); if(list==null||list.size()<=0) { result.error500("未找到版本信息"); }else { result.setResult(list); result.setSuccess(true); } return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDataLogController.java
2
请完成以下Java代码
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception { //4. Signing JWSSigner jwsSigner = getJwsSigner(); Instant now = Instant.now(); //Long expiresInMin = 30L; Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES)); //3. JWT Payload or claims JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder() .issuer("http://localhost:9080") .subject(subject) .claim("upn", subject) .claim("client_id", clientId) .audience("http://localhost:9280") .claim("scope", approvedScope) .claim("groups", Arrays.asList(approvedScope.split(" "))) .expirationTime(expirationTime) // expires in 30 minutes .notBeforeTime(Date.from(now)) .issueTime(Date.from(now)) .jwtID(UUID.randomUUID().toString()) .build(); SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims); signedJWT.sign(jwsSigner); return signedJWT.serialize(); }
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception { JWSSigner jwsSigner = getJwsSigner(); Instant now = Instant.now(); //6.Build refresh token JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder() .subject(subject) .claim("client_id", clientId) .claim("scope", approvedScope) //refresh token for 1 day. .expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS))) .build(); SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims); signedRefreshToken.sign(jwsSigner); return signedRefreshToken.serialize(); } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\handler\AbstractGrantTypeHandler.java
1
请完成以下Java代码
public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public String getWorkflowRunId() { return workflowRunId; } public void setWorkflowRunId(String workflowRunId) { this.workflowRunId = workflowRunId; } public String getQueryName() {
return queryName; } public void setQueryName(String queryName) { this.queryName = queryName; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\model\QueryInfo.java
1
请完成以下Java代码
public void eventCancelledByEventGateway(DelegateExecution execution) { deleteMessageEventSubScription(execution); Context.getCommandContext() .getExecutionEntityManager() .deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL); } protected ExecutionEntity deleteMessageEventSubScription(DelegateExecution execution) { ExecutionEntity executionEntity = (ExecutionEntity) execution; // Should we use triggerName and triggerData, because message name expression can change? String messageName = messageExecutionContext.getMessageName(execution); EventSubscriptionEntityManager eventSubscriptionEntityManager = Context.getCommandContext().getEventSubscriptionEntityManager(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if ( eventSubscription instanceof MessageEventSubscriptionEntity && eventSubscription.getEventName().equals(messageName)
) { eventSubscriptionEntityManager.delete(eventSubscription); } } return executionEntity; } public MessageEventDefinition getMessageEventDefinition() { return messageEventDefinition; } public MessageExecutionContext getMessageExecutionContext() { return messageExecutionContext; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateCatchMessageEventActivityBehavior.java
1
请完成以下Java代码
public void plusOne() { gauge.addAndGet(1); onInvoke(); } @Override public void minusOne() { gauge.addAndGet(-1); onInvoke(); } private void onInvoke() { final long millisNow = SystemTime.millis(); intervalLastInvoke = new BigDecimal(millisNow - millisLastInvoke.get()); millisLastInvoke.set(millisNow); invokeCount.addAndGet(1); updateInvokeRate(); } private void updateInvokeRate() { // getting local copies to ensure that the values we work with aren't changed by other threads // while this method executes final BigDecimal intervalLastInvokeLocal = this.intervalLastInvoke; final long invokeCountLocal = invokeCount.get(); if (invokeCountLocal < 2) { // need at least two 'plusOne()' invocations to get a rate invokeRate = BigDecimal.ZERO;
} else if (intervalLastInvokeLocal.signum() == 0) { // omit division by zero invokeRate = new BigDecimal(Long.MAX_VALUE); } else { invokeRate = new BigDecimal("1000") .setScale(2, BigDecimal.ROUND_HALF_UP) .divide(intervalLastInvokeLocal, RoundingMode.HALF_UP) .abs(); // be tolerant against intervalLastChange < 0 } } @Override public long getInvokeCount() { return invokeCount.get(); } @Override public BigDecimal getInvokeRate() { return invokeRate; } @Override public long getGauge() { return gauge.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\api\impl\Meter.java
1
请完成以下Java代码
public WindowId getWindowId(@NonNull final DocumentZoomIntoInfo zoomIntoInfo) { if (zoomIntoInfo.getWindowId() != null) { return zoomIntoInfo.getWindowId(); } final AdWindowId zoomInto_adWindowId; if (zoomIntoInfo.isRecordIdPresent()) { zoomInto_adWindowId = RecordWindowFinder.newInstance(zoomIntoInfo.getTableName(), zoomIntoInfo.getRecordId()) .checkRecordPresentInWindow() .checkParentRecord() .findAdWindowId() .orElse(null); } else {
zoomInto_adWindowId = RecordWindowFinder.findAdWindowId(zoomIntoInfo.getTableName()).orElse(null); } if (zoomInto_adWindowId == null) { throw new EntityNotFoundException("No windowId found") .setParameter("zoomIntoInfo", zoomIntoInfo); } return WindowId.of(zoomInto_adWindowId); } private DocumentEntityDescriptor getDocumentEntityDescriptor(final WindowId windowId) { final DocumentDescriptor descriptor = documentDescriptorFactory.getDocumentDescriptor(windowId); return descriptor.getEntityDescriptor(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\zoom_into\DocumentZoomIntoService.java
1
请在Spring Boot框架中完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static Map<String, Map<String, Object>> toMap() { BankAccountTypeEnum[] ary = BankAccountTypeEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); map.put("name", ary[num].name()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { BankAccountTypeEnum[] ary = BankAccountTypeEnum.values(); List list = new ArrayList();
for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); map.put("name", ary[i].name()); list.add(map); } return list; } public static BankAccountTypeEnum getEnum(String enumName) { BankAccountTypeEnum resultEnum = null; BankAccountTypeEnum[] enumAry = BankAccountTypeEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(enumName)) { resultEnum = enumAry[i]; break; } } return resultEnum; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BankAccountTypeEnum.java
2
请完成以下Java代码
public class InvoicesTableModel extends AbstractAllocableDocTableModel<IInvoiceRow> { private static final long serialVersionUID = 1L; // NOTE: order is important because some BL wants to apply the types in the same order they were enabled! private final LinkedHashSet<InvoiceWriteOffAmountType> allowedWriteOffTypes = new LinkedHashSet<>(); public InvoicesTableModel() { super(IInvoiceRow.class); // Initialize allowed write-off types for (final InvoiceWriteOffAmountType type : InvoiceWriteOffAmountType.values()) { final boolean allowed = allowedWriteOffTypes.contains(type); setAllowWriteOffAmountOfType(type, allowed); } } public final void setAllowWriteOffAmountOfType(final InvoiceWriteOffAmountType type, final boolean allowed) { Check.assumeNotNull(type, "type not null"); // // Update the internal set if (allowed) { allowedWriteOffTypes.add(type); } else {
allowedWriteOffTypes.remove(type); } // // Update column's editable status final String columnName = type.columnName(); getTableColumnInfo(columnName).setEditable(allowed); fireTableColumnChanged(columnName); } public final boolean isAllowWriteOffAmountOfType(final InvoiceWriteOffAmountType type) { return allowedWriteOffTypes.contains(type); } /** * @return allowed write-off types, in the same order they were enabled */ public final Set<InvoiceWriteOffAmountType> getAllowedWriteOffTypes() { return ImmutableSet.copyOf(allowedWriteOffTypes); } public void setMultiCurrency(final boolean multiCurrency) { getTableColumnInfo(IInvoiceRow.PROPERTY_ConvertedAmt).setVisible(multiCurrency); getTableColumnInfo(IInvoiceRow.PROPERTY_DocumentCurrency).setVisible(multiCurrency); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoicesTableModel.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getShutdownTimeout() { return this.shutdownTimeout; } public void setShutdownTimeout(Duration shutdownTimeout) { this.shutdownTimeout = shutdownTimeout; } public @Nullable String getReadFrom() { return this.readFrom; } public void setReadFrom(@Nullable String readFrom) { this.readFrom = readFrom; } public Pool getPool() { return this.pool; } public Cluster getCluster() { return this.cluster; } public static class Cluster { private final Refresh refresh = new Refresh(); public Refresh getRefresh() { return this.refresh; } public static class Refresh { /** * Whether to discover and query all cluster nodes for obtaining the * cluster topology. When set to false, only the initial seed nodes are * used as sources for topology discovery. */ private boolean dynamicRefreshSources = true; /** * Cluster topology refresh period.
*/ private @Nullable Duration period; /** * Whether adaptive topology refreshing using all available refresh * triggers should be used. */ private boolean adaptive; public boolean isDynamicRefreshSources() { return this.dynamicRefreshSources; } public void setDynamicRefreshSources(boolean dynamicRefreshSources) { this.dynamicRefreshSources = dynamicRefreshSources; } public @Nullable Duration getPeriod() { return this.period; } public void setPeriod(@Nullable Duration period) { this.period = period; } public boolean isAdaptive() { return this.adaptive; } public void setAdaptive(boolean adaptive) { this.adaptive = adaptive; } } } } }
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
2
请完成以下Java代码
public void setOwner(String taskId, String userId) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER, IdentityLinkType.OWNER)); } @Override public void addUserIdentityLink(String taskId, String userId, String identityLinkType) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, userId, AddIdentityLinkCmd.IDENTITY_USER, identityLinkType)); } @Override public void addGroupIdentityLink(String taskId, String groupId, String identityLinkType) { commandExecutor.execute(new AddIdentityLinkCmd(taskId, groupId, AddIdentityLinkCmd.IDENTITY_GROUP, identityLinkType)); } @Override public void deleteGroupIdentityLink(String taskId, String groupId, String identityLinkType) { commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, null, groupId, identityLinkType)); }
@Override public void deleteUserIdentityLink(String taskId, String userId, String identityLinkType) { commandExecutor.execute(new DeleteIdentityLinkCmd(taskId, userId, null, identityLinkType)); } @Override public List<IdentityLink> getIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetIdentityLinksForTaskCmd(taskId)); } @Override public TaskBuilder createTaskBuilder() { return new CmmnTaskBuilderImpl(commandExecutor, configuration); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnTaskServiceImpl.java
1
请完成以下Java代码
private CSVWriter createWriter() { final File outputFile; try { outputFile = File.createTempFile("Report_", ".csv"); } catch (final IOException ex) { throw new AdempiereException("Failed creating temporary CSV file", ex); } return CSVWriter.builder() .outputFile(outputFile) .header(getColumnHeadersTranslatedIfNeeded()) .adLanguage(adLanguage) .fieldDelimiter(fieldDelimiter) .build(); } @Override
public boolean isNoDataAddedYet() { return writer == null || writer.getLinesWrote() <= 0; } @Nullable public File getResultFile() { final File resultFile = writer != null ? writer.getOutputFile() : null; if (resultFile == null) { // shall not happen throw new AdempiereException(MSG_NoData); } return resultFile; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\csv\JdbcCSVExporter.java
1
请在Spring Boot框架中完成以下Java代码
public Integer getId() { return id; } public OrderDO setId(Integer id) { this.id = id; return this; } public Long getUserId() { return userId; } public OrderDO setUserId(Long userId) { this.userId = userId; return this; } public Long getProductId() { return productId; }
public OrderDO setProductId(Long productId) { this.productId = productId; return this; } public Integer getPayAmount() { return payAmount; } public OrderDO setPayAmount(Integer payAmount) { this.payAmount = payAmount; return this; } }
repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-order-service\src\main\java\cn\iocoder\springboot\lab52\orderservice\entity\OrderDO.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable DeliveryMode getDeliveryMode() { return this.deliveryMode; } public void setDeliveryMode(@Nullable DeliveryMode deliveryMode) { this.deliveryMode = deliveryMode; } public @Nullable Integer getPriority() { return this.priority; } public void setPriority(@Nullable Integer priority) { this.priority = priority; } public @Nullable Duration getTimeToLive() { return this.timeToLive; } public void setTimeToLive(@Nullable Duration timeToLive) { this.timeToLive = timeToLive; } public boolean determineQosEnabled() { if (this.qosEnabled != null) { return this.qosEnabled; } return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null); } public @Nullable Boolean getQosEnabled() { return this.qosEnabled; } public void setQosEnabled(@Nullable Boolean qosEnabled) { this.qosEnabled = qosEnabled; } public @Nullable Duration getReceiveTimeout() { return this.receiveTimeout; } public void setReceiveTimeout(@Nullable Duration receiveTimeout) { this.receiveTimeout = receiveTimeout; } public Session getSession() { return this.session; } public static class Session { /** * Acknowledge mode used when creating sessions. */ private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO; /** * Whether to use transacted sessions. */ private boolean transacted; public AcknowledgeMode getAcknowledgeMode() { return this.acknowledgeMode; } public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) { this.acknowledgeMode = acknowledgeMode; }
public boolean isTransacted() { return this.transacted; } public void setTransacted(boolean transacted) { this.transacted = transacted; } } } public enum DeliveryMode { /** * Does not require that the message be logged to stable storage. This is the * lowest-overhead delivery mode but can lead to lost of message if the broker * goes down. */ NON_PERSISTENT(1), /* * Instructs the JMS provider to log the message to stable storage as part of the * client's send operation. */ PERSISTENT(2); private final int value; DeliveryMode(int value) { this.value = value; } public int getValue() { return this.value; } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java
2
请完成以下Java代码
public static void setParameters(final PreparedStatement stmt, final List<?> params) throws SQLException { if (params == null || params.isEmpty()) { return; } for (int i = 0; i < params.size(); i++) { setParameter(stmt, i + 1, params.get(i)); } } public void close(final ResultSet rs) { if (rs != null) { try { rs.close(); } catch (final SQLException e) { logger.debug(e.getLocalizedMessage(), e); } } } public void close(final Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (final SQLException e) { logger.debug(e.getLocalizedMessage(), e); } } } public void close(final Connection conn) { if (conn != null) { try { conn.close(); } catch (final SQLException e) { logger.debug(e.getLocalizedMessage(), e); } } } public void close(final ResultSet rs, final PreparedStatement pstmt, final Connection conn) { close(rs); close(pstmt); close(conn); } public Set<String> getDBFunctionsMatchingPattern(final String functionNamePattern) {
ResultSet rs = null; try { final ImmutableSet.Builder<String> result = ImmutableSet.builder(); // // Fetch database functions close(rs); rs = database.getConnection() .getMetaData() .getFunctions(database.getDbName(), null, functionNamePattern); while (rs.next()) { final String functionName = rs.getString("FUNCTION_NAME"); final String schemaName = rs.getString("FUNCTION_SCHEM"); final String functionNameFQ = schemaName != null ? schemaName + "." + functionName : functionName; result.add(functionNameFQ); } // // Fetch database procedures // NOTE: after PostgreSQL 11 this will fetch nothing because our "after_import" routines are functions, // but we are keeping it for legacy purposes. // (see org.postgresql.jdbc.PgDatabaseMetaData.getProcedures) close(rs); rs = database.getConnection() .getMetaData() .getProcedures(database.getDbName(), null, functionNamePattern); while (rs.next()) { final String functionName = rs.getString("PROCEDURE_NAME"); final String schemaName = rs.getString("PROCEDURE_SCHEM"); final String functionNameFQ = schemaName != null ? schemaName + "." + functionName : functionName; result.add(functionNameFQ); } return result.build(); } catch (final SQLException ex) { logger.warn("Error while fetching functions for pattern {}. Considering no functions found.", functionNamePattern, ex); return ImmutableSet.of(); } finally { close(rs); } } @FunctionalInterface public static interface ResultSetRowLoader<T> { T loadRow(ResultSet rs) throws SQLException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLHelper.java
1
请完成以下Java代码
public void unpick(@NonNull final DDOrderMoveScheduleId scheduleId, @Nullable final HUQRCode unpickToTargetQRCode) { DDOrderUnpickCommand.builder() .ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository) .huqrCodesService(huqrCodesService) .scheduleId(scheduleId) .unpickToTargetQRCode(unpickToTargetQRCode) .build() .execute(); } public Set<DDOrderId> retrieveDDOrderIdsInTransit(@NonNull final LocatorId inTransitLocatorId) { return ddOrderMoveScheduleRepository.retrieveDDOrderIdsInTransit(inTransitLocatorId); }
public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId) { return ddOrderMoveScheduleRepository.queryInTransitSchedules(inTransitLocatorId).anyMatch(); } public void printMaterialInTransitReport( @NonNull final LocatorId inTransitLocatorId, @NonNull String adLanguage) { MaterialInTransitReportCommand.builder() .adLanguage(adLanguage) .inTransitLocatorId(inTransitLocatorId) .build() .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleService.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getTaxAmount() { return taxAmount; } /** * Sets the value of the taxAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxAmount(BigDecimal value) { this.taxAmount = value; } /** * Gets the value of the invoiceAmount property. * * @return * possible object is
* {@link BigDecimal } * */ public BigDecimal getInvoiceAmount() { return invoiceAmount; } /** * Sets the value of the invoiceAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setInvoiceAmount(BigDecimal value) { this.invoiceAmount = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\InvoiceFooterType.java
2
请在Spring Boot框架中完成以下Java代码
public class TransactionService { private static final Logger logger = LoggerFactory.getLogger(TransactionService.class); private final ConcurrentHashMap<UUID, List<Transaction>> processedTransactions = new ConcurrentHashMap<>(); private final Set<UUID> failedTransactions = ConcurrentHashMap.newKeySet(); public void processTransaction(Transaction transaction) { logger.info("Processing transaction: {}:{} for account {}", transaction.type(), transaction.amount(), transaction.accountId()); processedTransactions.computeIfAbsent(transaction.accountId(), k -> new ArrayList<>()) .add(transaction); } public List<Transaction> getProcessedTransactionsByAccount(UUID accountId) { return processedTransactions.getOrDefault(accountId, new ArrayList<>()); } public void simulateSlowProcessing(Transaction transaction) { try { processTransaction(transaction); Thread.sleep(Double.valueOf(500) .intValue());
logger.info("Transaction processing completed: {}:{} for account {}", transaction.type(), transaction.amount(), transaction.accountId()); } catch (InterruptedException e) { Thread.currentThread() .interrupt(); throw new RuntimeException(e); } } public void processTransactionWithFailure(Transaction transaction) { if (!failedTransactions.contains(transaction.transactionId())) { failedTransactions.add(transaction.transactionId()); throw new RuntimeException("Simulated failure for transaction " + transaction.type() + ":" + transaction.amount()); } processTransaction(transaction); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\fifo\service\TransactionService.java
2
请完成以下Java代码
public boolean isReceiptLineWithWrongLength(@NonNull final String v11LineStr) { if (!isReceiptLine(v11LineStr)) { return false; } return v11LineStr.length() != 87; } /** * If there is a problem extracting the amount, it logs an error message to {@link Loggables#get()}. * * @param esrImportLineText * @return */ public BigDecimal extractCtrlAmount(@NonNull final String esrImportLineText) { // set the control amount (from the control line) final String ctrlAmtStr = esrImportLineText.substring(39, 51); try { final BigDecimal controlAmount = new BigDecimal(ctrlAmtStr).divide(Env.ONEHUNDRED, 2, RoundingMode.UNNECESSARY); return controlAmount; } catch (NumberFormatException e) { Loggables.addLog(Services.get(IMsgBL.class).getMsg(Env.getCtx(), ERR_WRONG_CTRL_AMT, new Object[] { ctrlAmtStr })); return null; } } /**
* If there is a problem extracting the qty, it logs an error message to {@link Loggables#get()}. * * @param esrImportLineText * @return */ public BigDecimal extractCtrlQty(@NonNull final String esrImportLineText) { final String trxQtysStr = esrImportLineText.substring(51, 63); try { final BigDecimal controlTrxQty = new BigDecimal(trxQtysStr); return controlTrxQty; } catch (NumberFormatException e) { Loggables.addLog(Services.get(IMsgBL.class).getMsg(Env.getCtx(), ERR_WRONG_CTRL_QTY, new Object[] { trxQtysStr })); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\v11\ESRReceiptLineMatcherUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class CostSegmentAndElement { public static CostSegmentAndElement of( @NonNull final CostSegment costSegment, @NonNull final CostElementId costElementId) { return new CostSegmentAndElement(costSegment, costElementId); } @Getter(AccessLevel.PRIVATE) CostSegment costSegment; CostElementId costElementId; private CostSegmentAndElement( @NonNull final CostSegment costSegment, @NonNull final CostElementId costElementId) { this.costSegment = costSegment; this.costElementId = costElementId; } @Builder private CostSegmentAndElement( @NonNull final CostingLevel costingLevel, @NonNull final AcctSchemaId acctSchemaId, @NonNull final CostTypeId costTypeId, @NonNull final ClientId clientId, @NonNull final OrgId orgId, @NonNull final ProductId productId, @NonNull final AttributeSetInstanceId attributeSetInstanceId, @NonNull final CostElementId costElementId) { costSegment = CostSegment.builder() .costingLevel(costingLevel) .acctSchemaId(acctSchemaId) .costTypeId(costTypeId) .productId(productId) .clientId(clientId) .orgId(orgId) .attributeSetInstanceId(attributeSetInstanceId) .build(); this.costElementId = costElementId; } public CostSegmentAndElement withProductIdAndCostingLevel(final ProductId productId, final CostingLevel costingLevel) { return new CostSegmentAndElement( getCostSegment().withProductIdAndCostingLevel(productId, costingLevel), getCostElementId()); } public CostSegment toCostSegment()
{ return getCostSegment(); } public AcctSchemaId getAcctSchemaId() { return getCostSegment().getAcctSchemaId(); } public CostTypeId getCostTypeId() { return getCostSegment().getCostTypeId(); } public CostingLevel getCostingLevel() {return getCostSegment().getCostingLevel();} public ClientId getClientId() { return getCostSegment().getClientId(); } public OrgId getOrgId() { return getCostSegment().getOrgId(); } public ProductId getProductId() { return getCostSegment().getProductId(); } public AttributeSetInstanceId getAttributeSetInstanceId() { return getCostSegment().getAttributeSetInstanceId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostSegmentAndElement.java
2
请在Spring Boot框架中完成以下Java代码
public List<Job> findJobsByQueryCriteria(SuspendedJobQueryImpl jobQuery) { String query = "selectSuspendedJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery); } @Override public long findJobCountByQueryCriteria(SuspendedJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectSuspendedJobCountByQueryCriteria", jobQuery); } @Override public List<SuspendedJobEntity> findJobsByExecutionId(String executionId) { DbSqlSession dbSqlSession = getDbSqlSession(); // If the execution has been inserted in the same command execution as this query, there can't be any in the database if (isEntityInserted(dbSqlSession, "execution", executionId)) { return getListFromCache(suspendedJobsByExecutionIdMatcher, executionId); } return getList(dbSqlSession, "selectSuspendedJobsByExecutionId", executionId, suspendedJobsByExecutionIdMatcher, true); }
@Override @SuppressWarnings("unchecked") public List<SuspendedJobEntity> findJobsByProcessInstanceId(final String processInstanceId) { return getDbSqlSession().selectList("selectSuspendedJobsByProcessInstanceId", processInstanceId); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateSuspendedJobTenantIdForDeployment", params); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisSuspendedJobDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "10") public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @ApiModelProperty(example = "6") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-task-instances/6") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @ApiModelProperty(example = "variableUpdate") public String getDetailType() { return detailType; } public void setDetailType(String detailType) {
this.detailType = detailType; } @ApiModelProperty(example = "2") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public RestVariable getVariable() { return variable; } public void setVariable(RestVariable variable) { this.variable = variable; } @ApiModelProperty(example = "null") public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @ApiModelProperty(example = "null") public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java
2
请在Spring Boot框架中完成以下Java代码
public final class GraphQlRSocketAutoConfiguration { @Bean @ConditionalOnMissingBean GraphQlRSocketHandler graphQlRSocketHandler(ExecutionGraphQlService graphQlService, ObjectProvider<RSocketGraphQlInterceptor> interceptors, JsonEncoderSupplier jsonEncoderSupplier) { return new GraphQlRSocketHandler(graphQlService, interceptors.orderedStream().toList(), jsonEncoderSupplier.jsonEncoder()); } @Bean @ConditionalOnMissingBean GraphQlRSocketController graphQlRSocketController(GraphQlRSocketHandler handler) { return new GraphQlRSocketController(handler); } interface JsonEncoderSupplier { Encoder<?> jsonEncoder(); } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(JsonMapper.class) @ConditionalOnProperty(name = "spring.graphql.rsocket.preferred-json-mapper", havingValue = "jackson", matchIfMissing = true) static class JacksonJsonEncoderSupplierConfiguration { @Bean JsonEncoderSupplier jacksonJsonEncoderSupplier(JsonMapper jsonMapper) { return () -> new JacksonJsonEncoder(jsonMapper); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(ObjectMapper.class) @Conditional(NoJacksonOrJackson2Preferred.class) @Deprecated(since = "4.0.0", forRemoval = true) @SuppressWarnings("removal") static class Jackson2JsonEncoderSupplierConfiguration { @Bean
JsonEncoderSupplier jackson2JsonEncoderSupplier(ObjectMapper objectMapper) { return () -> new org.springframework.http.codec.json.Jackson2JsonEncoder(objectMapper); } } static class NoJacksonOrJackson2Preferred extends AnyNestedCondition { NoJacksonOrJackson2Preferred() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") static class NoJackson { } @ConditionalOnProperty(name = "spring.graphql.rsocket.preferred-json-mapper", havingValue = "jackson2") static class Jackson2Preferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\rsocket\GraphQlRSocketAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringBoot2JdbcWithH2Application implements CommandLineRunner { private final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); private final StudentJdbcTemplateRepository repository; private final StudentJdbcClientRepository jdbcClientRepository; public SpringBoot2JdbcWithH2Application (StudentJdbcTemplateRepository repository, StudentJdbcClientRepository jdbcClientRepository) { this.repository = repository; this.jdbcClientRepository = jdbcClientRepository; } public static void main(String[] args) { SpringApplication.run(SpringBoot2JdbcWithH2Application.class, args); } @Override public void run(String... args) { LOGGER.info("WITH JDBC TEMPLATE APPROACH..."); LOGGER.info("Student id 10001 -> {}", repository.findById(10001L)); LOGGER.info("Inserting -> {}", repository.insert(new Student(10010L, "John", "A1234657"))); LOGGER.info("Update 10003 -> {}", repository.update(new Student(10001L, "Name-Updated", "New-Passport"))); repository.deleteById(10002L);
LOGGER.info("All users -> {}", repository.findAll()); LOGGER.info("With Json format users -> {}", repository.findAll()); // repository.findAll().forEach(student -> System.out.println(student.toJSON())); LOGGER.info("WITH JDBC CLIENT APPROACH..."); LOGGER.info("Student id 10001 -> {}", jdbcClientRepository.findById(10001L)); LOGGER.info("Inserting -> {}", jdbcClientRepository.insert(new Student(10011L, "Ranga", "R1234657"))); LOGGER.info("Update 10011 -> {}", jdbcClientRepository.update(new Student(10011L, "Ranga Karanam", "New-Passport"))); jdbcClientRepository.deleteById(10002L); LOGGER.info("All users -> {}", jdbcClientRepository.findAll()); } }
repos\spring-boot-examples-master\spring-boot-2-jdbc-with-h2\src\main\java\com\in28minutes\springboot\jdbc\h2\example\SpringBoot2JdbcWithH2Application.java
2
请完成以下Java代码
public boolean addEvent(@NonNull final HUTraceEvent huTraceEvent) { final HUTraceEventQuery query = huTraceEvent.asQueryBuilder().build(); final List<HUTraceEvent> existingDbRecords = RetrieveDbRecordsUtil.query(query); final boolean inserted = existingDbRecords.isEmpty(); if (inserted) { final I_M_HU_Trace dbRecord = newInstance(I_M_HU_Trace.class); logger.debug("Found no existing M_HU_Trace record; creating new one; query={}", query); HuTraceEventToDbRecordUtil.copyToDbRecord(huTraceEvent, dbRecord); save(dbRecord); } else { Check.errorIf(existingDbRecords.size() > 1, "Expected only one M_HU_Trace record for the given query, but found {}; query={}, M_HU_Trace records={}", existingDbRecords.size(), query, existingDbRecords); HUTraceEvent existingHuTraceEvent = existingDbRecords.get(0); logger.debug("Found exiting HUTraceEvent record with ID={}; nothing to do; query={}", existingHuTraceEvent.getHuTraceEventId().getAsInt(), query); } return inserted; } /** * Return records according to the given specification.
* <p> * <b>Important:</b> if the specification is "empty", i.e. if it specifies no conditions, then return an empty list to prevent an {@code OutOfMemoryError}. */ public List<HUTraceEvent> query(@NonNull final HUTraceEventQuery query) { return RetrieveDbRecordsUtil.query(query); } /** * Similar to {@link #query(HUTraceEventQuery)}, but returns an ID that can be used with {@link IQueryBuilder#setOnlySelection(int)} to retrieve the query result. */ public PInstanceId queryToSelection(@NonNull final HUTraceEventQuery query) { return RetrieveDbRecordsUtil.queryToSelection(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\HUTraceRepository.java
1
请在Spring Boot框架中完成以下Java代码
public String getTransportDocumentNumber() { return transportDocumentNumber; } /** * Sets the value of the transportDocumentNumber property. * * @param value * allowed object is * {@link String } * */ public void setTransportDocumentNumber(String value) { this.transportDocumentNumber = value; } /** * Gets the value of the transportDocumentDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getTransportDocumentDate() { return transportDocumentDate; } /** * Sets the value of the transportDocumentDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setTransportDocumentDate(XMLGregorianCalendar value) { this.transportDocumentDate = value; } /** * Gets the value of the scac property.
* * @return * possible object is * {@link String } * */ public String getSCAC() { return scac; } /** * Sets the value of the scac property. * * @param value * allowed object is * {@link String } * */ public void setSCAC(String value) { this.scac = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ShipperExtensionType.java
2
请完成以下Java代码
public void setM_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_HU_PI) { set_ValueFromPO(COLUMNNAME_M_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_HU_PI); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Version.java
1
请完成以下Java代码
public static long convertString2Id(String idString) { long id; id = (idString.charAt(0) - 'A') * 26L * 10 * 10 * 26 * 10 * 10 + (idString.charAt(1) - 'a') * 10 * 10 * 26 * 10 * 10 + (idString.charAt(2) - '0') * 10 * 26 * 10 * 10 + (idString.charAt(3) - '0') * 26 * 10 * 10 + (idString.charAt(4) - 'A') * 10 * 10 + (idString.charAt(5) - '0') * 10 + (idString.charAt(6) - '0') ; // 编码等号前面的 return id; } public static String convertId2String(long id) { StringBuilder sbId = new StringBuilder(7); sbId.append((char)(id / (26 * 10 * 10 * 26 * 10 * 10) + 'A')); sbId.append((char)(id % (26 * 10 * 10 * 26 * 10 * 10) / (10 * 10 * 26 * 10 * 10) + 'a')); sbId.append((char)(id % (10 * 10 * 26 * 10 * 10) / (10 * 26 * 10 * 10) + '0')); sbId.append((char)(id % (10 * 26 * 10 * 10) / (26 * 10 * 10) + '0')); sbId.append((char)(id % (26 * 10 * 10) / (10 * 10) + 'A')); sbId.append((char)(id % (10 * 10) / (10) + '0')); sbId.append((char)(id % (10) / (1) + '0')); return sbId.toString(); } public static long convertString2IdWithIndex(String idString, long index) { long id = convertString2Id(idString); id = id * MAX_WORDS + index;
return id; } public static long convertString2IdWithIndex(String idString, int index) { return convertString2IdWithIndex(idString, (long) index); } public static String convertId2StringWithIndex(long id) { String idString = convertId2String(id / MAX_WORDS); long index = id % MAX_WORDS; return String.format("%s%0" + MAX_INDEX_LENGTH + "d", idString, index); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\synonym\SynonymHelper.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Integer getPort() { return this.port; } /** * Sets the port of the management server, use {@code null} if the * {@link ServerProperties#getPort() server port} should be used. Set to 0 to use a * random port or set to -1 to disable. * @param port the port */ public void setPort(@Nullable Integer port) { this.port = port; } public @Nullable InetAddress getAddress() { return this.address; } public void setAddress(@Nullable InetAddress address) { this.address = address; } public String getBasePath() { return this.basePath; } public void setBasePath(String basePath) { this.basePath = cleanBasePath(basePath); } public @Nullable Ssl getSsl() { return this.ssl; } public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; }
@Contract("!null -> !null") private @Nullable String cleanBasePath(@Nullable String basePath) { String candidate = null; if (StringUtils.hasLength(basePath)) { candidate = basePath.strip(); } if (StringUtils.hasText(candidate)) { if (!candidate.startsWith("/")) { candidate = "/" + candidate; } if (candidate.endsWith("/")) { candidate = candidate.substring(0, candidate.length() - 1); } } return candidate; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\web\server\ManagementServerProperties.java
2
请在Spring Boot框架中完成以下Java代码
public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the addinfo property. * * @return * possible object is * {@link String }
* */ public String getADDINFO() { return addinfo; } /** * Sets the value of the addinfo property. * * @param value * allowed object is * {@link String } * */ public void setADDINFO(String value) { this.addinfo = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DADDI1.java
2
请完成以下Java代码
public final class OAuth2ClientAuthenticationContext implements OAuth2AuthenticationContext { private final Map<Object, Object> context; private OAuth2ClientAuthenticationContext(Map<Object, Object> context) { this.context = Collections.unmodifiableMap(new HashMap<>(context)); } @SuppressWarnings("unchecked") @Nullable @Override public <V> V get(Object key) { return hasKey(key) ? (V) this.context.get(key) : null; } @Override public boolean hasKey(Object key) { Assert.notNull(key, "key cannot be null"); return this.context.containsKey(key); } /** * Returns the {@link RegisteredClient registered client}. * @return the {@link RegisteredClient} */ public RegisteredClient getRegisteredClient() { return get(RegisteredClient.class); } /** * Constructs a new {@link Builder} with the provided * {@link OAuth2ClientAuthenticationToken}. * @param authentication the {@link OAuth2ClientAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OAuth2ClientAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2ClientAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2ClientAuthenticationContext, Builder> { private Builder(OAuth2ClientAuthenticationToken authentication) { super(authentication); } /**
* Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration */ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); } /** * Builds a new {@link OAuth2ClientAuthenticationContext}. * @return the {@link OAuth2ClientAuthenticationContext} */ @Override public OAuth2ClientAuthenticationContext build() { Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); return new OAuth2ClientAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2ClientAuthenticationContext.java
1
请完成以下Java代码
protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); float stroke = 2f; double diameter = Math.min(getWidth(), getHeight()) - 12; // padding double x = (getWidth() - diameter) / 2.0; double y = (getHeight() - diameter) / 2.0; Ellipse2D circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.setColor(new Color(0xBBDEFB)); g2.fill(circle); g2.setColor(new Color(0x0D47A1)); g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g2.draw(circle); } finally { g2.dispose(); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame("Circle"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new DrawCircle()); f.setSize(320, 240); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\drawcircle\DrawCircle.java
1
请完成以下Java代码
public TypedValueSerializer<?> getSerializer() { return typedValueField.getSerializer(); } public String getErrorMessage() { return typedValueField.getErrorMessage(); } @Override public void setByteArrayId(String id) { byteArrayField.setByteArrayId(id); } @Override public String getSerializerName() { return typedValueField.getSerializerName(); } @Override public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getByteArrayValueId() { return byteArrayField.getByteArrayId(); } public byte[] getByteArrayValue() { return byteArrayField.getByteArrayValue(); } public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public String getName() { return getVariableName(); } // entity lifecycle ///////////////////////////////////////////////////////// public void postLoad() { // make sure the serializer is initialized typedValueField.postLoad(); } // getters and setters //////////////////////////////////////////////////////
public String getTypeName() { return typedValueField.getTypeName(); } public String getVariableTypeName() { return getTypeName(); } public Date getTime() { return timestamp; } @Override public String toString() { return this.getClass().getSimpleName() + "[variableName=" + variableName + ", variableInstanceId=" + variableInstanceId + ", revision=" + revision + ", serializerName=" + serializerName + ", longValue=" + longValue + ", doubleValue=" + doubleValue + ", textValue=" + textValue + ", textValue2=" + textValue2 + ", byteArrayId=" + byteArrayId + ", activityInstanceId=" + activityInstanceId + ", eventType=" + eventType + ", executionId=" + executionId + ", id=" + id + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntity.java
1
请完成以下Java代码
public void checkCycles(final ProductId productId) { try { assertNoCycles(productId); } catch (final BOMCycleException e) { final I_M_Product product = Services.get(IProductBL.class).getById(productId); throw new AdempiereException(ERR_PRODUCT_BOM_CYCLE, product.getValue()); } } private DefaultMutableTreeNode assertNoCycles(final ProductId productId) { final DefaultMutableTreeNode productNode = new DefaultMutableTreeNode(productId); final IProductBOMDAO productBOMDAO = Services.get(IProductBOMDAO.class); final List<I_PP_Product_BOMLine> productBOMLines = productBOMDAO.retrieveBOMLinesByComponentIdInTrx(productId); boolean first = true; for (final I_PP_Product_BOMLine productBOMLine : productBOMLines) { // Don't navigate the Co/ByProduct lines (gh480) if (isByOrCoProduct(productBOMLine)) { continue; } // If not the first bom line at this level if (!first) { clearSeenProducts(); markProductAsSeen(productId); } first = false; final DefaultMutableTreeNode bomNode = assertNoCycles(productBOMLine); if (bomNode != null) { productNode.add(bomNode); } } return productNode; } private static boolean isByOrCoProduct(final I_PP_Product_BOMLine bomLine) { final BOMComponentType componentType = BOMComponentType.ofCode(Objects.requireNonNull(bomLine.getComponentType())); return componentType.isByOrCoProduct(); } @Nullable private DefaultMutableTreeNode assertNoCycles(final I_PP_Product_BOMLine bomLine) { final I_PP_Product_BOM bom = bomLine.getPP_Product_BOM(); if (!bom.isActive()) { return null; }
// Check Child = Parent error final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID()); final ProductId parentProductId = ProductId.ofRepoId(bom.getM_Product_ID()); if (productId.equals(parentProductId)) { throw new BOMCycleException(bom, productId); } // Check BOM Loop Error if (!markProductAsSeen(parentProductId)) { throw new BOMCycleException(bom, parentProductId); } return assertNoCycles(parentProductId); } private void clearSeenProducts() { seenProductIds.clear(); } private boolean markProductAsSeen(final ProductId productId) { return seenProductIds.add(productId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMCycleDetection.java
1
请完成以下Java代码
public void addQtyOrderedAndResetQtyToOrder(final I_PMM_PurchaseCandidate candidate, final BigDecimal qtyOrdered, final BigDecimal qtyOrderedTU) { candidate.setQtyOrdered(candidate.getQtyOrdered().add(qtyOrdered)); candidate.setQtyOrdered_TU(candidate.getQtyOrdered_TU().add(qtyOrderedTU)); resetQtyToOrder(candidate); } @Override public void subtractQtyOrdered(final I_PMM_PurchaseCandidate candidate, final BigDecimal qtyOrdered, final BigDecimal qtyOrderedTU) { candidate.setQtyOrdered(candidate.getQtyOrdered().subtract(qtyOrdered)); candidate.setQtyOrdered_TU(candidate.getQtyOrdered_TU().subtract(qtyOrderedTU)); } @Override public void updateQtyToOrderFromQtyToOrderTU(final I_PMM_PurchaseCandidate candidate) { final I_M_HU_PI_Item_Product huPIItemProduct = getM_HU_PI_Item_Product_Effective(candidate); if (huPIItemProduct != null) { final BigDecimal qtyToOrderTU = candidate.getQtyToOrder_TU(); final BigDecimal tuCapacity = huPIItemProduct.getQty(); final BigDecimal qtyToOrder = qtyToOrderTU.multiply(tuCapacity); candidate.setQtyToOrder(qtyToOrder); } else { candidate.setQtyToOrder(candidate.getQtyToOrder_TU()); } } @Override public void resetQtyToOrder(I_PMM_PurchaseCandidate candidate) { candidate.setQtyToOrder(BigDecimal.ZERO); candidate.setQtyToOrder_TU(BigDecimal.ZERO); } @Override
public IPMMPricingAware asPMMPricingAware(final I_PMM_PurchaseCandidate candidate) { return PMMPricingAware_PurchaseCandidate.of(candidate); } @Override public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product_Effective(final I_PMM_PurchaseCandidate candidate) { final I_M_HU_PI_Item_Product hupipOverride = candidate.getM_HU_PI_Item_Product_Override(); if (hupipOverride != null) { // return M_HU_PI_Item_Product_Override if set return hupipOverride; } // return M_HU_PI_Item_Product return candidate.getM_HU_PI_Item_Product(); } @Override public int getM_HU_PI_Item_Product_Effective_ID(final I_PMM_PurchaseCandidate candidate) { final int hupipOverrideID = candidate.getM_HU_PI_Item_Product_Override_ID(); if (hupipOverrideID > 0) { // return M_HU_PI_Item_Product_Override if set return hupipOverrideID; } // return M_HU_PI_Item_Product return candidate.getM_HU_PI_Item_Product_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPurchaseCandidateBL.java
1
请在Spring Boot框架中完成以下Java代码
public String getMHUPackagingCodeText() { return mhuPackagingCodeText; } /** * Sets the value of the mhuPackagingCodeText property. * * @param value * allowed object is * {@link String } * */ public void setMHUPackagingCodeText(String value) { this.mhuPackagingCodeText = value; } /** * Gets the value of the ediExpDesadvPackItem 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 ediExpDesadvPackItem property.
* * <p> * For example, to add a new item, do as follows: * <pre> * getEDIExpDesadvPackItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EDIExpDesadvPackItemType } * * */ public List<EDIExpDesadvPackItemType> getEDIExpDesadvPackItem() { if (ediExpDesadvPackItem == null) { ediExpDesadvPackItem = new ArrayList<EDIExpDesadvPackItemType>(); } return this.ediExpDesadvPackItem; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackType.java
2
请完成以下Java代码
public class CallCenterValidator implements ModelValidator { public static final String ENTITYTYPE="de.metas.callcenter"; // private final Logger log = CLogMgt.getLogger(getClass()); private int m_AD_Client_ID = -1; //@Override public int getAD_Client_ID() { return m_AD_Client_ID; } //@Override public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) m_AD_Client_ID = client.getAD_Client_ID(); engine.addModelChange(X_R_Request.Table_Name, this); engine.addModelChange(X_R_Group.Table_Name, this); } //@Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null;
} //@Override public String modelChange(PO po, int type) throws Exception { if (po instanceof X_R_Request && type == TYPE_AFTER_NEW) { X_R_Request r = (X_R_Request)po; MRGroupProspect.linkRequest(r.getCtx(), r, r.get_TrxName()); } else if (po instanceof X_R_Group && (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE)) { X_R_Group bundle = (X_R_Group)po; BundleUtil.updateCCM_Bundle_Status(bundle); } return null; } //@Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\model\CallCenterValidator.java
1
请完成以下Java代码
public Set<String> getAllowedTrxNamePrefixes() { return allowedTrxNamePrefixesRO; } @Override public boolean isAllowTrxAfterThreadEnd() { return allowTrxAfterThreadEnd; } @Override public void reset() { setActive(DEFAULT_ACTIVE); setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END); setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS); setMaxTrx(DEFAULT_MAX_TRX); setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY); setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES); allowedTrxNamePrefixes.clear(); } @Override public String toString()
{ final StringBuilder sb = new StringBuilder(); sb.append("TrxConstraints["); sb.append("active=" + this.active); sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes()); sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd()); sb.append(", maxSavepoints=" + getMaxSavepoints()); sb.append(", maxTrx=" + getMaxTrx()); sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes()); sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly()); sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs()); sb.append("]"); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java
1
请在Spring Boot框架中完成以下Java代码
public CasAuthenticationFilter casAuthenticationFilter( AuthenticationManager authenticationManager, ServiceProperties serviceProperties) throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setAuthenticationManager(authenticationManager); filter.setServiceProperties(serviceProperties); return filter; } @Bean public ServiceProperties serviceProperties() { logger.info("service properties"); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService("http://localhost:8900/login/cas"); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public TicketValidator ticketValidator() { return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); } @Bean public CasUserDetailsService getUser(){ return new CasUserDetailsService(); } @Bean public CasAuthenticationProvider casAuthenticationProvider( TicketValidator ticketValidator, ServiceProperties serviceProperties) { CasAuthenticationProvider provider = new CasAuthenticationProvider(); provider.setServiceProperties(serviceProperties); provider.setTicketValidator(ticketValidator); provider.setUserDetailsService( s -> new User("casuser", "Mellon", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); //For Authentication with a Database-backed UserDetailsService //provider.setUserDetailsService(getUser()); provider.setKey("CAS_PROVIDER_LOCALHOST_8900");
return provider; } @Bean public SecurityContextLogoutHandler securityContextLogoutHandler() { return new SecurityContextLogoutHandler(); } @Bean public LogoutFilter logoutFilter() { LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/cas/logout", securityContextLogoutHandler()); logoutFilter.setFilterProcessesUrl("/logout/cas"); return logoutFilter; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } }
repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\java\com\baeldung\cassecuredapp\CasSecuredApplication.java
2
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getFullMessage() {
return fullMessage; } @Override public void setFullMessage(String fullMessage) { this.fullMessage = fullMessage; } @Override public String getAction() { return action; } @Override public void setAction(String action) { this.action = action; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\CommentEntityImpl.java
1
请完成以下Java代码
public static Server createBaseServer() { Server server = new Server(); // Adds a connector for port 80 with a timeout of 30 seconds. ServerConnector connector = new ServerConnector(server); connector.setPort(SERVER_PORT); connector.setHost("127.0.0.1"); connector.setIdleTimeout(30000); server.addConnector(connector); return server; } /** * Creates a server which delegates the request handling to a web * application. * * @return a server */ public static Server createWebAppServer() { // Adds an handler to a server and returns it. Server server = createBaseServer(); String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH); server.setHandler(webAppHandler); return server; } /** * Creates a server which delegates the request handling to both a logging
* handler and to a web application, in this order. * * @return a server */ public static Server createMultiHandlerServer() { Server server = createBaseServer(); // Creates the handlers and adds them to the server. HandlerCollection handlers = new HandlerCollection(); String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath(); Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH); handlers.addHandler(customRequestHandler); Handler loggingRequestHandler = new LoggingRequestHandler(); handlers.addHandler(loggingRequestHandler); server.setHandler(handlers); return server; } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\jetty\programmatic\JettyServerFactory.java
1
请完成以下Java代码
public ResponseEntity<Page<EmployeeDto>> getEmployeeData(Pageable pageable) { Page<EmployeeDto> employeeData = organisationService.getEmployeeData(pageable); return ResponseEntity.ok(employeeData); } @GetMapping("/data") public ResponseEntity<Page<EmployeeDto>> getData(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { List<EmployeeDto> empList = listImplementation(); int totalSize = empList.size(); int startIndex = page * size; int endIndex = Math.min(startIndex + size, totalSize); List<EmployeeDto> pageContent = empList.subList(startIndex, endIndex);
Page<EmployeeDto> employeeDtos = new PageImpl<>(pageContent, PageRequest.of(page, size), totalSize); return ResponseEntity.ok() .body(employeeDtos); } private static List<EmployeeDto> listImplementation() { List<EmployeeDto> empList = new ArrayList<>(); empList.add(new EmployeeDto("Jane", "Finance", 50000)); empList.add(new EmployeeDto("Sarah", "IT", 70000)); empList.add(new EmployeeDto("John", "IT", 90000)); return empList; } }
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\pageentityresponse\EmployeeController.java
1
请完成以下Java代码
public class TeamsAdaptiveCard { private String type = "message"; private List<Attachment> attachments; @Data @NoArgsConstructor @AllArgsConstructor public static class Attachment { private String contentType = "application/vnd.microsoft.card.adaptive"; private AdaptiveCard content; } @Data @NoArgsConstructor @AllArgsConstructor public static class AdaptiveCard { @JsonProperty("$schema") private final String schema = "http://adaptivecards.io/schemas/adaptive-card.json"; private final String type = "AdaptiveCard"; private BackgroundImage backgroundImage; @JsonProperty("body") private List<TextBlock> textBlocks = new ArrayList<>(); private List<ActionOpenUrl> actions = new ArrayList<>(); } @Data @NoArgsConstructor public static class BackgroundImage { private String url; private final String fillMode = "repeat"; public BackgroundImage(String color) {
// This is the only one way how to specify color the custom color for the card url = ImageUtils.getEmbeddedBase64EncodedImg(color); } } @Data @NoArgsConstructor @AllArgsConstructor public static class TextBlock { private final String type = "TextBlock"; private String text; private String weight = "Normal"; private String size = "Medium"; private String spacing = "None"; private String color = "#FFFFFF"; private final boolean wrap = true; } @Data @NoArgsConstructor @AllArgsConstructor public static class ActionOpenUrl { private final String type = "Action.OpenUrl"; private String title; private String url; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsAdaptiveCard.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<ToDo> findById(Long aLong) { return Optional.empty(); } @Override public boolean existsById(Long aLong) { return false; } @Override public void flush() { } @Override public <S extends ToDo> S saveAndFlush(S s) { return null; } @Override public void deleteInBatch(Iterable<ToDo> iterable) { } @Override public void deleteAllInBatch() { } @Override public ToDo getOne(Long aLong) { return null; } @Override public <S extends ToDo> Optional<S> findOne(Example<S> example) { return Optional.empty();
} @Override public <S extends ToDo> List<S> findAll(Example<S> example) { return null; } @Override public <S extends ToDo> List<S> findAll(Example<S> example, Sort sort) { return null; } @Override public <S extends ToDo> Page<S> findAll(Example<S> example, Pageable pageable) { return null; } @Override public <S extends ToDo> long count(Example<S> example) { return 0; } @Override public <S extends ToDo> boolean exists(Example<S> example) { return false; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\3.TodoProjectDB\src\main\java\spring\project\repository\LogicRepository.java
2
请完成以下Java代码
public void deleteDomainById(TenantId tenantId, DomainId domainId) { log.trace("Executing deleteDomainById [{}]", domainId.getId()); domainDao.removeById(tenantId, domainId.getId()); eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(domainId).build()); } @Override public Domain findDomainById(TenantId tenantId, DomainId domainId) { log.trace("Executing findDomainInfo [{}] [{}]", tenantId, domainId); return domainDao.findById(tenantId, domainId.getId()); } @Override public PageData<DomainInfo> findDomainInfosByTenantId(TenantId tenantId, PageLink pageLink) { log.trace("Executing findDomainInfosByTenantId [{}]", tenantId); PageData<Domain> domains = domainDao.findByTenantId(tenantId, pageLink); return domains.mapData(this::getDomainInfo); } @Override public DomainInfo findDomainInfoById(TenantId tenantId, DomainId domainId) { log.trace("Executing findDomainInfoById [{}] [{}]", tenantId, domainId); Domain domain = domainDao.findById(tenantId, domainId.getId()); return getDomainInfo(domain); } @Override public boolean isOauth2Enabled(TenantId tenantId) { log.trace("Executing isOauth2Enabled [{}] ", tenantId); return domainDao.countDomainByTenantIdAndOauth2Enabled(tenantId, true) > 0; } @Override public void deleteDomainsByTenantId(TenantId tenantId) { log.trace("Executing deleteDomainsByTenantId, tenantId [{}]", tenantId); domainDao.deleteByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) {
deleteDomainsByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findDomainById(tenantId, new DomainId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(domainDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override @Transactional public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteDomainById(tenantId, (DomainId) id); } private DomainInfo getDomainInfo(Domain domain) { if (domain == null) { return null; } List<OAuth2ClientInfo> clients = oauth2ClientDao.findByDomainId(domain.getUuidId()).stream() .map(OAuth2ClientInfo::new) .sorted(Comparator.comparing(OAuth2ClientInfo::getTitle)) .collect(Collectors.toList()); return new DomainInfo(domain, clients); } @Override public EntityType getEntityType() { return EntityType.DOMAIN; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\domain\DomainServiceImpl.java
1
请完成以下Java代码
public class GenConfig implements Serializable { public GenConfig(String tableName) { this.tableName = tableName; } @Id @Column(name = "config_id") @ApiModelProperty(value = "ID", hidden = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @ApiModelProperty(value = "表名") private String tableName; @ApiModelProperty(value = "接口名称") private String apiAlias; @NotBlank @ApiModelProperty(value = "包路径") private String pack;
@NotBlank @ApiModelProperty(value = "模块名") private String moduleName; @NotBlank @ApiModelProperty(value = "前端文件路径") private String path; @ApiModelProperty(value = "前端文件路径") private String apiPath; @ApiModelProperty(value = "作者") private String author; @ApiModelProperty(value = "表前缀") private String prefix; @ApiModelProperty(value = "是否覆盖") private Boolean cover = false; }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\domain\GenConfig.java
1
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_Value (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setRoutingNo (final @Nullable java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } @Override public void setStatementDate (final @Nullable java.sql.Timestamp StatementDate) { set_Value (COLUMNNAME_StatementDate, StatementDate); } @Override public java.sql.Timestamp getStatementDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementDate); } @Override public void setStatementLineDate (final @Nullable java.sql.Timestamp StatementLineDate) { set_Value (COLUMNNAME_StatementLineDate, StatementLineDate); } @Override public java.sql.Timestamp getStatementLineDate() { return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate); } @Override public void setStmtAmt (final @Nullable BigDecimal StmtAmt) { set_Value (COLUMNNAME_StmtAmt, StmtAmt); } @Override public BigDecimal getStmtAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setTrxAmt (final @Nullable BigDecimal TrxAmt) { set_Value (COLUMNNAME_TrxAmt, TrxAmt); } @Override public BigDecimal getTrxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Sales = S */ public static final String TRXTYPE_Sales = "S"; /** DelayedCapture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** CreditPayment = C */ public static final String TRXTYPE_CreditPayment = "C"; /** VoiceAuthorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F"; /** Authorization = A */ public static final String TRXTYPE_Authorization = "A"; /** Void = V */ public static final String TRXTYPE_Void = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; @Override public void setTrxType (final @Nullable java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate) { set_Value (COLUMNNAME_ValutaDate, ValutaDate); } @Override public java.sql.Timestamp getValutaDate() { return get_ValueAsTimestamp(COLUMNNAME_ValutaDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java
1
请在Spring Boot框架中完成以下Java代码
protected EventSubscriptionServiceConfiguration getService() { return this; } // init // ///////////////////////////////////////////////////////////////////// public void init() { configuratorsBeforeInit(); initDataManagers(); initEntityManagers(); configuratorsAfterInit(); } // Data managers /////////////////////////////////////////////////////////// public void initDataManagers() { if (eventSubscriptionDataManager == null) { eventSubscriptionDataManager = new MybatisEventSubscriptionDataManager(this); } } public void initEntityManagers() { if (eventSubscriptionEntityManager == null) { eventSubscriptionEntityManager = new EventSubscriptionEntityManagerImpl(this, eventSubscriptionDataManager); } } // getters and setters // ////////////////////////////////////////////////////// public EventSubscriptionServiceConfiguration getIdentityLinkServiceConfiguration() { return this; } public EventSubscriptionService getEventSubscriptionService() { return eventSubscriptionService; } public EventSubscriptionServiceConfiguration setEventSubscriptionService(EventSubscriptionService eventSubscriptionService) { this.eventSubscriptionService = eventSubscriptionService; return this; } public EventSubscriptionDataManager getEventSubscriptionDataManager() { return eventSubscriptionDataManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionDataManager(EventSubscriptionDataManager eventSubscriptionDataManager) { this.eventSubscriptionDataManager = eventSubscriptionDataManager; return this; }
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return eventSubscriptionEntityManager; } public EventSubscriptionServiceConfiguration setEventSubscriptionEntityManager(EventSubscriptionEntityManager eventSubscriptionEntityManager) { this.eventSubscriptionEntityManager = eventSubscriptionEntityManager; return this; } @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public EventSubscriptionServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public Duration getEventSubscriptionLockTime() { return eventSubscriptionLockTime; } public EventSubscriptionServiceConfiguration setEventSubscriptionLockTime(Duration eventSubscriptionLockTime) { this.eventSubscriptionLockTime = eventSubscriptionLockTime; return this; } public String getLockOwner() { return lockOwner; } public EventSubscriptionServiceConfiguration setLockOwner(String lockOwner) { this.lockOwner = lockOwner; return this; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\EventSubscriptionServiceConfiguration.java
2
请完成以下Java代码
public class DepartmentResource { @Context private Configuration config; @GET public DataResponse<Department> getAll(@Context UriInfo uriInfo) { return LinkRest.select(Department.class, config).uri(uriInfo).get(); } @GET @Path("{id}") public DataResponse<Department> getOne(@PathParam("id") int id, @Context UriInfo uriInfo) { return LinkRest.select(Department.class, config).byId(id).uri(uriInfo).getOne(); } @POST public SimpleResponse create(String data) { return LinkRest.create(Department.class, config).sync(data);
} @PUT public SimpleResponse createOrUpdate(String data) { return LinkRest.createOrUpdate(Department.class, config).sync(data); } @Path("{id}/employees") public EmployeeSubResource getEmployees(@PathParam("id") int id, @Context UriInfo uriInfo) { return new EmployeeSubResource(id, config); } @DELETE @Path("{id}") public SimpleResponse delete(@PathParam("id") int id) { return LinkRest.delete(Department.class, config).id(id).delete(); } }
repos\tutorials-master\web-modules\linkrest\src\main\java\com\baeldung\linkrest\apis\DepartmentResource.java
1
请完成以下Java代码
public boolean isRequireTrolley() { return get_ValueAsBoolean(COLUMNNAME_IsRequireTrolley); } @Override public void setMaxLaunchers (final int MaxLaunchers) { set_Value (COLUMNNAME_MaxLaunchers, MaxLaunchers); } @Override public int getMaxLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxLaunchers); } @Override public void setMaxStartedLaunchers (final int MaxStartedLaunchers) { set_Value (COLUMNNAME_MaxStartedLaunchers, MaxStartedLaunchers); }
@Override public int getMaxStartedLaunchers() { return get_ValueAsInt(COLUMNNAME_MaxStartedLaunchers); } @Override public void setMobileUI_UserProfile_DD_ID (final int MobileUI_UserProfile_DD_ID) { if (MobileUI_UserProfile_DD_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_DD_ID, MobileUI_UserProfile_DD_ID); } @Override public int getMobileUI_UserProfile_DD_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_DD_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_DD.java
1
请完成以下Java代码
public DisplayMode getDisplayMode(final JSONViewDataType viewType) { final ClassViewColumnLayoutDescriptor layout = layoutsByViewType.get(viewType); return layout != null ? layout.getDisplayMode() : DisplayMode.HIDDEN; } public int getSeqNo(final JSONViewDataType viewType) { final ClassViewColumnLayoutDescriptor layout = layoutsByViewType.get(viewType); if (layout == null) { return Integer.MAX_VALUE; } final int seqNo = layout.getSeqNo(); return seqNo >= 0 ? seqNo : Integer.MAX_VALUE; } public Field getField() { return fieldReference.getField(); } public boolean isSupportZoomInto() {return allowZoomInfo && widgetType.isSupportZoomInto();} } @Getter private enum DisplayMode
{ DISPLAYED(true, false), HIDDEN(false, false), DISPLAYED_BY_SYSCONFIG(true, true), HIDDEN_BY_SYSCONFIG(false, true), ; private final boolean displayed; private final boolean configuredBySysConfig; DisplayMode(final boolean displayed, final boolean configuredBySysConfig) { this.displayed = displayed; this.configuredBySysConfig = configuredBySysConfig; } } @Value @Builder private static class ClassViewColumnLayoutDescriptor { @NonNull JSONViewDataType viewType; DisplayMode displayMode; int seqNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\annotation\ViewColumnHelper.java
1
请在Spring Boot框架中完成以下Java代码
public List<FieldInfo> processJsonObjectToFieldList(JSONObject jsonObject) { // field List List<FieldInfo> fieldList = new ArrayList<FieldInfo>(); for (String jsonField : jsonObject.keySet()) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setFieldName(jsonField); fieldInfo.setColumnName(jsonField); fieldInfo.setFieldClass(String.class.getSimpleName()); fieldInfo.setFieldComment("father:" + jsonField); fieldList.add(fieldInfo); if (jsonObject.get(jsonField) instanceof JSONArray) { JSONArray jsonArray = jsonObject.getJSONArray(jsonField); for (Object arrayObject : jsonArray) { FieldInfo fieldInfo2 = new FieldInfo(); fieldInfo2.setFieldName(arrayObject.toString()); fieldInfo2.setColumnName(arrayObject.toString()); fieldInfo2.setFieldClass(String.class.getSimpleName()); fieldInfo2.setFieldComment("children:" + arrayObject.toString()); fieldList.add(fieldInfo2); } } else if (jsonObject.get(jsonField) instanceof JSONObject) { JSONObject subJsonObject = jsonObject.getJSONObject(jsonField); for (String arrayObject : subJsonObject.keySet()) {
FieldInfo fieldInfo2 = new FieldInfo(); fieldInfo2.setFieldName(arrayObject.toString()); fieldInfo2.setColumnName(arrayObject.toString()); fieldInfo2.setFieldClass(String.class.getSimpleName()); fieldInfo2.setFieldComment("children:" + arrayObject.toString()); fieldList.add(fieldInfo2); } } } if (fieldList.size() < 1) { throw new CodeGenException("JSON解析失败"); } return fieldList; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\service\impl\parser\JsonParserServiceImpl.java
2
请完成以下Java代码
public int getC_CurrencyTo_ID() { if (m_C_CurrencyTo_ID == 0) { m_C_CurrencyTo_ID = getParent().getC_Currency_ID(); } return m_C_CurrencyTo_ID; } // getC_CurrencyTo_ID /** * Before Save * * @param newRecord new * @return true */ @Override protected boolean beforeSave(boolean newRecord) { // Set Amt if (getC_Invoice_ID() == 0 && getC_Payment_ID() == 0) { setAmt(BigDecimal.ZERO); setOpenAmt(BigDecimal.ZERO); } // Converted Amt if (BigDecimal.ZERO.compareTo(getOpenAmt()) == 0) { setConvertedAmt(BigDecimal.ZERO); } else if (BigDecimal.ZERO.compareTo(getConvertedAmt()) == 0) { setConvertedAmt(computeConvertedAmt()); } // Total setTotalAmt(getConvertedAmt().add(getFeeAmt()).add(getInterestAmt())); // Set Collection Status if (isProcessed() && getInvoice() != null) { I_C_DunningLevel level = getParent().getC_DunningLevel(); if (level != null) { getInvoice().setC_DunningLevel_ID(level.getC_DunningLevel_ID()); if (level.getInvoiceCollectionType() != null) { getInvoice().setInvoiceCollectionType(level.getInvoiceCollectionType()); } else { if (!level.isStatement()) { getInvoice().setInvoiceCollectionType(MInvoice.INVOICECOLLECTIONTYPE_Dunning); } } getInvoice().saveEx(); } } return true; } // beforeSave private BigDecimal computeConvertedAmt() { return Services.get(ICurrencyBL.class).convert( getOpenAmt(), CurrencyId.ofRepoId(getC_CurrencyFrom_ID()), CurrencyId.ofRepoId(getC_CurrencyTo_ID()), ClientId.ofRepoId(getAD_Client_ID()), OrgId.ofRepoId(getAD_Org_ID())); } /** * After Save * * @param newRecord new * @param success success * @return success */
@Override protected boolean afterSave(boolean newRecord, boolean success) { updateEntry(); return success; } // afterSave /** * After Delete * * @param success success * @return success */ @Override protected boolean afterDelete(boolean success) { updateEntry(); return success; } // afterDelete /** * Update Entry. * Calculate/update Amt/Qty */ private void updateEntry() { // we do not count the fee line as an item, but it sum it up. String sql = "UPDATE C_DunningRunEntry e " + "SET Amt=COALESCE((SELECT SUM(ConvertedAmt)+SUM(FeeAmt)+SUM(InterestAmt)" + " FROM C_DunningRunLine l " + "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID), 0), " + "QTY=(SELECT COUNT(*)" + " FROM C_DunningRunLine l " + "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID " + " AND (NOT C_Invoice_ID IS NULL OR NOT C_Payment_ID IS NULL))" + " WHERE C_DunningRunEntry_ID=" + getC_DunningRunEntry_ID(); DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); } // updateEntry } // MDunningRunLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRunLine.java
1
请完成以下Java代码
public static Consumer<Map<String, Object>> principal(Authentication principal) { Assert.notNull(principal, "principal cannot be null"); return (attributes) -> attributes.put(PRINCIPAL_ATTR_NAME, principal); } /** * Modifies the {@link ClientHttpRequest#getAttributes() attributes} to include the * {@link Authentication principal} to be used to look up the * {@link OAuth2AuthorizedClient}. * @param principalName the {@code principalName} to be used to look up the * {@link OAuth2AuthorizedClient} * @return the {@link Consumer} to populate the attributes */ public static Consumer<Map<String, Object>> principal(String principalName) { Assert.hasText(principalName, "principalName cannot be empty"); Authentication principal = createAuthentication(principalName); return (attributes) -> attributes.put(PRINCIPAL_ATTR_NAME, principal); }
private static Authentication createAuthentication(String principalName) { return new AbstractAuthenticationToken(Collections.emptySet()) { @Override public Object getPrincipal() { return principalName; } @Override public Object getCredentials() { return null; } }; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\client\RequestAttributePrincipalResolver.java
1
请完成以下Java代码
public int getAD_Scheduler_ID() { return get_ValueAsInt(COLUMNNAME_AD_Scheduler_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 setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public org.compiere.model.I_AD_Window getAD_Window() { return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class); } @Override public void setAD_Window(final org.compiere.model.I_AD_Window AD_Window) { set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window); } @Override public void setAD_Window_ID (final int AD_Window_ID) { if (AD_Window_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Window_ID, AD_Window_ID); } @Override public int getAD_Window_ID() { return get_ValueAsInt(COLUMNNAME_AD_Window_ID); } @Override public void setErrorMsg (final @Nullable java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override
public java.lang.String getErrorMsg() { return get_ValueAsString(COLUMNNAME_ErrorMsg); } @Override public void setIsProcessing (final boolean IsProcessing) { set_Value (COLUMNNAME_IsProcessing, IsProcessing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_IsProcessing); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setResult (final int Result) { set_Value (COLUMNNAME_Result, Result); } @Override public int getResult() { return get_ValueAsInt(COLUMNNAME_Result); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance.java
1
请完成以下Java代码
default byte[] getListenerInfo() { throw new UnsupportedOperationException("This container does not support retrieving the listener info"); } /** * If this container has child containers, return true if at least one child is running. If there are not * child containers, returns {@link #isRunning()}. * @return true if a child is running. * @since 2.7.3 */ default boolean isChildRunning() { return isRunning(); } /** * Return true if the container is running, has never been started, or has been * stopped. * @return true if the state is as expected. * @since 2.8 * @see #stopAbnormally(Runnable) */ default boolean isInExpectedState() { return true; } /** * Stop the container after some exception so that {@link #isInExpectedState()} will * return false. * @param callback the callback. * @since 2.8 * @see #isInExpectedState() */ default void stopAbnormally(Runnable callback) { stop(callback); } /** * If this container has child containers, return the child container that is assigned * the topic/partition. Return this when there are no child containers.
* @param topic the topic. * @param partition the partition. * @return the container. */ default MessageListenerContainer getContainerFor(String topic, int partition) { return this; } /** * Notify a parent container that a child container has stopped. * @param child the container. * @param reason the reason. * @since 2.9.7 */ default void childStopped(MessageListenerContainer child, ConsumerStoppedEvent.Reason reason) { } /** * Notify a parent container that a child container has started. * @param child the container. * @since 3.3 */ default void childStarted(MessageListenerContainer child) { } @Override default void destroy() { stop(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\MessageListenerContainer.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONPatchEvent<PathType> { @Schema(description = "operation") public static enum JSONOperation { replace; } @JsonProperty("op") private final JSONOperation op; @JsonProperty("path") private final PathType path; @JsonProperty("value") private final Object value; private JSONPatchEvent( @JsonProperty("op") final JSONOperation op, @JsonProperty("path") final PathType path, @JsonProperty("value") final Object value) { this.op = op; this.path = path; this.value = value; } public boolean isReplace() { return op == JSONOperation.replace; } public String getValueAsString() { return value != null ? value.toString() : null; } public Boolean getValueAsBoolean(final Boolean defaultValue) { return DisplayType.toBoolean(value, defaultValue); } public int getValueAsInteger(final int defaultValueIfNull) { if (value == null) { return defaultValueIfNull; } else if (value instanceof Number) { return ((Number)value).intValue(); } else { return Integer.parseInt(value.toString()); } } public List<Integer> getValueAsIntegersList() { if (value == null) { return ImmutableList.of(); } if (value instanceof List<?>) {
@SuppressWarnings("unchecked") final List<Integer> intList = (List<Integer>)value; return intList; } else if (value instanceof String) { return ImmutableList.copyOf(DocumentIdsSelection.ofCommaSeparatedString(value.toString()).toIntSet()); } else { throw new AdempiereException("Cannot convert value to int list").setParameter("event", this); } } public <ET extends Enum<ET>> ET getValueAsEnum(final Class<ET> enumType) { if (value == null) { return null; } if (enumType.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") final ET valueConv = (ET)value; return valueConv; } else if (value instanceof String) { return Enum.valueOf(enumType, value.toString()); } else { throw new AdempiereException("Cannot convert value " + value + " to " + enumType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONPatchEvent.java
2
请完成以下Java代码
public final class ElementPermissions extends AbstractPermissions<ElementPermission> { public static Builder builder() { return new Builder(); } private final String elementTableName; public ElementPermissions(final Builder builder) { super(builder); this.elementTableName = builder.getElementTableName(); } public Builder asNewBuilder() { final Builder builder = builder(); builder.setElementTableName(elementTableName); builder.addPermissions(this, CollisionPolicy.Override); return builder; } /** * @return element permissions; never return null */ public ElementPermission getPermission(final int elementId) { final ElementResource resource = elementResource(elementId); final ElementPermission permission = getPermissionOrDefault(resource); return permission != null ? permission : ElementPermission.none(resource); } public ElementResource elementResource(final int elementId) { return ElementResource.of(elementTableName, elementId); } public ElementPermission noPermissions(final int elementId) { return ElementPermission.none(elementResource(elementId)); } public static class Builder extends PermissionsBuilder<ElementPermission, ElementPermissions> {
private String elementTableName; @Override protected ElementPermissions createPermissionsInstance() { return new ElementPermissions(this); } public Builder setElementTableName(final String elementTableName) { this.elementTableName = elementTableName; return this; } public String getElementTableName() { Check.assumeNotEmpty(elementTableName, "elementTableName not empty"); return elementTableName; } @Override protected void assertValidPermissionToAdd(final ElementPermission permission) { final String elementTableName = getElementTableName(); if (!Objects.equals(elementTableName, permission.getResource().getElementTableName())) { throw new IllegalArgumentException("Permission to add " + permission + " is not matching element table name '" + elementTableName + "'"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermissions.java
1
请完成以下Java代码
public class ADProcessADValidator extends AbstractADValidator<I_AD_Process> { @Override public void validate(@NonNull final I_AD_Process process) { String classname = process.getClassname(); if (Check.isBlank(classname)) { return; } classname = classname.trim(); // Skip @script references if (classname.startsWith("@script")) { return; } Util.validateJavaClassname(process.getClassname(), JavaProcess.class); } @Override public String getLogMessage(final IADValidatorViolation violation) { final StringBuilder message = new StringBuilder(); try { final I_AD_Process process = InterfaceWrapperHelper.create(violation.getItem(), I_AD_Process.class);
message.append("Error on ").append(process).append(" (IsActive=").append(process.isActive()).append("): "); } catch (final Exception e) { message.append("Error (InterfaceWrapperHelper exception: ").append(e.getLocalizedMessage()).append(") on ").append(violation.getItem()).append(": "); } message.append(violation.getError().getLocalizedMessage()); return message.toString(); } @Override public Class<I_AD_Process> getType() { return I_AD_Process.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\spi\impl\ADProcessADValidator.java
1
请完成以下Java代码
public String getDescription() { return this.description; } public String getTelephoneNumber() { return this.telephoneNumber; } protected void populateContext(DirContextAdapter adapter) { adapter.setAttributeValue("givenName", this.givenName); adapter.setAttributeValue("sn", this.sn); adapter.setAttributeValues("cn", getCn()); adapter.setAttributeValue("description", getDescription()); adapter.setAttributeValue("telephoneNumber", getTelephoneNumber()); if (getPassword() != null) { adapter.setAttributeValue("userPassword", getPassword()); } adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); } public static class Essence extends LdapUserDetailsImpl.Essence { public Essence() { } public Essence(DirContextOperations ctx) { super(ctx); setCn(ctx.getStringAttributes("cn")); setGivenName(ctx.getStringAttribute("givenName")); setSn(ctx.getStringAttribute("sn")); setDescription(ctx.getStringAttribute("description")); setTelephoneNumber(ctx.getStringAttribute("telephoneNumber")); Object password = ctx.getObjectAttribute("userPassword"); if (password != null) { setPassword(LdapUtils.convertPasswordToString(password)); } } public Essence(Person copyMe) { super(copyMe); setGivenName(copyMe.givenName); setSn(copyMe.sn); setDescription(copyMe.getDescription()); setTelephoneNumber(copyMe.getTelephoneNumber()); ((Person) this.instance).cn = new ArrayList<>(copyMe.cn); } @Override protected LdapUserDetailsImpl createTarget() { return new Person(); } public void setGivenName(String givenName) { ((Person) this.instance).givenName = givenName; } public void setSn(String sn) { ((Person) this.instance).sn = sn; }
public void setCn(String[] cn) { ((Person) this.instance).cn = Arrays.asList(cn); } public void addCn(String value) { ((Person) this.instance).cn.add(value); } public void setTelephoneNumber(String tel) { ((Person) this.instance).telephoneNumber = tel; } public void setDescription(String desc) { ((Person) this.instance).description = desc; } @Override public LdapUserDetails createUserDetails() { Person p = (Person) super.createUserDetails(); Assert.notNull(p.cn, "person.sn cannot be null"); Assert.notEmpty(p.cn, "person.cn cannot be empty"); // TODO: Check contents for null entries return p; } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\Person.java
1
请在Spring Boot框架中完成以下Java代码
public class FilterServiceImpl extends ServiceImpl implements FilterService { public Filter newTaskFilter() { return commandExecutor.execute(new CreateFilterCmd(EntityTypes.TASK)); } public Filter newTaskFilter(String filterName) { return newTaskFilter().setName(filterName); } public FilterQuery createFilterQuery() { return new FilterQueryImpl(commandExecutor); } public FilterQuery createTaskFilterQuery() { return new FilterQueryImpl(commandExecutor).filterResourceType(EntityTypes.TASK); } public Filter saveFilter(Filter filter) { return commandExecutor.execute(new SaveFilterCmd(filter)); } public Filter getFilter(String filterId) { return commandExecutor.execute(new GetFilterCmd(filterId)); } public void deleteFilter(String filterId) { commandExecutor.execute(new DeleteFilterCmd(filterId)); } @SuppressWarnings("unchecked") public <T> List<T> list(String filterId) { return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId)); } @SuppressWarnings("unchecked") public <T, Q extends Query<?, T>> List<T> list(String filterId, Q extendingQuery) { return (List<T>) commandExecutor.execute(new ExecuteFilterListCmd(filterId, extendingQuery)); } @SuppressWarnings("unchecked") public <T> List<T> listPage(String filterId, int firstResult, int maxResults) { return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, firstResult, maxResults)); } @SuppressWarnings("unchecked")
public <T, Q extends Query<?, T>> List<T> listPage(String filterId, Q extendingQuery, int firstResult, int maxResults) { return (List<T>) commandExecutor.execute(new ExecuteFilterListPageCmd(filterId, extendingQuery, firstResult, maxResults)); } @SuppressWarnings("unchecked") public <T> T singleResult(String filterId) { return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId)); } @SuppressWarnings("unchecked") public <T, Q extends Query<?, T>> T singleResult(String filterId, Q extendingQuery) { return (T) commandExecutor.execute(new ExecuteFilterSingleResultCmd(filterId, extendingQuery)); } public Long count(String filterId) { return commandExecutor.execute(new ExecuteFilterCountCmd(filterId)); } public Long count(String filterId, Query<?, ?> extendingQuery) { return commandExecutor.execute(new ExecuteFilterCountCmd(filterId, extendingQuery)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\FilterServiceImpl.java
2
请完成以下Java代码
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit getM_ShipmentSchedule_ExportAudit() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit.class); } @Override public void setM_ShipmentSchedule_ExportAudit(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit M_ShipmentSchedule_ExportAudit) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule_ExportAudit.class, M_ShipmentSchedule_ExportAudit); } @Override public void setM_ShipmentSchedule_ExportAudit_ID (final int M_ShipmentSchedule_ExportAudit_ID) { if (M_ShipmentSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, M_ShipmentSchedule_ExportAudit_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID); } @Override public void setM_ShipmentSchedule_ExportAudit_Item_ID (final int M_ShipmentSchedule_ExportAudit_Item_ID) { if (M_ShipmentSchedule_ExportAudit_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() {
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getHistoryConfiguration() { return historyConfiguration; } public void setHistoryConfiguration(String historicConfiguration) { this.historyConfiguration = historicConfiguration; } public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) { this.failedActivityId = failedActivityId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\incident\IncidentContext.java
1
请完成以下Java代码
public void setA_Period_9 (BigDecimal A_Period_9) { set_Value (COLUMNNAME_A_Period_9, A_Period_9); } /** Get A_Period_9. @return A_Period_9 */ public BigDecimal getA_Period_9 () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_9); if (bd == null) return Env.ZERO; return bd; } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Spread.java
1