instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public Optional<String> getUrl() {return getByPathAsString("page", "url");} public Optional<String> getUsername() {return getByPathAsString("user", "username");} public Optional<String> getCaption() {return getByPathAsString("caption");} public Optional<MobileApplicationId> getApplicationId() {return getByPathAsString("applicationId").map(MobileApplicationId::ofNullableString);} public Optional<String> getDeviceId() {return getByPathAsString("device", "deviceId");} public Optional<String> getTabId() {return getByPathAsString("device", "tabId");} public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");} public Optional<String> getByPathAsString(final String... path) { return getByPath(path).map(Object::toString); } public Optional<Object> getByPath(final String... path) { Object currentValue = properties; for (final String pathElement : path) { if (!(currentValue instanceof Map)) { //throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties); return Optional.empty(); } //noinspection unchecked final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null); if (value == null) { return Optional.empty();
} else { currentValue = value; } } return Optional.of(currentValue); } private static Optional<Object> getByKey(final Map<String, Object> map, final String key) { return map.entrySet() .stream() .filter(e -> e.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getValue) .filter(Objects::nonNull) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class JasyptEnvironmentChangeListener implements ApplicationListener<EnvironmentChangeEvent> { private Logger logger = LoggerFactory.getLogger(getClass()); // Environment 管理器,可以实现配置项的获取和修改 @Autowired private EnvironmentManager environmentManager; // Jasypt 加密器,可以对配置项进行加密和加密 @Autowired private StringEncryptor encryptor; @Override public void onApplicationEvent(EnvironmentChangeEvent event) { for (String key : event.getKeys()) { // 获得 value Object valueObj = environmentManager.getProperty(key);
if (!(valueObj instanceof String)) { continue; } String value = (String) valueObj; // 判断 value 是否为加密。如果是,则进行解密 if (value.startsWith("ENC(") && value.endsWith(")")) { value = encryptor.decrypt(StringUtils.substringBetween(value, "ENC(", ")")); logger.info("[onApplicationEvent][key({}) 解密后为 {}]", key, value); // 设置到 Environment 中 environmentManager.setProperty(key, value); } } } }
repos\SpringBoot-Labs-master\labx-05-spring-cloud-alibaba-nacos-config\labx-05-sca-nacos-config-demo-jasypt\src\main\java\cn\iocoder\springcloudalibaba\labx5\nacosdemo\listener\JasyptEnvironmentChangeListener.java
2
请完成以下Java代码
public boolean isPrincipalAuthenticated() { return !AnonymousAuthenticationToken.class.isAssignableFrom(this.principal.getClass()) && this.principal.isAuthenticated(); } @Override public Object getCredentials() { return ""; } /** * Returns the ID Token previously issued by the Provider to the Client and used as a * hint about the End-User's current authenticated session with the Client. * @return the ID Token previously issued by the Provider to the Client */ public String getIdTokenHint() { return this.idTokenHint; } /** * Returns the ID Token previously issued by the Provider to the Client. * @return the ID Token previously issued by the Provider to the Client */ @Nullable public OidcIdToken getIdToken() { return this.idToken; } /** * Returns the End-User's current authenticated session identifier with the Provider. * @return the End-User's current authenticated session identifier with the Provider */ @Nullable public String getSessionId() { return this.sessionId; } /** * Returns the client identifier the ID Token was issued to. * @return the client identifier */ @Nullable public String getClientId() { return this.clientId;
} /** * Returns the URI which the Client is requesting that the End-User's User Agent be * redirected to after a logout has been performed. * @return the URI which the Client is requesting that the End-User's User Agent be * redirected to after a logout has been performed */ @Nullable public String getPostLogoutRedirectUri() { return this.postLogoutRedirectUri; } /** * Returns the opaque value used by the Client to maintain state between the logout * request and the callback to the {@link #getPostLogoutRedirectUri()}. * @return the opaque value used by the Client to maintain state between the logout * request and the callback to the {@link #getPostLogoutRedirectUri()} */ @Nullable public String getState() { return this.state; } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcLogoutAuthenticationToken.java
1
请在Spring Boot框架中完成以下Java代码
protected static void validateQueueName(String name) { validateQueueNameOrTopic(name, NAME); if (DataConstants.CF_QUEUE_NAME.equals(name) || DataConstants.CF_STATES_QUEUE_NAME.equals(name)) { throw new DataValidationException(String.format("The queue name '%s' is not allowed. This name is reserved for internal use. Please choose a different name.", name)); } } protected static void validateQueueTopic(String topic) { validateQueueNameOrTopic(topic, TOPIC); } static void validateQueueNameOrTopic(String value, String fieldName) { if (StringUtils.isEmpty(value) || value.trim().length() == 0) { throw new DataValidationException(String.format("Queue %s should be specified!", fieldName)); } if (!QUEUE_PATTERN.matcher(value).matches()) {
throw new DataValidationException( String.format("Queue %s contains a character other than ASCII alphanumerics, '.', '_' and '-'!", fieldName)); } } public static boolean isValidDomain(String domainName) { if (domainName == null) { return false; } if (LOCALHOST_PATTERN.matcher(domainName).matches()) { return true; } return DOMAIN_PATTERN.matcher(domainName).matches(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\DataValidator.java
2
请完成以下Java代码
protected void addResource(Object source, Map<String, byte[]> resourceMap, String resourceRootPath, String resourceName) { String resourcePath = (resourceRootPath == null ? "" : resourceRootPath).concat(resourceName); LOG.debugDiscoveredResource(resourcePath); InputStream inputStream = null; try { if(source instanceof File) { try { inputStream = new FileInputStream((File) source); } catch (IOException e) { throw LOG.cannotOpenFileInputStream(((File) source).getAbsolutePath(), e); } } else { inputStream = (InputStream) source; } byte[] bytes = IoUtil.readInputStream(inputStream, resourcePath); resourceMap.put(resourceName, bytes); } finally { if(inputStream != null) { IoUtil.closeSilently(inputStream); } }
} protected Enumeration<URL> loadClasspathResourceRoots(final ClassLoader classLoader, String strippedPaResourceRootPath) { Enumeration<URL> resourceRoots; try { resourceRoots = classLoader.getResources(strippedPaResourceRootPath); } catch (IOException e) { throw LOG.couldNotGetResource(strippedPaResourceRootPath, classLoader, e); } return resourceRoots; } protected boolean isBelowPath(String processFileName, String paResourceRootPath) { if(paResourceRootPath == null || paResourceRootPath.length() ==0 ) { return true; } else { return processFileName.startsWith(paResourceRootPath); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\ClassPathProcessApplicationScanner.java
1
请在Spring Boot框架中完成以下Java代码
public Job flowJob() { return jobBuilderFactory.get("flowJob") .start(flow()) .next(step3()) .end() .build(); } private Step step1() { return stepBuilderFactory.get("step1") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤一操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step2() { return stepBuilderFactory.get("step2") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤二操作。。。"); return RepeatStatus.FINISHED; }).build(); } private Step step3() {
return stepBuilderFactory.get("step3") .tasklet((stepContribution, chunkContext) -> { System.out.println("执行步骤三操作。。。"); return RepeatStatus.FINISHED; }).build(); } // 创建一个flow对象,包含若干个step private Flow flow() { return new FlowBuilder<Flow>("flow") .start(step1()) .next(step2()) .build(); } }
repos\SpringAll-master\67.spring-batch-start\src\main\java\cc\mrbird\batch\job\FlowJobDemo.java
2
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderMapping orderMapping = (OrderMapping) o; return Objects.equals(this.orderId, orderMapping.orderId) && Objects.equals(this.salesId, orderMapping.salesId) && Objects.equals(this.updated, orderMapping.updated); } @Override public int hashCode() { return Objects.hash(orderId, salesId, updated); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OrderMapping {\n"); sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n"); sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderMapping.java
2
请完成以下Java代码
protected Result getTargetVector() { final int words = vectorsReader.getNumWords(); final int size = vectorsReader.getSize(); String[] input = null; while ((input = nextWords(3, "Enter 3 words")) != null) { // linear search the input word in vocabulary int[] bi = new int[input.length]; int found = 0; for (int k = 0; k < input.length; k++) { for (int i = 0; i < words; i++) { if (input[k].equals(vectorsReader.getWord(i))) { bi[k] = i; System.out.printf("\nWord: %s Position in vocabulary: %d\n", input[k], bi[k]); found++; } } if (found == k) { System.out.printf("%s : Out of dictionary word!\n", input[k]); } } if (found < input.length) { continue; } float[] vec = new float[size];
double len = 0; for (int j = 0; j < size; j++) { vec[j] = vectorsReader.getMatrixElement(bi[1], j) - vectorsReader.getMatrixElement(bi[0], j) + vectorsReader.getMatrixElement(bi[2], j); len += vec[j] * vec[j]; } len = Math.sqrt(len); for (int i = 0; i < size; i++) { vec[i] /= len; } return new Result(vec, bi); } return null; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\WordAnalogy.java
1
请完成以下Java代码
public int hashCode() { Integer hashcode = this._hashcode; if (hashcode == null) { hashcode = this._hashcode = Objects.hash(valid, initialValue, reason, fieldName); } return hashcode; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof DocumentValidStatus)) { return false; } final DocumentValidStatus other = (DocumentValidStatus)obj; return valid == other.valid && Objects.equals(initialValue, other.initialValue) && Objects.equals(reason, other.reason) && Objects.equals(fieldName, other.fieldName) && Objects.equals(errorCode, other.errorCode); } public boolean isInitialInvalid() { return this == STATE_InitialInvalid; }
public void throwIfInvalid() { if (isValid()) { return; } if (exception != null) { throw AdempiereException.wrapIfNeeded(exception); } else { throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Invalid")); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentValidStatus.java
1
请完成以下Java代码
protected Response createResponse(List<MessageCorrelationResultDto> resultDtos, CorrelationMessageDto messageDto) { Response.ResponseBuilder response = Response.noContent(); if (messageDto.isResultEnabled()) { response = Response.ok(resultDtos, MediaType.APPLICATION_JSON); } return response.build(); } protected MessageCorrelationBuilder createMessageCorrelationBuilder(CorrelationMessageDto messageDto) { ProcessEngine processEngine = getProcessEngine(); RuntimeService runtimeService = processEngine.getRuntimeService(); ObjectMapper objectMapper = getObjectMapper(); Map<String, Object> correlationKeys = VariableValueDto.toMap(messageDto.getCorrelationKeys(), processEngine, objectMapper); Map<String, Object> localCorrelationKeys = VariableValueDto.toMap(messageDto.getLocalCorrelationKeys(), processEngine, objectMapper); Map<String, Object> processVariables = VariableValueDto.toMap(messageDto.getProcessVariables(), processEngine, objectMapper); Map<String, Object> processVariablesLocal = VariableValueDto.toMap(messageDto.getProcessVariablesLocal(), processEngine, objectMapper); Map<String, Object> processVariablesToTriggeredScope = VariableValueDto.toMap(messageDto.getProcessVariablesToTriggeredScope(), processEngine, objectMapper); MessageCorrelationBuilder builder = runtimeService .createMessageCorrelation(messageDto.getMessageName()); if (processVariables != null) { builder.setVariables(processVariables); } if (processVariablesLocal != null) { builder.setVariablesLocal(processVariablesLocal); } if (processVariablesToTriggeredScope != null) { builder.setVariablesToTriggeredScope(processVariablesToTriggeredScope); } if (messageDto.getBusinessKey() != null) { builder.processInstanceBusinessKey(messageDto.getBusinessKey()); }
if (correlationKeys != null && !correlationKeys.isEmpty()) { for (Entry<String, Object> correlationKey : correlationKeys.entrySet()) { String name = correlationKey.getKey(); Object value = correlationKey.getValue(); builder.processInstanceVariableEquals(name, value); } } if (localCorrelationKeys != null && !localCorrelationKeys.isEmpty()) { for (Entry<String, Object> correlationKey : localCorrelationKeys.entrySet()) { String name = correlationKey.getKey(); Object value = correlationKey.getValue(); builder.localVariableEquals(name, value); } } if (messageDto.getTenantId() != null) { builder.tenantId(messageDto.getTenantId()); } else if (messageDto.isWithoutTenantId()) { builder.withoutTenantId(); } String processInstanceId = messageDto.getProcessInstanceId(); if (processInstanceId != null) { builder.processInstanceId(processInstanceId); } return builder; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MessageRestServiceImpl.java
1
请完成以下Java代码
public class Product { private Integer id; private String name; private String description; private Map<String, Attribute> attributes; public Product(){ } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Map<String, Attribute> getAttributes() { return attributes; } public void setAttributes(Map<String, Attribute> attributes) { this.attributes = attributes; } }
repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphqlreturnmap\entity\Product.java
1
请完成以下Java代码
public Mono<MultipleCommentsView> getComments(String slug, Optional<User> user) { return commentService.getComments(slug, user); } public Mono<ArticleView> favoriteArticle(String slug, User currentUser) { return articleRepository.findBySlug(slug) .map(article -> { currentUser.favorite(article); return ArticleView.ofOwnArticle(article, currentUser); }); } public Mono<ArticleView> unfavoriteArticle(String slug, User currentUser) { return articleRepository.findBySlug(slug) .map(article -> { currentUser.unfavorite(article); return ArticleView.ofOwnArticle(article, currentUser); });
} private ArticleView updateArticle(UpdateArticleRequest request, User currentUser, Article article) { if (!article.isAuthor(currentUser)) { throw new InvalidRequestException("Article", "only author can update article"); } ofNullable(request.getBody()) .ifPresent(article::setBody); ofNullable(request.getDescription()) .ifPresent(article::setDescription); ofNullable(request.getTitle()) .ifPresent(article::setTitle); return ArticleView.ofOwnArticle(article, currentUser); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\ArticleFacade.java
1
请完成以下Java代码
public String getCredentialType() { return credentialType; } public void setCredentialType(String credentialType) { this.credentialType = credentialType; } public String getCredentialId() { return credentialId; } public void setCredentialId(String credentialId) { this.credentialId = credentialId; } public String getPublicKeyCose() { return publicKeyCose; } public void setPublicKeyCose(String publicKeyCose) { this.publicKeyCose = publicKeyCose; } public Long getSignatureCount() { return signatureCount; } public void setSignatureCount(Long signatureCount) { this.signatureCount = signatureCount; } public Boolean getUvInitialized() { return uvInitialized; } public void setUvInitialized(Boolean uvInitialized) { this.uvInitialized = uvInitialized; } public String getTransports() { return transports; } public void setTransports(String transports) { this.transports = transports; } public Boolean getBackupEligible() { return backupEligible;
} public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible; } public Boolean getBackupState() { return backupState; } public void setBackupState(Boolean backupState) { this.backupState = backupState; } public String getAttestationObject() { return attestationObject; } public void setAttestationObject(String attestationObject) { this.attestationObject = attestationObject; } public Instant getLastUsed() { return lastUsed; } public void setLastUsed(Instant lastUsed) { this.lastUsed = lastUsed; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java
1
请完成以下Java代码
public boolean intersects(@NonNull final AttributesKey attributesKey) { return parts.stream().anyMatch(attributesKey.parts::contains); } public String getValueByAttributeId(@NonNull final AttributeId attributeId) { for (final AttributesKeyPart part : parts) { if (part.getType() == AttributeKeyPartType.AttributeIdAndValue && AttributeId.equals(part.getAttributeId(), attributeId)) { return part.getValue(); } } throw new AdempiereException("Attribute `" + attributeId + "` was not found in `" + this + "`");
} public static boolean equals(@Nullable final AttributesKey k1, @Nullable final AttributesKey k2) { return Objects.equals(k1, k2); } @Override public int compareTo(@Nullable final AttributesKey o) { if (o == null) { return 1; // we assume that null is less than not-null } return this.getAsString().compareTo(o.getAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKey.java
1
请完成以下Java代码
private DocumentFilter getEffectiveFilter(final @NonNull CreateViewRequest request) { if (request.isUseAutoFilters()) { final InvoiceAndLineId invoiceAndLineId = getInvoiceLineId(request); final I_C_Invoice invoice = invoiceBL.getById(invoiceAndLineId.getInvoiceId()); final BPartnerId bpartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final LookupValue bpartner = lookupDataSourceFactory.searchInTableLookup(I_C_BPartner.Table_Name).findById(bpartnerId); return DocumentFilter.equalsFilter(InOutCostsViewFilterHelper.FILTER_ID, InOutCostsViewFilterHelper.PARAM_C_BPartner_ID, bpartner); } else { return request.getFiltersUnwrapped(getFilterDescriptor()) .getFilterById(InOutCostsViewFilterHelper.FILTER_ID) .orElse(null); } } @SuppressWarnings("SameParameterValue") private RelatedProcessDescriptor createProcessDescriptor(final int sortNo, @NonNull final Class<?> processClass) { final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass); return RelatedProcessDescriptor.builder() .processId(processId) .anyTable().anyWindow() .displayPlace(RelatedProcessDescriptor.DisplayPlace.ViewQuickActions) .sortNo(sortNo) .build(); } private DocumentFilterDescriptor getFilterDescriptor() { DocumentFilterDescriptor filterDescriptor = this._filterDescriptor; if (filterDescriptor == null) { final LookupDescriptorProviders lookupDescriptorProviders = lookupDataSourceFactory.getLookupDescriptorProviders(); filterDescriptor = this._filterDescriptor = InOutCostsViewFilterHelper.createFilterDescriptor(lookupDescriptorProviders); }
return filterDescriptor; } @Override public InOutCostsView filterView( final @NonNull IView view, final @NonNull JSONFilterViewRequest filterViewRequest, final @NonNull Supplier<IViewsRepository> viewsRepo) { final InOutCostsView inOutCostsView = (InOutCostsView)view; return createView( CreateViewRequest.filterViewBuilder(view, filterViewRequest) .setParameter(VIEW_PARAM_SOTrx, inOutCostsView.getSoTrx()) .setParameter(VIEW_PARAM_invoiceLineId, inOutCostsView.getInvoiceLineId()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsViewFactory.java
1
请完成以下Java代码
public void setIsInDispute (boolean IsInDispute) { set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute)); } /** Get In Dispute. @return Document is in dispute */ @Override public boolean isInDispute () { Object oo = get_Value(COLUMNNAME_IsInDispute); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Offener Betrag. @param OpenAmt Offener Betrag */ @Override public void setOpenAmt (java.math.BigDecimal OpenAmt) { set_Value (COLUMNNAME_OpenAmt, OpenAmt); } /** Get Offener Betrag. @return Offener Betrag */ @Override public java.math.BigDecimal getOpenAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java
1
请完成以下Java代码
protected void handleStartEvent(EventSubscriptionEntity eventSubscription, Map<String, Object> payload, String businessKey, CommandContext commandContext) { String processDefinitionId = eventSubscription.getConfiguration(); ensureNotNull("Configuration of signal start event subscription '" + eventSubscription.getId() + "' contains no process definition id.", processDefinitionId); DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache(); ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId); if (processDefinition == null || processDefinition.isSuspended()) { // ignore event subscription LOG.debugIgnoringEventSubscription(eventSubscription, processDefinitionId); } else { ActivityImpl signalStartEvent = processDefinition.findActivity(eventSubscription.getActivityId()); PvmProcessInstance processInstance = processDefinition.createProcessInstance(businessKey, signalStartEvent); processInstance.start(payload); } }
@Override public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, Object payloadLocal, Object payloadToTriggeredScope, String businessKey, CommandContext commandContext) { if (eventSubscription.getExecutionId() != null) { handleIntermediateEvent(eventSubscription, payload, payloadLocal, null, commandContext); } else { handleStartEvent(eventSubscription, (Map<String, Object>) payload, businessKey, commandContext); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\event\SignalEventHandler.java
1
请完成以下Java代码
public void setAuthenticationConverter(AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } /** * Sets the {@link AuthenticationSuccessHandler} used for handling an * {@link OAuth2PushedAuthorizationRequestAuthenticationToken} and returning the * Pushed Authorization Response. * @param authenticationSuccessHandler the {@link AuthenticationSuccessHandler} used * for handling an {@link OAuth2PushedAuthorizationRequestAuthenticationToken} */ public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { Assert.notNull(authenticationSuccessHandler, "authenticationSuccessHandler cannot be null"); this.authenticationSuccessHandler = authenticationSuccessHandler; } /** * Sets the {@link AuthenticationFailureHandler} used for handling an * {@link OAuth2AuthenticationException} and returning the {@link OAuth2Error Error * Response}. * @param authenticationFailureHandler the {@link AuthenticationFailureHandler} used * for handling an {@link OAuth2AuthenticationException} */ public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler;
} private void sendPushedAuthorizationResponse(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { OAuth2PushedAuthorizationRequestAuthenticationToken pushedAuthorizationRequestAuthentication = (OAuth2PushedAuthorizationRequestAuthenticationToken) authentication; Map<String, Object> pushedAuthorizationResponse = new LinkedHashMap<>(); pushedAuthorizationResponse.put(OAuth2ParameterNames.REQUEST_URI, pushedAuthorizationRequestAuthentication.getRequestUri()); long expiresIn = ChronoUnit.SECONDS.between(Instant.now(), pushedAuthorizationRequestAuthentication.getRequestUriExpiresAt()); pushedAuthorizationResponse.put(OAuth2ParameterNames.EXPIRES_IN, expiresIn); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(HttpStatus.CREATED); JSON_MESSAGE_CONVERTER.write(pushedAuthorizationResponse, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON, httpResponse); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\OAuth2PushedAuthorizationRequestEndpointFilter.java
1
请完成以下Java代码
public EventModelBuilder correlationParameter(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.correlation(name, type)); return this; } @Override public EventModelBuilder payload(String name, String type) { eventPayloadDefinitions.put(name, new EventPayload(name, type)); return this; } @Override public EventModelBuilder metaParameter(String name, String type) { EventPayload payload = new EventPayload(name, type); payload.setMetaParameter(true); eventPayloadDefinitions.put(name, payload); return this; } @Override public EventModelBuilder fullPayload(String name) { eventPayloadDefinitions.put(name, EventPayload.fullPayload(name)); return this; } @Override public EventModel createEventModel() { return buildEventModel(); } @Override public EventDeployment deploy() { if (resourceName == null) { throw new FlowableIllegalArgumentException("A resource name is mandatory"); } EventModel eventModel = buildEventModel(); return eventRepository.createDeployment() .name(deploymentName) .addEventDefinition(resourceName, eventJsonConverter.convertToJson(eventModel))
.category(category) .parentDeploymentId(parentDeploymentId) .tenantId(deploymentTenantId) .deploy(); } protected EventModel buildEventModel() { EventModel eventModel = new EventModel(); if (StringUtils.isNotEmpty(key)) { eventModel.setKey(key); } else { throw new FlowableIllegalArgumentException("An event definition key is mandatory"); } eventModel.setPayload(eventPayloadDefinitions.values()); return eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\EventModelBuilderImpl.java
1
请完成以下Java代码
private static void addForecastLine(final I_M_Forecast forecastRecord, final @NotNull ForecastLineRequest request) { final I_M_ForecastLine forecastLineRecord = InterfaceWrapperHelper.newInstance(I_M_ForecastLine.class); forecastLineRecord.setM_Forecast_ID(forecastRecord.getM_Forecast_ID()); forecastLineRecord.setM_Warehouse_ID(forecastRecord.getM_Warehouse_ID()); forecastLineRecord.setQty(request.getQuantity().toBigDecimal()); forecastLineRecord.setC_UOM_ID(request.getQuantity().getUomId().getRepoId()); forecastLineRecord.setM_Product_ID(request.getProductId().getRepoId()); forecastLineRecord.setC_Activity_ID(ActivityId.toRepoId(request.getActivityId())); forecastLineRecord.setC_Campaign_ID(CampaignId.toRepoId(request.getCampaignId())); forecastLineRecord.setC_Project_ID(ProjectId.toRepoId(request.getProjectId())); forecastLineRecord.setQtyCalculated(Quantity.toBigDecimal(request.getQuantityCalculated())); saveRecord(forecastLineRecord); } @Override public I_M_Forecast getById(@NonNull final ForecastId forecastId)
{ final I_M_Forecast forecast = InterfaceWrapperHelper.load(forecastId, I_M_Forecast.class); if (forecast == null) { throw new AdempiereException("@NotFound@: " + forecastId); } return forecast; } @Override public void save(@NonNull final I_M_Forecast forecastRecord) { saveRecord(forecastRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impl\ForecastDAO.java
1
请完成以下Java代码
public class HttpStatusExchangeRejectedHandler implements ServerExchangeRejectedHandler { private static final Log logger = LogFactory.getLog(HttpStatusExchangeRejectedHandler.class); private final HttpStatus status; /** * Constructs an instance which uses {@code 400} as response code. */ public HttpStatusExchangeRejectedHandler() { this(HttpStatus.BAD_REQUEST); } /** * Constructs an instance which uses a configurable http code as response. * @param status http status code to use */ public HttpStatusExchangeRejectedHandler(HttpStatus status) {
this.status = status; } @Override public Mono<Void> handle(ServerWebExchange exchange, ServerExchangeRejectedException serverExchangeRejectedException) { return Mono.fromRunnable(() -> { logger.debug( LogMessage.format("Rejecting request due to: %s", serverExchangeRejectedException.getMessage()), serverExchangeRejectedException); exchange.getResponse().setStatusCode(this.status); }); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\HttpStatusExchangeRejectedHandler.java
1
请完成以下Java代码
private static FileType to(String fileType) { return FILE_TYPE_MAPPER.getOrDefault(fileType, OTHER); } /** * 查看文件类型(防止参数中存在.点号或者其他特殊字符,所以先抽取文件名,然后再获取文件类型) * * @param url url * @return 文件类型 */ public static FileType typeFromUrl(String url) { String nonPramStr = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length()); String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1); return typeFromFileName(fileName); } public static FileType typeFromFileName(String fileName) {
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1); String lowerCaseFileType = fileType.toLowerCase(); return FileType.to(lowerCaseFileType); } private final String instanceName; FileType(String instanceName) { this.instanceName = instanceName; } public String getInstanceName() { return instanceName; } }
repos\kkFileView-master\server\src\main\java\cn\keking\model\FileType.java
1
请完成以下Java代码
public class MybatisByteArrayDataManager extends AbstractDataManager<ByteArrayEntity> implements ByteArrayDataManager { protected IdGenerator idGenerator; public MybatisByteArrayDataManager(IdGenerator idGenerator) { this.idGenerator = idGenerator; } @Override public ByteArrayEntity create() { return new ByteArrayEntityImpl(); } @Override public Class<? extends ByteArrayEntity> getManagedEntityClass() { return ByteArrayEntityImpl.class; } @Override @SuppressWarnings("unchecked") public List<ByteArrayEntity> findAll() { return getDbSqlSession().selectList("selectByteArrays");
} @Override public void deleteByteArrayNoRevisionCheck(String byteArrayEntityId) { getDbSqlSession().delete("deleteByteArrayNoRevisionCheck", byteArrayEntityId, ByteArrayEntityImpl.class); } @Override public void bulkDeleteByteArraysNoRevisionCheck(List<String> byteArrayEntityIds) { getDbSqlSession().delete("deleteByteArraysNoRevisionCheck", createSafeInValuesList(byteArrayEntityIds), ByteArrayEntityImpl.class); } @Override protected IdGenerator getIdGenerator() { return idGenerator; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\data\impl\MybatisByteArrayDataManager.java
1
请完成以下Java代码
public class DocumentLineInformation1 { @XmlElement(name = "Id", required = true) protected List<DocumentLineIdentification1> id; @XmlElement(name = "Desc") protected String desc; @XmlElement(name = "Amt") protected RemittanceAmount3 amt; /** * Gets the value of the id 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 id property. * * <p> * For example, to add a new item, do as follows: * <pre> * getId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentLineIdentification1 } * * */ public List<DocumentLineIdentification1> getId() { if (id == null) { id = new ArrayList<DocumentLineIdentification1>(); } return this.id; } /** * Gets the value of the desc property. * * @return * possible object is * {@link String } * */ public String getDesc() { return desc; } /** * Sets the value of the desc property. * * @param value * allowed object is * {@link String }
* */ public void setDesc(String value) { this.desc = value; } /** * Gets the value of the amt property. * * @return * possible object is * {@link RemittanceAmount3 } * */ public RemittanceAmount3 getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link RemittanceAmount3 } * */ public void setAmt(RemittanceAmount3 value) { this.amt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\DocumentLineInformation1.java
1
请在Spring Boot框架中完成以下Java代码
public Long getOperatorId() { return operatorId; } public void setOperatorId(Long operatorId) { this.operatorId = operatorId; } public String getOperatorName() { return operatorName; } public void setOperatorName(String operatorName) { this.operatorName = operatorName; } public String getOperateType() { return operateType; }
public void setOperateType(String operateType) { this.operateType = operateType; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperatorLog.java
2
请完成以下Java代码
private Map<String, Object> getOtherProperties() { return otherProperties; } @JsonAnySetter private void putOtherProperty(final String name, final Object jsonValue) { otherProperties.put(name, jsonValue); } protected final JSONDocumentBase putDebugProperty(final String name, final Object jsonValue) { otherProperties.put("debug-" + name, jsonValue); return this; } public final void setFields(final Collection<JSONDocumentField> fields) {
setFields(fields == null ? null : Maps.uniqueIndex(fields, JSONDocumentField::getField)); } @JsonIgnore protected final void setFields(final Map<String, JSONDocumentField> fieldsByName) { this.fieldsByName = fieldsByName; if (unboxPasswordFields && fieldsByName != null && !fieldsByName.isEmpty()) { fieldsByName.forEach((fieldName, field) -> field.unboxPasswordField()); } } @JsonIgnore protected final int getFieldsCount() { return fieldsByName == null ? 0 : fieldsByName.size(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentBase.java
1
请完成以下Java代码
public class Result<T> implements Serializable { private static final long serialVersionUID = 1L; private int resultCode; private String message; private T data; public Result() { } public Result(int resultCode, String message) { this.resultCode = resultCode; this.message = message; } public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data;
} public void setData(T data) { this.data = data; } public Result failure(String code) { return new Result(500, "服务错误"); } @Override public String toString() { return "Result{" + "resultCode=" + resultCode + ", message='" + message + '\'' + ", data=" + data + '}'; } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-RESTful-api\src\main\java\cn\lanqiao\springboot3\common\Result.java
1
请完成以下Java代码
public static void main(String[] args) { new LambdaVariables().localVariableMultithreading(); } Supplier<Integer> incrementer(int start) { return () -> start; // can't modify start parameter inside the lambda } Supplier<Integer> incrementer() { return () -> start++; } public void localVariableMultithreading() { boolean run = true; executor.execute(() -> { while (run) { // do operation } }); // commented because it doesn't compile, it's just an example of non-final local variables in lambdas // run = false; } public void instanceVariableMultithreading() { executor.execute(() -> { while (run) { // do operation } }); run = false; } /** * WARNING: always avoid this workaround!! */ public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]); holder[0] = 0; System.out.println(sums.sum());
} /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() { int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0]) .sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请完成以下Java代码
public void setRealizedLoss_Acct (int RealizedLoss_Acct) { set_Value (COLUMNNAME_RealizedLoss_Acct, Integer.valueOf(RealizedLoss_Acct)); } /** Get Realisierte Währungsverluste. @return Konto für realisierte Währungsverluste */ @Override public int getRealizedLoss_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_RealizedLoss_Acct); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_ValidCombination getUnrealizedGain_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setUnrealizedGain_A(org.compiere.model.I_C_ValidCombination UnrealizedGain_A) { set_ValueFromPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedGain_A); } /** Set Nicht realisierte Währungsgewinne. @param UnrealizedGain_Acct Konto für nicht realisierte Währungsgewinne */ @Override public void setUnrealizedGain_Acct (int UnrealizedGain_Acct) { set_Value (COLUMNNAME_UnrealizedGain_Acct, Integer.valueOf(UnrealizedGain_Acct)); } /** Get Nicht realisierte Währungsgewinne. @return Konto für nicht realisierte Währungsgewinne */ @Override public int getUnrealizedGain_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedGain_Acct); if (ii == null) return 0; return ii.intValue(); }
@Override public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A) { set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A); } /** Set Nicht realisierte Währungsverluste. @param UnrealizedLoss_Acct Konto für nicht realisierte Währungsverluste */ @Override public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct) { set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct)); } /** Get Nicht realisierte Währungsverluste. @return Konto für nicht realisierte Währungsverluste */ @Override public int getUnrealizedLoss_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_Acct); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency_Acct.java
1
请完成以下Java代码
public boolean isSuccess() { return !isError(); } /** * @return action of given type; never returns null */ public <T extends ResultAction> T getAction(final Class<T> actionType) { final ResultAction action = getAction(); if (action == null) { throw new IllegalStateException("No action defined"); } if (!actionType.isAssignableFrom(action.getClass())) { throw new IllegalStateException("Action is not of type " + actionType + " but " + action.getClass()); } @SuppressWarnings("unchecked") final T actionCasted = (T)action; return actionCasted; } // // // // // /** * Base interface for all post-process actions */ public interface ResultAction { } @lombok.Value @lombok.Builder public static class OpenReportAction implements ResultAction { @NonNull String filename; @NonNull String contentType; @NonNull Resource reportData; } @lombok.Value @lombok.Builder public static class OpenViewAction implements ResultAction { @NonNull ViewId viewId; @Nullable ViewProfileId profileId; @Builder.Default ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.SAME_TAB_OVERLAY; } @lombok.Value @lombok.Builder
public static class OpenIncludedViewAction implements ResultAction { @NonNull ViewId viewId; ViewProfileId profileId; } @lombok.Value(staticConstructor = "of") public static class CreateAndOpenIncludedViewAction implements ResultAction { @NonNull CreateViewRequest createViewRequest; } public static final class CloseViewAction implements ResultAction { public static final CloseViewAction instance = new CloseViewAction(); private CloseViewAction() {} } @lombok.Value @lombok.Builder public static class OpenSingleDocument implements ResultAction { @NonNull DocumentPath documentPath; @Builder.Default ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB; } @lombok.Value @lombok.Builder public static class SelectViewRowsAction implements ResultAction { @NonNull ViewId viewId; @NonNull DocumentIdsSelection rowIds; } @lombok.Value @lombok.Builder public static class DisplayQRCodeAction implements ResultAction { @NonNull String code; } @lombok.Value @lombok.Builder public static class NewRecordAction implements ResultAction { @NonNull String windowId; @NonNull @Singular Map<String, String> fieldValues; @NonNull @Builder.Default ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab = ProcessExecutionResult.WebuiNewRecord.TargetTab.SAME_TAB; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessInstanceResult.java
1
请在Spring Boot框架中完成以下Java代码
public class Cause2PersistenceConfig { @Autowired private Environment env; public Cause2PersistenceConfig() { super(); } @Bean public LocalSessionFactoryBean sessionFactory() { final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); sessionFactory.setHibernateProperties(hibernateProperties()); // sessionFactory.setPackagesToScan(new String[] { "com.baeldung.ex.mappingexception.cause2.persistence.model" }); // sessionFactory.setAnnotatedClasses(new Class[] { Foo.class }); return sessionFactory; } @Bean public DataSource restDataSource() { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory().getObject()); return txManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); return hibernateProperties; } }
repos\tutorials-master\spring-exceptions\src\main\java\com\baeldung\ex\mappingexception\spring\Cause2PersistenceConfig.java
2
请完成以下Java代码
public class PrincipalSid implements Sid { private final String principal; public PrincipalSid(String principal) { Assert.hasText(principal, "Principal required"); this.principal = principal; } public PrincipalSid(Authentication authentication) { Assert.notNull(authentication, "Authentication required"); Assert.notNull(authentication.getPrincipal(), "Principal required"); this.principal = authentication.getName(); } @Override public boolean equals(Object object) { if ((object == null) || !(object instanceof PrincipalSid)) { return false; } // Delegate to getPrincipal() to perform actual comparison (both should be // identical) return ((PrincipalSid) object).getPrincipal().equals(this.getPrincipal()); }
@Override public int hashCode() { return this.getPrincipal().hashCode(); } public String getPrincipal() { return this.principal; } @Override public String toString() { return "PrincipalSid[" + this.principal + "]"; } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\PrincipalSid.java
1
请完成以下Java代码
public class Zoo { public Animal animal; public Zoo() { } public Zoo(final Animal animal) { this.animal = animal; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") }) public static class Animal { public String name; public Animal() { } public Animal(final String name) { this.name = name; } } @JsonTypeName("dog") public static class Dog extends Animal { public double barkVolume; public Dog() { } public Dog(final String name) { this.name = name; }
} @JsonTypeName("cat") public static class Cat extends Animal { boolean likesCream; public int lives; public Cat() { } public Cat(final String name) { this.name = name; } } }
repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\annotation\Zoo.java
1
请完成以下Java代码
public class BasicAuthProvider implements ClientRequestInterceptor { protected static final ExternalTaskClientLogger LOG = ExternalTaskClientLogger.CLIENT_LOGGER; protected String username; protected String password; public BasicAuthProvider(String username, String password) { if (username == null || password == null) { throw LOG.basicAuthCredentialsNullException(); } this.username = username; this.password = password; } @Override
public void intercept(ClientRequestContext requestContext) { String authToken = username + ":" + password; String encodedAuthToken = encodeToBase64(authToken); requestContext.addHeader(AUTHORIZATION, "Basic " + encodedAuthToken); } protected String encodeToBase64(String decodedString) { byte[] stringAsBytes = decodedString.getBytes(Charset.defaultCharset()); return Base64.getEncoder() .encodeToString(stringAsBytes); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\interceptor\auth\BasicAuthProvider.java
1
请在Spring Boot框架中完成以下Java代码
public String getVersionAttr() { if (versionAttr == null) { return "*"; } else { return versionAttr; } } /** * Sets the value of the versionAttr property. * * @param value * allowed object is * {@link String } * */ public void setVersionAttr(String value) { this.versionAttr = value; } /** * Gets the value of the sequenceNoAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getSequenceNoAttr() { return sequenceNoAttr; } /** * Sets the value of the sequenceNoAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setSequenceNoAttr(BigInteger value) { this.sequenceNoAttr = value; } /** * Gets the value of the trxNameAttr property.
* * @return * possible object is * {@link String } * */ public String getTrxNameAttr() { return trxNameAttr; } /** * Sets the value of the trxNameAttr property. * * @param value * allowed object is * {@link String } * */ public void setTrxNameAttr(String value) { this.trxNameAttr = value; } /** * Gets the value of the adSessionIDAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getADSessionIDAttr() { return adSessionIDAttr; } /** * Sets the value of the adSessionIDAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setADSessionIDAttr(BigInteger value) { this.adSessionIDAttr = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCBPartnerProductVType.java
2
请完成以下Java代码
public void replace(final int offset, final int length, final String text, final AttributeSet attrs) throws BadLocationException { super.replace(offset, length, text, attrs); } /** * Caret Listener * @param e event */ @Override public void caretUpdate(CaretEvent e) { if(log.isTraceEnabled()) log.trace("Dot=" + e.getDot() + ",Last=" + m_lastDot + ", Mark=" + e.getMark()); // Selection if (e.getDot() != e.getMark()) { m_lastDot = e.getDot(); return; } // // Is the current position a fixed character? if (e.getDot()+1 > m_mask.length() || m_mask.charAt(e.getDot()) != DELIMITER) { m_lastDot = e.getDot(); return; } // Direction? int newDot = -1; if (m_lastDot > e.getDot()) // <- newDot = e.getDot() - 1; else // -> (or same) newDot = e.getDot() + 1; if (e.getDot() == 0) // first newDot = 1; else if (e.getDot() == m_mask.length()-1) // last newDot = e.getDot() - 1; // if (log.isDebugEnabled()) log.debug("OnFixedChar=" + m_mask.charAt(e.getDot()) + ", newDot=" + newDot + ", last=" + m_lastDot); // m_lastDot = e.getDot(); if (newDot >= 0 && newDot < getText().length()) m_tc.setCaretPosition(newDot); } // caretUpdate
/** * Get Full Text * @return text */ private String getText() { String str = ""; try { str = getContent().getString(0, getContent().length() - 1); // cr at end } catch (Exception e) { str = ""; } return str; } private final void provideErrorFeedback() { UIManager.getLookAndFeel().provideErrorFeedback(m_tc); } } // MDocDate
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocDate.java
1
请在Spring Boot框架中完成以下Java代码
public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } protected final List<String> filter(@Nullable Collection<String> classNames, ClassNameFilter classNameFilter, @Nullable ClassLoader classLoader) { if (CollectionUtils.isEmpty(classNames)) { return Collections.emptyList(); } List<String> matches = new ArrayList<>(classNames.size()); for (String candidate : classNames) { if (classNameFilter.matches(candidate, classLoader)) { matches.add(candidate); } } return matches; } /** * Slightly faster variant of {@link ClassUtils#forName(String, ClassLoader)} that * doesn't deal with primitives, arrays or inner types. * @param className the class name to resolve * @param classLoader the class loader to use * @return a resolved class * @throws ClassNotFoundException if the class cannot be found */ protected static Class<?> resolve(String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException { if (classLoader != null) { return Class.forName(className, false, classLoader); } return Class.forName(className); } protected enum ClassNameFilter { PRESENT { @Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return isPresent(className, classLoader); } }, MISSING {
@Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return !isPresent(className, classLoader); } }; abstract boolean matches(String className, @Nullable ClassLoader classLoader); private static boolean isPresent(String className, @Nullable ClassLoader classLoader) { if (classLoader == null) { classLoader = ClassUtils.getDefaultClassLoader(); } try { resolve(className, classLoader); return true; } catch (Throwable ex) { return false; } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\FilteringSpringBootCondition.java
2
请完成以下Java代码
public static String initCap(final String in) { if (in == null || in.isEmpty()) { return in; } // boolean capitalize = true; final char[] data = in.toCharArray(); for (int i = 0; i < data.length; i++) { if (data[i] == ' ' || Character.isWhitespace(data[i])) { capitalize = true; } else if (capitalize) { data[i] = Character.toUpperCase(data[i]); capitalize = false; } else { data[i] = Character.toLowerCase(data[i]); } } return new String(data); } // initCap /** * @param in input {@link String} * @return {@param in} if != null, empty string otherwise */ @NonNull public static String nullToEmpty(@Nullable final String in) { return in != null ? in : ""; } /** * Example: * <pre> * - string = `87whdhA7008S` (length 14) * - groupSeparator = "--" * - groupSize = 4 * * Results into `87wh--dhA7--008S` of length 18. * </pre> * * @param string the input string * @param groupSeparator the separator string * @param groupSize the size of each character group, after which a groupSeparator is inserted * @return the input string containing the groupSeparator */ @NonNull public static String insertSeparatorEveryNCharacters( @NonNull final String string, @NonNull final String groupSeparator, final int groupSize) { if (groupSize < 1) { return string; } final StringBuilder result = new StringBuilder(string);
int insertPosition = groupSize; while (insertPosition < result.length()) { result.insert(insertPosition, groupSeparator); insertPosition += groupSize + groupSeparator.length(); } return result.toString(); } public static Map<String, String> parseURLQueryString(@Nullable final String query) { final String queryNorm = trimBlankToNull(query); if (queryNorm == null) { return ImmutableMap.of(); } final HashMap<String, String> params = new HashMap<>(); for (final String param : queryNorm.split("&")) { final String key; final String value; final int idx = param.indexOf("="); if (idx < 0) { key = param; value = null; } else { key = param.substring(0, idx); value = param.substring(idx + 1); } params.put(key, value); } return params; } @Nullable public static String ucFirst(@Nullable final String str) { if (str == null || str.isEmpty()) { return str; } final char first = str.charAt(0); if (!Character.isLetter(first)) { return str; } final char capital = Character.toUpperCase(first); if(first == capital) { return str; } final StringBuilder sb = new StringBuilder(str); sb.setCharAt(0, capital); return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StringUtils.java
1
请完成以下Java代码
public void save(@NonNull final InvoiceAcct invoiceAcct) { // // Delete previous records queryBL.createQueryBuilder(I_C_Invoice_Acct.class) .addEqualsFilter(I_C_Invoice_Acct.COLUMNNAME_C_Invoice_ID, invoiceAcct.getInvoiceId()) .create() .delete(); // // Save new for (final InvoiceAcctRule rule : invoiceAcct.getRulesOrdered()) { final I_C_Invoice_Acct record = InterfaceWrapperHelper.newInstance(I_C_Invoice_Acct.class); record.setC_Invoice_ID(invoiceAcct.getInvoiceId().getRepoId()); record.setAD_Org_ID(invoiceAcct.getOrgId().getRepoId()); updateRecordFromRule(record, rule); InterfaceWrapperHelper.save(record);
} } private void updateRecordFromRule(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRule from) { updateRecordFromRuleMatcher(record, from.getMatcher()); record.setC_ElementValue_ID(from.getElementValueId().getRepoId()); } private void updateRecordFromRuleMatcher(@NonNull final I_C_Invoice_Acct record, @NonNull final InvoiceAcctRuleMatcher from) { record.setC_AcctSchema_ID(from.getAcctSchemaId().getRepoId()); record.setC_InvoiceLine_ID(InvoiceAndLineId.toRepoId(from.getInvoiceAndLineId())); record.setAccountName(from.getAccountConceptualName() != null ? from.getAccountConceptualName().getAsString() : null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\acct\InvoiceAcctRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class C_User_Role { private final ITrxManager trxManager = Services.get(ITrxManager.class); private final IUserDAO userDAO = Services.get(IUserDAO.class); private final ExportBPartnerToRabbitMQService exportToRabbitMQService; private final UserRoleRepository userRoleRepository; public C_User_Role(@NonNull final ExportBPartnerToRabbitMQService exportToRabbitMQService, final UserRoleRepository userRoleRepository) { this.exportToRabbitMQService = exportToRabbitMQService; this.userRoleRepository = userRoleRepository; } @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = I_C_User_Role.COLUMNNAME_Name)
public void triggerSyncBPartnerWithExternalSystem(@NonNull final I_C_User_Role userRole) { final Set<BPartnerId> bpartnerIds = userRoleRepository.getAssignedUsers(UserRoleId.ofRepoId(userRole.getC_User_Role_ID())) .stream() .map(userDAO::getBPartnerIdByUserId) .collect(Collectors.toSet()); if (bpartnerIds.isEmpty()) { return; } trxManager.runAfterCommit(() -> bpartnerIds.forEach(exportToRabbitMQService::enqueueBPartnerSync)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\interceptor\C_User_Role.java
2
请完成以下Java代码
public static DummyDeviceResponse generateRandomResponse() { final BigDecimal value = NumberUtils.randomBigDecimal(responseMinValue, responseMaxValue, 3); return new DummyDeviceResponse(value); } // // // // // private static class StaticStateHolder { private final HashMap<String, DeviceConfig> devicesByName = new HashMap<>(); private final ArrayListMultimap<AttributeCode, DeviceConfig> devicesByAttributeCode = ArrayListMultimap.create(); public synchronized void addDevice(final DeviceConfig device) { final String deviceName = device.getDeviceName(); final DeviceConfig existingDevice = removeDeviceByName(deviceName); devicesByName.put(deviceName, device); device.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.put(attributeCode, device)); logger.info("addDevice: {} -> {}", existingDevice, device); }
public synchronized @Nullable DeviceConfig removeDeviceByName(@NonNull final String deviceName) { final DeviceConfig existingDevice = devicesByName.remove(deviceName); if (existingDevice != null) { existingDevice.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.remove(attributeCode, existingDevice)); } return existingDevice; } public synchronized ImmutableList<DeviceConfig> getAllDevices() { return ImmutableList.copyOf(devicesByName.values()); } public synchronized ImmutableList<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode) { return ImmutableList.copyOf(devicesByAttributeCode.get(attributeCode)); } public ImmutableSet<AttributeCode> getAllAttributeCodes() { return ImmutableSet.copyOf(devicesByAttributeCode.keySet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDeviceConfigPool.java
1
请完成以下Java代码
public boolean contains(String key) { return get(key) != null; } /** * 词典大小 * * @return */ public int size() { return trie.size(); } /** * 从一行词典条目创建值
* * @param params 第一个元素为键,请注意跳过 * @return */ protected abstract V createValue(String[] params); /** * 文本词典加载完毕的回调函数 * * @param map */ protected void onLoaded(TreeMap<String, V> map) { } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonDictionary.java
1
请完成以下Java代码
public void setPrefix(String prefix) { Assert.notNull(prefix, "prefix cannot be null"); this.prefix = prefix; } /** * Whether to convert the authority value to upper case in the mapping. * @param convertToUpperCase defaults to {@code false} */ public void setConvertToUpperCase(boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } /** * Whether to convert the authority value to lower case in the mapping.
* @param convertToLowerCase defaults to {@code false} */ public void setConvertToLowerCase(boolean convertToLowerCase) { this.convertToLowerCase = convertToLowerCase; } /** * Sets a default authority to be assigned to all users * @param authority the name of the authority to be assigned to all users. */ public void setDefaultAuthority(String authority) { Assert.hasText(authority, "The authority name cannot be set to an empty value"); this.defaultAuthority = new SimpleGrantedAuthority(authority); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAuthorityMapper.java
1
请完成以下Java代码
public void deletePrivateAccess(final RemoveRecordPrivateAccessRequest request) { queryPrivateAccess(request.getPrincipal(), request.getRecordRef()) .create() .delete(); } private IQueryBuilder<I_AD_Private_Access> queryPrivateAccess( @NonNull final Principal principal, @NonNull final TableRecordReference recordRef) { return queryBL .createQueryBuilder(I_AD_Private_Access.class) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_User_ID, principal.getUserId()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_UserGroup_ID, principal.getUserGroupId()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_Record_ID, recordRef.getRecord_ID()); } @Override public void createMobileApplicationAccess(@NonNull final CreateMobileApplicationAccessRequest request) { mobileApplicationPermissionsRepository.createMobileApplicationAccess(request); resetCacheAfterTrxCommit(); } @Override public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId) { mobileApplicationPermissionsRepository.deleteMobileApplicationAccess(applicationId); } @Override public void deleteUserOrgAccessByUserId(final UserId userId) { queryBL.createQueryBuilder(I_AD_User_OrgAccess.class) .addEqualsFilter(I_AD_User_OrgAccess.COLUMNNAME_AD_User_ID, userId) .create()
.delete(); } @Override public void deleteUserOrgAssignmentByUserId(final UserId userId) { queryBL.createQueryBuilder(I_C_OrgAssignment.class) .addEqualsFilter(I_C_OrgAssignment.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } @Value(staticConstructor = "of") private static class RoleOrgPermissionsCacheKey { RoleId roleId; AdTreeId adTreeOrgId; } @Value(staticConstructor = "of") private static class UserOrgPermissionsCacheKey { UserId userId; AdTreeId adTreeOrgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsDAO.java
1
请完成以下Java代码
public class SqlComposedKey { public static SqlComposedKey of( @NonNull final ImmutableSet<String> keyColumnNames, @NonNull final ImmutableMap<String, Object> values) { return new SqlComposedKey(keyColumnNames, values); } @Getter @NonNull private final ImmutableSet<String> keyColumnNames; @NonNull private final ImmutableMap<String, Object> values; @Builder private SqlComposedKey( @NonNull @Singular final ImmutableSet<String> keyColumnNames, @NonNull @Singular final ImmutableMap<String, Object> values) { Check.assumeNotEmpty(keyColumnNames, "keyColumnNames is not empty"); this.keyColumnNames = keyColumnNames; this.values = values; } @Nullable public Object getValue(@NonNull final String keyColumnName) { return values.get(keyColumnName); } public Optional<Integer> getValueAsInteger(@NonNull final String keyColumnName) { return Optional.ofNullable(NumberUtils.asIntegerOrNull(getValue(keyColumnName))); } public <T extends RepoIdAware> Optional<T> getValueAsId(@NonNull final String keyColumnName, @NonNull final Class<T> type) { return getValueAsInteger(keyColumnName).map(repoId -> RepoIdAwares.ofRepoIdOrNull(repoId, type)); } /** * @return all values (including nulls) in the same order as the key column names are */ public ArrayList<Object> getSqlValuesList() { final ArrayList<Object> allValuesIncludingNulls = new ArrayList<>(keyColumnNames.size()); for (final String keyColumnName : keyColumnNames) { final Object value = getValue(keyColumnName); allValuesIncludingNulls.add(value); } return allValuesIncludingNulls; } public void forEach(@NonNull final BiConsumer<String, Object> keyAndValueConsumer) { for (final String keyColumnName : keyColumnNames) { final Object value = getValue(keyColumnName); keyAndValueConsumer.accept(keyColumnName, value); } } public SqlAndParams getSqlValuesCommaSeparated() { final SqlAndParams.Builder sqlBuilder = SqlAndParams.builder(); for (final String keyColumnName : keyColumnNames) {
final Object value = getValue(keyColumnName); if (!sqlBuilder.isEmpty()) { sqlBuilder.append(", "); } sqlBuilder.append("?", value); } return sqlBuilder.build(); } public String getSqlWhereClauseById(@NonNull final String tableAlias) { final StringBuilder sql = new StringBuilder(); for (final String keyFieldName : keyColumnNames) { final Object idPart = getValue(keyFieldName); if (sql.length() > 0) { sql.append(" AND "); } sql.append(tableAlias).append(".").append(keyFieldName); if (!JSONNullValue.isNull(idPart)) { sql.append("=").append(DB.TO_SQL(idPart)); } else { sql.append(" IS NULL"); } } return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlComposedKey.java
1
请完成以下Java代码
public static final PricingConditionsBreakId ofOrNull(final int discountSchemaId, final int discountSchemaBreakId) { if (discountSchemaId > 0 && discountSchemaBreakId > 0) { return of(discountSchemaId, discountSchemaBreakId); } else { return null; } } public static final boolean matching(final PricingConditionsId id, PricingConditionsBreakId breakId) { if (id == null) { return breakId == null; } else if (breakId == null) { return true; } else { return Objects.equals(id, breakId.getPricingConditionsId()); } } public static final void assertMatching(final PricingConditionsId id, PricingConditionsBreakId breakId) { if (!matching(id, breakId)) { throw new AdempiereException("" + id + " and " + breakId + " are not matching") .setParameter("pricingConditionsId", id) .setParameter("pricingConditionsBreakId", breakId);
} } private final PricingConditionsId pricingConditionsId; private final int discountSchemaBreakId; private PricingConditionsBreakId(@NonNull final PricingConditionsId pricingConditionsId, final int discountSchemaBreakId) { Check.assumeGreaterThanZero(discountSchemaBreakId, "discountSchemaBreakId"); this.pricingConditionsId = pricingConditionsId; this.discountSchemaBreakId = discountSchemaBreakId; } public boolean matchingDiscountSchemaId(final int discountSchemaId) { return pricingConditionsId.getRepoId() == discountSchemaId; } public int getDiscountSchemaId() { return pricingConditionsId.getRepoId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakId.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDateChanged() { if (previousTime == null) { return true; } return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate)); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isQtyChanged() { return getQtyDelta().signum() != 0; } // TODO figure out if we really need this public Candidate toCandidateWithQtyDelta() { return candidate.withQuantity(getQtyDelta()); } /** * Convenience method that returns a new instance whose included {@link Candidate} has the given id. */ public CandidateSaveResult withCandidateId(@Nullable final CandidateId candidateId) { return toBuilder() .candidate(candidate.withId(candidateId)) .build(); }
/** * Convenience method that returns a new instance with negated candidate quantity and previousQty */ public CandidateSaveResult withNegatedQuantity() { return toBuilder() .candidate(candidate.withNegatedQuantity()) .previousQty(previousQty == null ? null : previousQty.negate()) .build(); } public CandidateSaveResult withParentId(@Nullable final CandidateId parentId) { return toBuilder() .candidate(candidate.withParentId(parentId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateSaveResult.java
2
请在Spring Boot框架中完成以下Java代码
public Notification getPersonalDeliveryNotification() { return personalDeliveryNotification; } /** * Sets the value of the personalDeliveryNotification property. * * @param value * allowed object is * {@link Notification } * */ public void setPersonalDeliveryNotification(Notification value) { this.personalDeliveryNotification = value; } /** * Gets the value of the proactiveNotification 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 proactiveNotification property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProactiveNotification().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProactiveNotification } * * */ public List<ProactiveNotification> getProactiveNotification() { if (proactiveNotification == null) { proactiveNotification = new ArrayList<ProactiveNotification>(); } return this.proactiveNotification; } /** * Gets the value of the delivery property. * * @return * possible object is * {@link Delivery } * */ public Delivery getDelivery() { return delivery; } /** * Sets the value of the delivery property. * * @param value * allowed object is * {@link Delivery } * */
public void setDelivery(Delivery value) { this.delivery = value; } /** * Gets the value of the invoiceAddress property. * * @return * possible object is * {@link Address } * */ public Address getInvoiceAddress() { return invoiceAddress; } /** * Sets the value of the invoiceAddress property. * * @param value * allowed object is * {@link Address } * */ public void setInvoiceAddress(Address value) { this.invoiceAddress = value; } /** * Gets the value of the countrySpecificService property. * * @return * possible object is * {@link String } * */ public String getCountrySpecificService() { return countrySpecificService; } /** * Sets the value of the countrySpecificService property. * * @param value * allowed object is * {@link String } * */ public void setCountrySpecificService(String value) { this.countrySpecificService = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProductAndServiceData.java
2
请完成以下Java代码
public BigDecimal getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setRate(BigDecimal value) { this.rate = value; } /** * Gets the value of the taxblBaseAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getTaxblBaseAmt() { return taxblBaseAmt; } /** * Sets the value of the taxblBaseAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTaxblBaseAmt(ActiveOrHistoricCurrencyAndAmount value) { this.taxblBaseAmt = value; } /** * Gets the value of the ttlAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) { this.ttlAmt = value; } /**
* Gets the value of the dtls 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 dtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TaxRecordDetails1 } * * */ public List<TaxRecordDetails1> getDtls() { if (dtls == null) { dtls = new ArrayList<TaxRecordDetails1>(); } return this.dtls; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxAmount1.java
1
请完成以下Java代码
public org.compiere.model.I_C_BP_Group getCustomer_Group() { return get_ValueAsPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class); } @Override public void setCustomer_Group(final org.compiere.model.I_C_BP_Group Customer_Group) { set_ValueFromPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class, Customer_Group); } @Override public void setCustomer_Group_ID (final int Customer_Group_ID) { if (Customer_Group_ID < 1) set_Value (COLUMNNAME_Customer_Group_ID, null); else set_Value (COLUMNNAME_Customer_Group_ID, Customer_Group_ID); } @Override public int getCustomer_Group_ID() { return get_ValueAsInt(COLUMNNAME_Customer_Group_ID); } @Override public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup) { set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup); } @Override public boolean isExcludeBPGroup() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup); } @Override public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory) { set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory); } @Override public boolean isExcludeProductCategory() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) {
if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints) { set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints); } @Override public BigDecimal getPercentOfBasePoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
1
请完成以下Java代码
public static BankStatementReconciliationView cast(final IView view) { return (BankStatementReconciliationView)view; } @Getter private final PaymentsToReconcileView paymentsToReconcileView; @Builder private BankStatementReconciliationView( @NonNull final ViewId bankStatementViewId, final BankStatementLineAndPaymentsRows rows, @Nullable final List<RelatedProcessDescriptor> paymentToReconcilateProcesses) { super(bankStatementViewId, TranslatableStrings.empty(), rows.getBankStatementLineRows(), NullDocumentFilterDescriptorsProvider.instance); paymentsToReconcileView = PaymentsToReconcileView.builder() .bankStatementViewId(bankStatementViewId) .rows(rows.getPaymentToReconcileRows()) .processes(paymentToReconcilateProcesses) .build(); }
@Override public String getTableNameOrNull(final DocumentId documentId) { return null; } @Override public ViewId getIncludedViewId(final IViewRow row_NOTUSED) { return paymentsToReconcileView.getViewId(); } @Override protected BankStatementLineRows getRowsData() { return BankStatementLineRows.cast(super.getRowsData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementReconciliationView.java
1
请完成以下Java代码
private final ClientSetup getClientSetup() { if (_clientSetup == null) { _clientSetup = ClientSetup.newInstance(getCtx()); } return _clientSetup; } @Override protected void prepare() { try (final IAutoCloseable cacheFlagRestorer = CacheInterceptor.temporaryDisableCaching()) { final ClientSetup clientSetup = getClientSetup(); for (final ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameter() == null) { continue; } final String name = para.getParameterName(); if (PARAM_CompanyName.equalsIgnoreCase(name)) { clientSetup.setCompanyName(para.getParameterAsString()); } else if (PARAM_VATaxID.equalsIgnoreCase(name)) { clientSetup.setCompanyTaxID(para.getParameterAsString()); } else if (PARAM_C_Location_ID.equalsIgnoreCase(name)) { clientSetup.setCompanyAddressByLocationId(para.getParameterAsInt()); } else if (PARAM_Logo_ID.equalsIgnoreCase(name)) { clientSetup.setCompanyLogoByImageId(para.getParameterAsInt()); } else if (PARAM_AD_Language.equalsIgnoreCase(name)) { clientSetup.setAD_Language(para.getParameterAsString()); } else if (PARAM_C_Currency_ID.equalsIgnoreCase(name)) { clientSetup.setCurrencyId(para.getParameterAsRepoId(CurrencyId::ofRepoIdOrNull)); } // // else if (PARAM_FirstName.equalsIgnoreCase(name)) { clientSetup.setContactFirstName(para.getParameterAsString()); } else if (PARAM_LastName.equalsIgnoreCase(name)) { clientSetup.setContactLastName(para.getParameterAsString()); } // // else if (PARAM_AccountNo.equalsIgnoreCase(name)) { clientSetup.setAccountNo(para.getParameterAsString()); } else if (PARAM_IBAN.equalsIgnoreCase(name)) { clientSetup.setIBAN(para.getParameterAsString()); } else if (PARAM_C_Bank_ID.equalsIgnoreCase(name)) { clientSetup.setC_Bank_ID(para.getParameterAsInt()); } //
// else if (PARAM_Phone.equalsIgnoreCase(name)) { clientSetup.setPhone(para.getParameterAsString()); } else if (PARAM_Fax.equalsIgnoreCase(name)) { clientSetup.setFax(para.getParameterAsString()); } else if (PARAM_EMail.equalsIgnoreCase(name)) { clientSetup.setEMail(para.getParameterAsString()); } // // else if (PARAM_Description.equalsIgnoreCase(name)) { clientSetup.setBPartnerDescription(para.getParameterAsString()); } } } } @Override protected String doIt() throws Exception { try (final IAutoCloseable cacheFlagRestorer = CacheInterceptor.temporaryDisableCaching()) { final ClientSetup clientSetup = getClientSetup(); clientSetup.save(); return MSG_OK; } } @Override protected void postProcess(final boolean success) { if (!success) { return; } // Fully reset the cache CacheMgt.get().reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\AD_Client_Setup.java
1
请完成以下Java代码
private void updateInvoiceCandidates() { updateInvoiceCandidateColumn(I_C_Invoice_Candidate.COLUMNNAME_Bill_Location_ID, oldBPLocationId, newBPLocationId); updateInvoiceCandidateColumn(I_C_Invoice_Candidate.COLUMNNAME_Bill_Location_Value_ID, oldLocationId, newLocationId); updateInvoiceCandidateColumn(I_C_Invoice_Candidate.COLUMNNAME_Bill_Location_Override_ID, oldBPLocationId, newBPLocationId); updateInvoiceCandidateColumn(I_C_Invoice_Candidate.COLUMNNAME_Bill_Location_Override_Value_ID, oldLocationId, newLocationId); updateInvoiceCandidateColumn(I_C_Invoice_Candidate.COLUMNNAME_First_Ship_BPLocation_ID, oldLocationId, newLocationId); } private void updateInvoiceCandidateColumn(final String columnName, final RepoIdAware oldLocationId, final RepoIdAware newLocationId) { final ICompositeQueryUpdater<I_C_Invoice_Candidate> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_Invoice_Candidate.class) .addSetColumnValue(columnName, newLocationId); queryBL .createQueryBuilder(I_C_Invoice_Candidate.class) .addEqualsFilter(columnName, oldLocationId) .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false) .create() .update(queryUpdater); } private void updateFlatrateTerms() { updateFlatrateTermsColumn(I_C_Flatrate_Term.COLUMNNAME_Bill_Location_ID, oldBPLocationId, newBPLocationId); updateFlatrateTermsColumn(I_C_Flatrate_Term.COLUMNNAME_DropShip_Location_ID, oldBPLocationId, newBPLocationId); } private void updateFlatrateTermsColumn(final String columnName, final RepoIdAware oldLocationId, final RepoIdAware newLocationId) {
final Collection<String> disallowedFlatrateStatuses = ImmutableSet.of(X_C_Flatrate_Term.CONTRACTSTATUS_Voided, X_C_Flatrate_Term.CONTRACTSTATUS_Quit); final ICompositeQueryUpdater<I_C_Flatrate_Term> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_Flatrate_Term.class) .addSetColumnValue(columnName, newLocationId); queryBL .createQueryBuilder(I_C_Flatrate_Term.class) .addEqualsFilter(columnName, oldLocationId) .addNotInArrayFilter(I_C_Flatrate_Term.COLUMN_ContractStatus,disallowedFlatrateStatuses) .addCompareFilter(I_C_Flatrate_Term.COLUMN_EndDate, CompareQueryFilter.Operator.GREATER_OR_EQUAL, Env.getDate()) // .addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Processed, false) in this case contracts are already processed .create() .update(queryUpdater); } private void deactivateOldBPLocation() { newLocation.setIsBillToDefault(newLocation.isBillToDefault() || oldLocation.isBillToDefault()); newLocation.setIsShipToDefault(newLocation.isShipToDefault() || oldLocation.isShipToDefault()); newLocation.setIsBillTo(newLocation.isBillTo() || oldLocation.isBillTo()); newLocation.setIsShipTo(newLocation.isShipTo() || oldLocation.isShipTo()); oldLocation.setIsBillToDefault(false); oldLocation.setIsShipToDefault(false); oldLocation.setIsActive(false); bpartnerDAO.save(oldLocation); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\command\BPartnerLocationReplaceCommand.java
1
请在Spring Boot框架中完成以下Java代码
public FlushMode getFlushMode() { return this.flushMode; } public void setFlushMode(FlushMode flushMode) { this.flushMode = flushMode; } public SaveMode getSaveMode() { return this.saveMode; } public void setSaveMode(SaveMode saveMode) { this.saveMode = saveMode; } public @Nullable String getCleanupCron() { return this.cleanupCron; } public void setCleanupCron(@Nullable String cleanupCron) { this.cleanupCron = cleanupCron; } public ConfigureAction getConfigureAction() { return this.configureAction; } public void setConfigureAction(ConfigureAction configureAction) { this.configureAction = configureAction; } public RepositoryType getRepositoryType() { return this.repositoryType; } public void setRepositoryType(RepositoryType repositoryType) { this.repositoryType = repositoryType; } /** * Strategies for configuring and validating Redis. */ public enum ConfigureAction { /** * Ensure that Redis Keyspace events for Generic commands and Expired events are
* enabled. */ NOTIFY_KEYSPACE_EVENTS, /** * No not attempt to apply any custom Redis configuration. */ NONE } /** * Type of Redis session repository to auto-configure. */ public enum RepositoryType { /** * Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository. */ DEFAULT, /** * Auto-configure a RedisIndexedSessionRepository or * ReactiveRedisIndexedSessionRepository. */ INDEXED } }
repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java
2
请完成以下Java代码
public String getTextFormat() { return textFormatAttribute.getValue(this); } public void setTextFormat(String textFormat) { textFormatAttribute.setValue(this, textFormat); } public Text getText() { return textChild.getChild(this); } public void setText(Text text) { textChild.setChild(this, text); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(TextAnnotation.class, CMMN_ELEMENT_TEXT_ANNOTATION) .namespaceUri(CMMN11_NS)
.extendsType(Artifact.class) .instanceProvider(new ModelTypeInstanceProvider<TextAnnotation>() { public TextAnnotation newInstance(ModelTypeInstanceContext instanceContext) { return new TextAnnotationImpl(instanceContext); } }); textFormatAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TEXT_FORMAT) .defaultValue("text/plain") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); textChild = sequenceBuilder.element(Text.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TextAnnotationImpl.java
1
请完成以下Java代码
public ProcessInstanceBuilder messageName(String messageName) { this.messageName = messageName; return this; } @Override public ProcessInstanceBuilder name(String processInstanceName) { this.processInstanceName = processInstanceName; return this; } @Override public ProcessInstanceBuilder businessKey(String businessKey) { this.businessKey = businessKey; return this; } @Override public ProcessInstanceBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public ProcessInstanceBuilder variables(Map<String, Object> variables) { if (this.variables == null) { this.variables = new HashMap<>(); } if (variables != null) { for (String variableName : variables.keySet()) { this.variables.put(variableName, variables.get(variableName)); } } return this; } @Override public ProcessInstanceBuilder variable(String variableName, Object value) { if (this.variables == null) { this.variables = new HashMap<>(); } this.variables.put(variableName, value); return this; } @Override public ProcessInstanceBuilder transientVariables(Map<String, Object> transientVariables) { if (this.transientVariables == null) { this.transientVariables = new HashMap<>(); } if (transientVariables != null) { for (String variableName : transientVariables.keySet()) { this.transientVariables.put(variableName, transientVariables.get(variableName)); } } return this; } @Override public ProcessInstanceBuilder transientVariable(String variableName, Object value) { if (this.transientVariables == null) { this.transientVariables = new HashMap<>(); } this.transientVariables.put(variableName, value); return this; } @Override public ProcessInstance start() { return runtimeService.startProcessInstance(this); }
public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getMessageName() { return messageName; } public String getProcessInstanceName() { return processInstanceName; } public String getBusinessKey() { return businessKey; } public String getTenantId() { return tenantId; } public Map<String, Object> getVariables() { return variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java
1
请完成以下Java代码
public long size() { return rows.size(); } @Override public int getQueryLimit() { return -1; } @Override public boolean isQueryLimitHit() { return false; } @Override public ViewResult getPage( final int firstRow, final int pageLength, @NonNull final ViewRowsOrderBy orderBys) { final List<PickingSlotRow> pageRows = rows.getPage(firstRow, pageLength); return ViewResult.ofViewAndPage(this, firstRow, pageLength, orderBys.toDocumentQueryOrderByList(), pageRows); } @Override public PickingSlotRow getById(@NonNull final DocumentId id) throws EntityNotFoundException { return rows.getById(id); } @Override public LookupValuesPage getFilterParameterDropdown(final String filterId, final String filterParameterName, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public LookupValuesPage getFilterParameterTypeahead(final String filterId, final String filterParameterName, final String query, final ViewFilterParameterLookupEvaluationCtx ctx) { throw new UnsupportedOperationException(); } @Override public DocumentFilterList getStickyFilters() { return DocumentFilterList.EMPTY; } @Override public DocumentFilterList getFilters() { return filters; } @Override public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override
public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs, final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请在Spring Boot框架中完成以下Java代码
private Set<RuleChainId> updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map<String, String> labelsMap) { Set<RuleChainId> updatedRuleChains = new HashSet<>(); List<RuleChainOutputLabelsUsage> usageList = getOutputLabelUsage(tenantId, ruleChainId); for (RuleChainOutputLabelsUsage usage : usageList) { labelsMap.forEach((oldLabel, newLabel) -> { if (usage.getLabels().contains(oldLabel)) { updatedRuleChains.add(usage.getRuleChainId()); renameOutgoingLinks(tenantId, usage.getRuleNodeId(), oldLabel, newLabel); } }); } return updatedRuleChains; } private void renameOutgoingLinks(TenantId tenantId, RuleNodeId ruleNodeId, String oldLabel, String newLabel) { List<EntityRelation> relations = ruleChainService.getRuleNodeRelations(tenantId, ruleNodeId); for (EntityRelation relation : relations) { if (relation.getType().equals(oldLabel)) { relationService.deleteRelation(tenantId, relation);
relation.setType(newLabel); relationService.saveRelation(tenantId, relation); } } } private boolean isOutputRuleNode(RuleNode ruleNode) { return isRuleNode(ruleNode, TbRuleChainOutputNode.class); } private boolean isInputRuleNode(RuleNode ruleNode) { return isRuleNode(ruleNode, TbRuleChainInputNode.class); } private boolean isRuleNode(RuleNode ruleNode, Class<?> clazz) { return ruleNode != null && ruleNode.getType().equals(clazz.getName()); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\rule\DefaultTbRuleChainService.java
2
请完成以下Java代码
public void logout() { userSession.assertLoggedIn(); final Login loginService = getLoginService(); destroyMFSession(loginService); } @PostMapping("/resetPassword") public void resetPasswordRequest(@RequestBody final JSONResetPasswordRequest request) { userSession.assertNotLoggedIn(); usersService.createResetPasswordByEMailRequest(request.getEmail()); } @GetMapping("/resetPassword/{token}") @Deprecated public JSONResetPassword getResetPasswordInfo(@PathVariable("token") final String token) { return resetPasswordInitByToken(token); } @PostMapping("/resetPassword/{token}/init") public JSONResetPassword resetPasswordInitByToken(@PathVariable("token") final String token) { userSession.assertNotLoggedIn(); final I_AD_User user = usersService.getByPasswordResetCode(token); final String userADLanguage = user.getAD_Language(); if (userADLanguage != null && !Check.isBlank(userADLanguage)) { userSession.setAD_Language(userADLanguage); } return JSONResetPassword.builder() .fullname(user.getName()) .email(user.getEMail()) .token(token) .build(); } @GetMapping("/resetPassword/{token}/avatar") public ResponseEntity<byte[]> getUserAvatar( @PathVariable("token") final String token, @RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth, @RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight) { final I_AD_User user = usersService.getByPasswordResetCode(token); final WebuiImageId avatarId = WebuiImageId.ofRepoIdOrNull(user.getAvatar_ID()); if (avatarId == null)
{ return imageService.getEmptyImage(); } return imageService.getWebuiImage(avatarId, maxWidth, maxHeight) .toResponseEntity(); } @PostMapping("/resetPassword/{token}") public JSONLoginAuthResponse resetPasswordComplete( @PathVariable("token") final String token, @RequestBody final JSONResetPasswordCompleteRequest request) { userSession.assertNotLoggedIn(); if (!Objects.equals(token, request.getToken())) { throw new AdempiereException("@Invalid@ @PasswordResetCode@"); } final I_AD_User user = usersService.resetPassword(token, request.getPassword()); final String username = usersService.extractUserLogin(user); final HashableString password = usersService.extractUserPassword(user); return authenticate(username, password, null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\login\LoginRestController.java
1
请在Spring Boot框架中完成以下Java代码
public void setReplicationModeAttr(ReplicationModeEnum value) { this.replicationModeAttr = value; } /** * Gets the value of the replicationTypeAttr property. * * @return * possible object is * {@link ReplicationTypeEnum } * */ public ReplicationTypeEnum getReplicationTypeAttr() { return replicationTypeAttr; } /** * Sets the value of the replicationTypeAttr property. * * @param value * allowed object is * {@link ReplicationTypeEnum } * */ public void setReplicationTypeAttr(ReplicationTypeEnum value) { this.replicationTypeAttr = value; } /** * Gets the value of the versionAttr property. * * @return * possible object is * {@link String } * */ public String getVersionAttr() { if (versionAttr == null) { return "*"; } else { return versionAttr; } } /** * Sets the value of the versionAttr property. * * @param value * allowed object is * {@link String } * */ public void setVersionAttr(String value) { this.versionAttr = value; } /** * Gets the value of the sequenceNoAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getSequenceNoAttr() { return sequenceNoAttr; }
/** * Sets the value of the sequenceNoAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setSequenceNoAttr(BigInteger value) { this.sequenceNoAttr = value; } /** * Gets the value of the trxNameAttr property. * * @return * possible object is * {@link String } * */ public String getTrxNameAttr() { return trxNameAttr; } /** * Sets the value of the trxNameAttr property. * * @param value * allowed object is * {@link String } * */ public void setTrxNameAttr(String value) { this.trxNameAttr = value; } /** * Gets the value of the adSessionIDAttr property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getADSessionIDAttr() { return adSessionIDAttr; } /** * Sets the value of the adSessionIDAttr property. * * @param value * allowed object is * {@link BigInteger } * */ public void setADSessionIDAttr(BigInteger value) { this.adSessionIDAttr = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpCBPartnerProductVType.java
2
请完成以下Java代码
public final class AttributeSetDescriptor { public static final AttributeSetDescriptor NONE = AttributeSetDescriptor.builder() .attributeSetId(AttributeSetId.NONE) .name("NONE") .isInstanceAttribute(false) .mandatoryType(AttributeSetMandatoryType.NotMandatory) .attributes(ImmutableList.of()) .build(); @NonNull private final AttributeSetId attributeSetId; @NonNull private final String name; @Nullable private final String description; private final boolean isInstanceAttribute; @NonNull private final AttributeSetMandatoryType mandatoryType; @NonNull private final ImmutableList<AttributeId> attributeIdsInOrder; @NonNull @Getter(AccessLevel.NONE) private final ImmutableMap<AttributeId, AttributeSetAttribute> byId; @Builder private AttributeSetDescriptor( @NonNull final AttributeSetId attributeSetId, @NonNull final String name, @Nullable final String description, final boolean isInstanceAttribute, @NonNull final AttributeSetMandatoryType mandatoryType, @NonNull final List<AttributeSetAttribute> attributes) { this.attributeSetId = attributeSetId; this.name = name; this.description = description; this.isInstanceAttribute = isInstanceAttribute; this.mandatoryType = mandatoryType; this.attributeIdsInOrder = attributes.stream() .sorted(Comparator.comparing(AttributeSetAttribute::getSeqNo)) .map(AttributeSetAttribute::getAttributeId) .collect(ImmutableList.toImmutableList()); this.byId = Maps.uniqueIndex(attributes, AttributeSetAttribute::getAttributeId); } public ImmutableList<Attribute> getAttributesInOrder() { return attributeIdsInOrder.stream() .map(byId::get) .map(AttributeSetAttribute::getAttribute) .collect(ImmutableList.toImmutableList()); } public boolean contains(@NonNull final AttributeId attributeId) { return byId.containsKey(attributeId); }
public Optional<AttributeSetAttribute> getByAttributeId(@NonNull final AttributeId attributeId) { return Optional.ofNullable(byId.get(attributeId)); } public OptionalBoolean getMandatoryOnReceipt(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnReceipt) .orElse(OptionalBoolean.UNKNOWN); } public OptionalBoolean getMandatoryOnShipment(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnShipment) .orElse(OptionalBoolean.UNKNOWN); } public OptionalBoolean getMandatoryOnPicking(@NonNull final AttributeId attributeId) { return getByAttributeId(attributeId) .map(AttributeSetAttribute::getMandatoryOnPicking) .orElse(OptionalBoolean.UNKNOWN); } public boolean isASIMandatory(@NonNull final SOTrx soTrx) { if (!isInstanceAttribute) { return false; } else { return mandatoryType.isASIMandatory(soTrx); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\AttributeSetDescriptor.java
1
请完成以下Java代码
public class RuntimeReceiveMessagePayloadEventListener implements ReceiveMessagePayloadEventListener { private final RuntimeService runtimeService; private final ManagementService managementService; public RuntimeReceiveMessagePayloadEventListener( RuntimeService runtimeService, ManagementService managementService ) { this.runtimeService = runtimeService; this.managementService = managementService; } @Override public void receiveMessage(ReceiveMessagePayload messagePayload) { String messageName = messagePayload.getName(); String correlationKey = messagePayload.getCorrelationKey(); EventSubscriptionEntity subscription = managementService.executeCommand( new FindMessageEventSubscription(messageName, correlationKey) ); if (subscription != null && Objects.equals(correlationKey, subscription.getConfiguration())) { Map<String, Object> variables = messagePayload.getVariables(); String executionId = subscription.getExecutionId(); runtimeService.messageEventReceived(messageName, executionId, variables); } else { throw new ActivitiObjectNotFoundException(
"Message subscription name '" + messageName + "' with correlation key '" + correlationKey + "' not found." ); } } static class FindMessageEventSubscription implements Command<EventSubscriptionEntity> { private final String messageName; private final String correlationKey; public FindMessageEventSubscription(String messageName, String correlationKey) { this.messageName = messageName; this.correlationKey = correlationKey; } public EventSubscriptionEntity execute(CommandContext commandContext) { return new EventSubscriptionQueryImpl(commandContext) .eventType("message") .eventName(messageName) .configuration(correlationKey) .singleResult(); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\RuntimeReceiveMessagePayloadEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public void process(final Exchange exchange) { final PushBOMsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_PUSH_BOMs_CONTEXT, PushBOMsRouteContext.class); if (Check.isBlank(context.getExportDirectoriesBasePath())) { exchange.getIn().setBody(null); return; } final JsonBOM jsonBOM = context.getJsonBOM(); final JsonAttachmentRequest attachmentRequest = getAttachmentRequest(jsonBOM, context.getExportDirectoriesBasePath()); exchange.getIn().setBody(attachmentRequest); } @Nullable private JsonAttachmentRequest getAttachmentRequest( @NonNull final JsonBOM jsonBOM, @NonNull final String basePathForExportDirectories) { final String filePath = jsonBOM.getAttachmentFilePath(); if (Check.isBlank(filePath)) { return null; } final String bpartnerMetasfreshId = jsonBOM.getBPartnerMetasfreshId(); if (Check.isBlank(bpartnerMetasfreshId)) { throw new RuntimeCamelException("Missing METASFRESHID! ARTNRID=" + jsonBOM.getProductId()); }
final JsonExternalReferenceTarget targetBPartner = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_BPARTNER, bpartnerMetasfreshId); final JsonExternalReferenceTarget targetProduct = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_PRODUCT, ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId())); final JsonAttachment attachment = JsonAttachmentUtil.createLocalFileJsonAttachment(basePathForExportDirectories, filePath); return JsonAttachmentRequest.builder() .targets(ImmutableList.of(targetBPartner, targetProduct)) .orgCode(getAuthOrgCode()) .attachment(attachment) .build(); } @NonNull private String getAuthOrgCode() { return ((TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials()).getOrgCode(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\ProductsAttachFileProcessor.java
2
请完成以下Java代码
private void cut() { } @Around("cut()") public Object around(ProceedingJoinPoint point) throws Throwable { Signature signature = point.getSignature(); MethodSignature methodSignature = null; if (!(signature instanceof MethodSignature)) { throw new IllegalArgumentException("该注解只能用于方法"); } methodSignature = (MethodSignature) signature; Object target = point.getTarget(); Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes()); DataSource datasource = currentMethod.getAnnotation(DataSource.class); if (datasource != null) { DataSourceContextHolder.setDataSourceType(datasource.name()); log.debug("设置数据源为:" + datasource.name()); } else {
DataSourceContextHolder.setDataSourceType(DSEnum.DATA_SOURCE_CORE); log.debug("设置数据源为:dataSourceCore"); } try { return point.proceed(); } finally { log.debug("清空数据源信息!"); DataSourceContextHolder.clearDataSourceType(); } } /** * aop的顺序要早于spring的事务 */ @Override public int getOrder() { return 1; } }
repos\SpringBootBucket-master\springboot-multisource\src\main\java\com\xncoding\pos\common\aop\MultiSourceExAop.java
1
请完成以下Java代码
protected void configureTenantCheck(QueryParameters query) { TenantCheck tenantCheck = query.getTenantCheck(); if (isTenantCheckEnabled()) { Authentication currentAuthentication = getCurrentAuthentication(); tenantCheck.setTenantCheckEnabled(true); tenantCheck.setAuthTenantIds(currentAuthentication.getTenantIds()); } else { tenantCheck.setTenantCheckEnabled(false); tenantCheck.setAuthTenantIds(null); } } /** * Add a new {@link PermissionCheck} with the given values. */ protected void addPermissionCheck(QueryParameters query, Resource resource, String queryParam, Permission permission) { if(!isPermissionDisabled(permission)){ PermissionCheck permCheck = new PermissionCheck();
permCheck.setResource(resource); permCheck.setResourceIdQueryParam(queryParam); permCheck.setPermission(permission); query.getAuthCheck().addAtomicPermissionCheck(permCheck); } } protected boolean isPermissionDisabled(Permission permission) { List<String> disabledPermissions = getProcessEngine().getProcessEngineConfiguration().getDisabledPermissions(); for (String disabledPerm : disabledPermissions) { if (!disabledPerm.equals(permission.getName())) { return true; } } return false; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\plugin\resource\AbstractCockpitPluginResource.java
1
请完成以下Java代码
public int getC_OrderTax_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderTax_ID); } @Override public void setC_Tax_ID (final int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, C_Tax_ID); } @Override public int getC_Tax_ID() { return get_ValueAsInt(COLUMNNAME_C_Tax_ID); } @Override public void setIsDocumentLevel (final boolean IsDocumentLevel) { set_Value (COLUMNNAME_IsDocumentLevel, IsDocumentLevel); } @Override public boolean isDocumentLevel() { return get_ValueAsBoolean(COLUMNNAME_IsDocumentLevel); } @Override public void setIsPackagingTax (final boolean IsPackagingTax) { set_Value (COLUMNNAME_IsPackagingTax, IsPackagingTax); } @Override public boolean isPackagingTax() { return get_ValueAsBoolean(COLUMNNAME_IsPackagingTax); } @Override public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setIsWholeTax (final boolean IsWholeTax) { set_Value (COLUMNNAME_IsWholeTax, IsWholeTax); }
@Override public boolean isWholeTax() { return get_ValueAsBoolean(COLUMNNAME_IsWholeTax); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderTax.java
1
请完成以下Java代码
public Optional<ZonedDateTime> getCreatedValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getCreated); } public Optional<UserId> getCreatedByValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getCreatedBy); } public Optional<ZonedDateTime> getUpdatedValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getUpdated); } public Optional<UserId> getUpdatedByValue(@NonNull final DataEntryFieldId fieldId) { return getCreatedUpdatedInfo(fieldId) .map(CreatedUpdatedInfo::getUpdatedBy); }
public Optional<CreatedUpdatedInfo> getCreatedUpdatedInfo(@NonNull final DataEntryFieldId fieldId) { return getOptional(fieldId) .map(DataEntryRecordField::getCreatedUpdatedInfo); } public Optional<Object> getFieldValue(@NonNull final DataEntryFieldId fieldId) { return getOptional(fieldId) .map(DataEntryRecordField::getValue); } private Optional<DataEntryRecordField<?>> getOptional(@NonNull final DataEntryFieldId fieldId) { return Optional.ofNullable(fields.get(fieldId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecord.java
1
请在Spring Boot框架中完成以下Java代码
private void unmarkBillToDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setBillToDefault(false); } } private void unmarkPurchaseDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setPurchaseDefault(false); } } private void unmarkSalesDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setSalesDefault(false); } }
private void unmarkShipToDefaultContacts(final List<BPartnerContact> contacts) { for (final BPartnerContact contact : contacts) { final BPartnerContactType contactType = contact.getContactType(); if (contactType == null) { continue; } contactType.setShipToDefault(false); } } private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm) { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(newTerm.getAD_Org_ID())); return FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID())) .qty(newTerm.getPlannedQtyPerUnit()) .term(newTerm) .priceDate(TimeUtil.asLocalDate(newTerm.getStartDate(), timeZone)) .build() .computeOrThrowEx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\service\OrgChangeCommand.java
2
请完成以下Java代码
public Optional<BPartnerLocationId> resolveBPartnerLocationExternalIdentifier(@NonNull final BPartnerId bPartnerId, @NonNull final OrgId orgId, @NonNull final ExternalIdentifier externalIdentifier) { return bPartnerMasterdataProvider.resolveBPartnerLocationExternalIdentifier(bPartnerId, orgId, externalIdentifier); } @NonNull public Optional<UserId> resolveUserExternalIdentifier(@NonNull final OrgId orgId, @NonNull final ExternalIdentifier externalIdentifier) { return bPartnerMasterdataProvider.resolveUserExternalIdentifier(orgId, externalIdentifier); } public boolean isAutoInvoice(@NonNull final JsonOLCandCreateRequest request, @NonNull final BPartnerId bpartnerId) { return bPartnerMasterdataProvider.isAutoInvoice(request, bpartnerId); } @Nullable public PaymentRule getPaymentRule(final JsonOLCandCreateRequest request) { final JSONPaymentRule jsonPaymentRule = request.getPaymentRule(); if (jsonPaymentRule == null) { return null; } if (JSONPaymentRule.Paypal.equals(jsonPaymentRule)) { return PaymentRule.PayPal; } if (JSONPaymentRule.OnCredit.equals(jsonPaymentRule)) { return PaymentRule.OnCredit; } if (JSONPaymentRule.DirectDebit.equals(jsonPaymentRule)) { return PaymentRule.DirectDebit; } throw MissingResourceException.builder() .resourceName("paymentRule") .resourceIdentifier(jsonPaymentRule.getCode()) .parentResource(request) .build(); } public PaymentTermId getPaymentTermId(@NonNull final IdentifierString paymentTerm, @NonNull final Object parent, @NonNull final OrgId orgId) { final PaymentTermQueryBuilder queryBuilder = PaymentTermQuery.builder(); queryBuilder.orgId(orgId); switch (paymentTerm.getType()) { case EXTERNAL_ID: queryBuilder.externalId(paymentTerm.asExternalId()); break;
case VALUE: queryBuilder.value(paymentTerm.asValue()); break; default: throw new InvalidIdentifierException(paymentTerm); } final Optional<PaymentTermId> paymentTermId = paymentTermRepo.firstIdOnly(queryBuilder.build()); return paymentTermId.orElseThrow(() -> MissingResourceException.builder() .resourceName("PaymentTerm") .resourceIdentifier(paymentTerm.toJson()) .parentResource(parent).build()); } @Nullable public BPartnerId getSalesRepBPartnerId(@NonNull final BPartnerId bPartnerId) { final I_C_BPartner bPartner = bPartnerDAO.getById(bPartnerId); return BPartnerId.ofRepoIdOrNull(bPartner.getC_BPartner_SalesRep_ID()); } @NonNull public ExternalSystemId getExternalSystemId(@NonNull final ExternalSystemType type) { return externalSystemRepository.getIdByType(type); } @Nullable public Incoterms getIncoterms(@NonNull final JsonOLCandCreateRequest request, @NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId) { return bPartnerMasterdataProvider.getIncoterms(request, orgId, bPartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\MasterdataProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class HardwareTrayId implements RepoIdAware { int repoId; @NonNull HardwarePrinterId printerId; public static HardwareTrayId cast(@Nullable final RepoIdAware repoIdAware) { return (HardwareTrayId)repoIdAware; } public static HardwareTrayId ofRepoId(@NonNull final HardwarePrinterId printerId, final int trayId) { return new HardwareTrayId(printerId, trayId); } public static HardwareTrayId ofRepoId(final int printerId, final int trayId) { return new HardwareTrayId(HardwarePrinterId.ofRepoId(printerId), trayId); } public static HardwareTrayId ofRepoIdOrNull( @Nullable final Integer printerId, @Nullable final Integer trayId) { return printerId != null && printerId > 0 && trayId != null && trayId > 0 ? ofRepoId(printerId, trayId) : null; }
public static HardwareTrayId ofRepoIdOrNull( @Nullable final HardwarePrinterId printerId, final int trayId) { return printerId != null && trayId > 0 ? ofRepoId(printerId, trayId) : null; } private HardwareTrayId(@NonNull final HardwarePrinterId printerId, final int trayId) { this.repoId = Check.assumeGreaterThanZero(trayId, "trayId"); this.printerId = printerId; } public static int toRepoId(@Nullable final HardwareTrayId trayId) { return trayId != null ? trayId.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwareTrayId.java
2
请完成以下Java代码
public String getFirstName() { return firstName; } @Override public void setFirstName(String firstName) { this.firstName = firstName; } @Override public String getLastName() { return lastName; } @Override public void setLastName(String lastName) { this.lastName = lastName; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; }
// Default constructor for Gson public StudentV2() { } public StudentV2(String firstName, String lastName, String major) { this.firstName = firstName; this.lastName = lastName; this.major = major; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof StudentV2)) return false; StudentV2 studentV2 = (StudentV2) o; return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major); } @Override public int hashCode() { return Objects.hash(firstName, lastName, major); } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\StudentV2.java
1
请完成以下Java代码
public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; } public String getMessageRef() { return messageRef; } public void setMessageRef(String messageRef) { this.messageRef = messageRef; } public String toString() { return sourceRef + " --> " + targetRef;
} public MessageFlow clone() { MessageFlow clone = new MessageFlow(); clone.setValues(this); return clone; } public void setValues(MessageFlow otherFlow) { super.setValues(otherFlow); setName(otherFlow.getName()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setMessageRef(otherFlow.getMessageRef()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MessageFlow.java
1
请完成以下Java代码
public Object getValue(VariableScope variableScope) { return getValue(variableScope, null); } public Object getValue(VariableScope variableScope, BaseDelegateExecution contextExecution) { ELContext elContext = expressionManager.getElContext(variableScope); try { ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext, contextExecution); Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(invocation); return invocation.getInvocationResult(); } catch (PropertyNotFoundException pnfe) { throw new ProcessEngineException("Unknown property used in expression: " + expressionText+". Cause: "+pnfe.getMessage(), pnfe); } catch (MethodNotFoundException mnfe) { throw new ProcessEngineException("Unknown method used in expression: " + expressionText+". Cause: "+mnfe.getMessage(), mnfe); } catch(ELException ele) { Throwable cause = ele.getCause(); if (cause != null) { throw new ProcessEngineException(cause); } else { throw new ProcessEngineException("Error while evaluating expression: " + expressionText + ". Cause: " + ele.getMessage(), ele); } } catch (Exception e) { throw new ProcessEngineException("Error while evaluating expression: " + expressionText+". Cause: "+e.getMessage(), e); } } public void setValue(Object value, VariableScope variableScope) { setValue(value, variableScope, null);
} public void setValue(Object value, VariableScope variableScope, BaseDelegateExecution contextExecution) { ELContext elContext = expressionManager.getElContext(variableScope); try { ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value, contextExecution); Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(invocation); } catch (Exception e) { throw new ProcessEngineException("Error while evaluating expression: " + expressionText+". Cause: "+e.getMessage(), e); } } @Override public String toString() { if(valueExpression != null) { return valueExpression.getExpressionString(); } return super.toString(); } @Override public boolean isLiteralText() { return valueExpression.isLiteralText(); } public String getExpressionText() { return expressionText; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\JuelExpression.java
1
请在Spring Boot框架中完成以下Java代码
public class ADUIElementGroupNameFQ { @NonNull AdUIElementGroupId uiElementGroupId; String name; ADUIColumnNameFQ uiColumnName; boolean missing; public static ADUIElementGroupNameFQ missing(@NonNull final AdUIElementGroupId uiElementGroupId) { return builder().uiElementGroupId(uiElementGroupId).missing(true).build(); } @Override public String toString() {return toShortString();} public String toShortString() { if (missing) { return "<" + uiElementGroupId.getRepoId() + ">"; } else
{ final StringBuilder sb = new StringBuilder(); if (uiColumnName != null) { sb.append(uiColumnName.toShortString()); } if (sb.length() > 0) { sb.append(" -> "); } sb.append(name); return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\ADUIElementGroupNameFQ.java
2
请完成以下Java代码
private DocumentFilter createAreaSearchFilter(final I_C_Location location) { final DocumentEntityDescriptor entityDescriptor = documentCollection.getDocumentEntityDescriptor(getWindowId()); final GeoLocationDocumentQuery query = createGeoLocationQuery(location); return geoLocationDocumentService.createDocumentFilter(entityDescriptor, query); } private GeoLocationDocumentQuery createGeoLocationQuery(final I_C_Location location) { final CountryId countryId = CountryId.ofRepoId(location.getC_Country_ID()); final ITranslatableString countryName = countriesRepo.getCountryNameById(countryId); return GeoLocationDocumentQuery.builder() .country(IntegerLookupValue.of(countryId, countryName)) .address1(location.getAddress1()) .city(location.getCity()) .postal(location.getPostal()) .distanceInKm(distanceInKm) .visitorsAddress(visitorsAddress) .build(); }
private I_C_Location getSelectedLocationOrFirstAvailable() { final Set<Integer> bpLocationIds = getSelectedIncludedRecordIds(I_C_BPartner_Location.class); if (!bpLocationIds.isEmpty()) { // retrieve the selected location final LocationId locationId = bpartnersRepo.getBPartnerLocationAndCaptureIdInTrx(BPartnerLocationId.ofRepoId(getRecord_ID(), bpLocationIds.iterator().next())).getLocationCaptureId(); return locationsRepo.getById(locationId); } else { // retrieve the first bpartner location available final List<I_C_BPartner_Location> partnerLocations = bpartnersRepo.retrieveBPartnerLocations(BPartnerId.ofRepoId(getRecord_ID())); if (!partnerLocations.isEmpty()) { return locationsRepo.getById(LocationId.ofRepoId(partnerLocations.get(0).getC_Location_ID())); } } throw new AdempiereException("@NotFound@ @C_Location_ID@"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\location\geocoding\process\C_BPartner_Window_AreaSearchProcess.java
1
请完成以下Java代码
private static Method getGroupsForUserMethod() { if (getGroupsForUser == null) { getGroupsForUser = getMethod("com.ibm.websphere.security.UserRegistry", "getGroupsForUser", new String[] { "java.lang.String" }); } return getGroupsForUser; } private static Method getSecurityNameMethod() { if (getSecurityName == null) { getSecurityName = getMethod("com.ibm.websphere.security.cred.WSCredential", "getSecurityName", new String[] {}); } return getSecurityName; } private static Method getNarrowMethod() { if (narrow == null) { narrow = getMethod(PORTABLE_REMOTE_OBJECT_CLASSNAME, "narrow", new String[] { Object.class.getName(), Class.class.getName() }); }
return narrow; } // SEC-803 private static Class<?> getWSCredentialClass() { if (wsCredentialClass == null) { wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential"); } return wsCredentialClass; } private static Class<?> getClass(String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { logger.error("Required class " + className + " not found"); throw new RuntimeException("Required class " + className + " not found", ex); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\websphere\DefaultWASUsernameAndGroupsExtractor.java
1
请完成以下Java代码
public User editUser(User forEdit) throws UserException { try { if (forEdit.getId() == null) throw new UserException("ID cannot be blank"); User toEdit = userMap.get(forEdit.getId()); if (toEdit == null) throw new UserException("User not found"); if (forEdit.getEmail() != null) { toEdit.setEmail(forEdit.getEmail()); } if (forEdit.getFirstName() != null) { toEdit.setFirstName(forEdit.getFirstName()); } if (forEdit.getLastName() != null) { toEdit.setLastName(forEdit.getLastName()); } if (forEdit.getId() != null) { toEdit.setId(forEdit.getId()); } return toEdit;
} catch (Exception ex) { throw new UserException(ex.getMessage()); } } @Override public void deleteUser(String id) { userMap.remove(id); } @Override public boolean userExist(String id) { return userMap.containsKey(id); } }
repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\UserServiceMapImpl.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } /** * Set the creates the time. * * @param createTime the creates the time */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * Get the update by. * * @return the update by */ public String getUpdateBy() { return updateBy; } /** * Set the update by. * * @param updateBy the update by */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } /** * Get the update time. * * @return the update time */ public Date getUpdateTime() { return updateTime; } /** * Set the update time. * * @param updateTime the update time */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /** * Get the disabled. * * @return the disabled
*/ public Integer getDisabled() { return disabled; } /** * Set the disabled. * * @param disabled the disabled */ public void setDisabled(Integer disabled) { this.disabled = disabled; } /** * Get the theme. * * @return the theme */ public String getTheme() { return theme; } /** * Set the theme. * * @param theme theme */ public void setTheme(String theme) { this.theme = theme; } /** * Get the checks if is ldap. * * @return the checks if is ldap */ public Integer getIsLdap() { return isLdap; } /** * Set the checks if is ldap. * * @param isLdap the checks if is ldap */ public void setIsLdap(Integer isLdap) { this.isLdap = isLdap; } }
repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java
1
请完成以下Java代码
public WFActivity getActivityById(@NonNull final WFActivityId id) { return getActivityByIdOptional(id) .orElseThrow(() -> new AdempiereException(NO_ACTIVITY_ERROR_MSG) .appendParametersToMessage() .setParameter("ID", id) .setParameter("WFProcess", this)); } @NonNull public Optional<WFActivity> getActivityByIdOptional(@NonNull final WFActivityId id) { return Optional.ofNullable(activitiesById.get(id)); } public WFProcess withChangedActivityStatus( @NonNull final WFActivityId wfActivityId, @NonNull final WFActivityStatus newActivityStatus) { return withChangedActivityById(wfActivityId, wfActivity -> wfActivity.withStatus(newActivityStatus));
} private WFProcess withChangedActivityById(@NonNull final WFActivityId wfActivityId, @NonNull final UnaryOperator<WFActivity> remappingFunction) { return withChangedActivities(wfActivity -> wfActivity.getId().equals(wfActivityId) ? remappingFunction.apply(wfActivity) : wfActivity); } private WFProcess withChangedActivities(@NonNull final UnaryOperator<WFActivity> remappingFunction) { final ImmutableList<WFActivity> activitiesNew = CollectionUtils.map(this.activities, remappingFunction); return !Objects.equals(this.activities, activitiesNew) ? toBuilder().activities(activitiesNew).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomerService { @Autowired private OrderClient orderClient; private List<Customer> customers = Arrays.asList( new Customer(1, "John", "Smith"), new Customer(2, "Deny", "Dominic")); @GetMapping public List<Customer> getAllCustomers() { return customers; } @GetMapping("/{id}") public Customer getCustomerById(@PathVariable int id) { return customers.stream()
.filter(customer -> customer.getId() == id) .findFirst() .orElseThrow(IllegalArgumentException::new); } @PostMapping(value = "/order") public String sendOrder(@RequestBody Map<String, Object> body) { OrderDTO dto = new OrderDTO(); dto.setCustomerId((Integer) body.get("customerId")); dto.setItemId((String) body.get("itemId")); OrderResponse response = orderClient.order(dto); return response.getStatus(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\customer-service\src\main\java\com\baeldung\customerservice\CustomerService.java
2
请在Spring Boot框架中完成以下Java代码
public boolean configureMessageConverters(final List<MessageConverter> messageConverters) { final MappingJackson2MessageConverter jsonConverter = new MappingJackson2MessageConverter(); jsonConverter.setObjectMapper(JsonObjectMapperHolder.sharedJsonObjectMapper()); messageConverters.add(jsonConverter); return true; } private static class LoggingChannelInterceptor implements ChannelInterceptor { private static final Logger logger = LogManager.getLogger(LoggingChannelInterceptor.class); @Override public void afterSendCompletion(final @NonNull Message<?> message, final @NonNull MessageChannel channel, final boolean sent, final Exception ex) { if (!sent)
{ logger.warn("Failed sending: message={}, channel={}, sent={}", message, channel, sent, ex); } } @Override public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex) { if (ex != null) { logger.warn("Failed receiving: message={}, channel={}", message, channel, ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\config\WebsocketConfig.java
2
请完成以下Java代码
public List<String> getAuthenticatedGroupIds() { IdentityService identityService = processEngineConfiguration.getIdentityService(); Authentication currentAuthentication = identityService.getCurrentAuthentication(); if(currentAuthentication == null) { return null; } else { return currentAuthentication.getGroupIds(); } } public void enableAuthorizationCheck() { authorizationCheckEnabled = true; } public void disableAuthorizationCheck() { authorizationCheckEnabled = false; } public boolean isAuthorizationCheckEnabled() { return authorizationCheckEnabled; } public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { this.authorizationCheckEnabled = authorizationCheckEnabled; } public void enableUserOperationLog() { userOperationLogEnabled = true; } public void disableUserOperationLog() { userOperationLogEnabled = false; } public boolean isUserOperationLogEnabled() { return userOperationLogEnabled; } public void setLogUserOperationEnabled(boolean userOperationLogEnabled) { this.userOperationLogEnabled = userOperationLogEnabled; } public void enableTenantCheck() { tenantCheckEnabled = true; } public void disableTenantCheck() { tenantCheckEnabled = false; } public void setTenantCheckEnabled(boolean tenantCheckEnabled) { this.tenantCheckEnabled = tenantCheckEnabled; } public boolean isTenantCheckEnabled() { return tenantCheckEnabled; } public JobEntity getCurrentJob() { return currentJob;
} public void setCurrentJob(JobEntity currentJob) { this.currentJob = currentJob; } public boolean isRestrictUserOperationLogToAuthenticatedUsers() { return restrictUserOperationLogToAuthenticatedUsers; } public void setRestrictUserOperationLogToAuthenticatedUsers(boolean restrictUserOperationLogToAuthenticatedUsers) { this.restrictUserOperationLogToAuthenticatedUsers = restrictUserOperationLogToAuthenticatedUsers; } public String getOperationId() { if (!getOperationLogManager().isUserOperationLogEnabled()) { return null; } if (operationId == null) { operationId = Context.getProcessEngineConfiguration().getIdGenerator().getNextId(); } return operationId; } public void setOperationId(String operationId) { this.operationId = operationId; } public OptimizeManager getOptimizeManager() { return getSession(OptimizeManager.class); } public <T> void executeWithOperationLogPrevented(Command<T> command) { boolean initialLegacyRestrictions = isRestrictUserOperationLogToAuthenticatedUsers(); disableUserOperationLog(); setRestrictUserOperationLogToAuthenticatedUsers(true); try { command.execute(this); } finally { enableUserOperationLog(); setRestrictUserOperationLogToAuthenticatedUsers(initialLegacyRestrictions); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContext.java
1
请在Spring Boot框架中完成以下Java代码
public class Application implements CommandLineRunner { private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(Application.class); @Autowired private PersonRepository repository; @Autowired private DatabaseSeeder dbSeeder; public static void main(String[] args) { System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "jdbcintro"); SpringApplication.run(Application.class, args); } @Override public void run(String... arg0) throws Exception { LOGGER.info("@@ Inserting Data...."); dbSeeder.insertData(); LOGGER.info("@@ findAll() call..."); repository.findAll() .forEach(person -> LOGGER.info(person.toString())); LOGGER.info("@@ findById() call..."); Optional<Person> optionalPerson = repository.findById(1L); optionalPerson.ifPresent(person -> LOGGER.info(person.toString())); LOGGER.info("@@ save() call...");
Person newPerson = new Person("Franz", "Kafka"); Person result = repository.save(newPerson); LOGGER.info(result.toString()); LOGGER.info("@@ delete"); optionalPerson.ifPresent(person -> repository.delete(person)); LOGGER.info("@@ findAll() call..."); repository.findAll() .forEach(person -> LOGGER.info(person.toString())); LOGGER.info("@@ findByFirstName() call..."); repository.findByFirstName("Franz") .forEach(person -> LOGGER.info(person.toString())); LOGGER.info("@@ updateByFirstName() call..."); repository.updateByFirstName(2L, "Date Inferno"); repository.findAll() .forEach(person -> LOGGER.info(person.toString())); } }
repos\tutorials-master\persistence-modules\spring-data-jdbc\src\main\java\com\baeldung\springdatajdbcintro\Application.java
2
请完成以下Java代码
public class PeriodStatus extends JavaProcess { /** Action */ private String p_PeriodAction = null; @Override protected void prepare() { final ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { final String name = para[i].getParameterName(); if (para[i].getParameter() == null) { ; } else if (name.equals("PeriodAction")) { p_PeriodAction = (String)para[i].getParameter(); } } } @Override protected String doIt() throws Exception { final I_C_Period period = getRecord(I_C_Period.class); final String newPeriodStatus = Services.get(IPeriodBL.class).getPeriodStatusForAction(p_PeriodAction); // // Retrieve period controls final List<I_C_PeriodControl> periodControls = Services.get(IQueryBL.class) .createQueryBuilder(I_C_PeriodControl.class, getCtx(), getTrxName()) .addEqualsFilter(I_C_PeriodControl.COLUMN_C_Period_ID, period.getC_Period_ID()) .addOnlyActiveRecordsFilter() .create() .list(); // // Update the period controls for (final I_C_PeriodControl pc : periodControls) { // Don't update permanently closed period controls if (X_C_PeriodControl.PERIODSTATUS_PermanentlyClosed.equals(pc.getPeriodStatus()))
{ continue; } pc.setPeriodStatus(newPeriodStatus); pc.setPeriodAction(X_C_PeriodControl.PERIODACTION_NoAction); InterfaceWrapperHelper.save(pc); } return "@Ok@"; } @Override protected void postProcess(boolean success) { // // Reset caches CacheMgt.get().reset(I_C_PeriodControl.Table_Name); final int periodId = getRecord_ID(); CacheMgt.get().reset(I_C_Period.Table_Name, periodId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\PeriodStatus.java
1
请完成以下Java代码
private void publishRfQClose(final I_C_RfQResponseLine rfqResponseLine) { // Create and collect the RfQ close event final boolean winnerKnown = true; final SyncRfQCloseEvent syncRfQCloseEvent = syncObjectsFactory.createSyncRfQCloseEvent(rfqResponseLine, winnerKnown); if (syncRfQCloseEvent != null) { syncRfQCloseEvents.add(syncRfQCloseEvent); syncProductSupplies.addAll(syncRfQCloseEvent.getPlannedSupplies()); } } private void pushToWebUI() { trxManager.getTrxListenerManagerOrAutoCommit(ITrx.TRXNAME_ThreadInherited) .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> pushToWebUINow()); } private void pushToWebUINow() { // // Push new RfQs final List<SyncRfQ> syncRfQsCopy = copyAndClear(this.syncRfQs); if (!syncRfQsCopy.isEmpty()) { webuiPush.pushRfQs(syncRfQsCopy); } // Push close events { final List<SyncRfQCloseEvent> syncRfQCloseEventsCopy = copyAndClear(this.syncRfQCloseEvents); if (!syncRfQCloseEventsCopy.isEmpty())
{ webuiPush.pushRfQCloseEvents(syncRfQCloseEventsCopy); } // Internally push the planned product supplies, to create the PMM_PurchaseCandidates serverSyncBL.reportProductSupplies(PutProductSuppliesRequest.of(syncProductSupplies)); } } private static <T> List<T> copyAndClear(final List<T> list) { if (list == null || list.isEmpty()) { return ImmutableList.of(); } final List<T> listCopy = ImmutableList.copyOf(list); list.clear(); return listCopy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\PMMWebuiRfQResponsePublisherInstance.java
1
请完成以下Java代码
public class NoUnmappedLeafInstanceValidator implements MigratingActivityInstanceValidator, MigratingTransitionInstanceValidator, MigratingCompensationInstanceValidator { public void validate(MigratingActivityInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingActivityInstanceValidationReportImpl instanceReport) { if (isInvalid(migratingInstance)) { instanceReport.addFailure("There is no migration instruction for this instance's activity"); } } @Override public void validate(MigratingTransitionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingTransitionInstanceValidationReportImpl instanceReport) { if (isInvalid(migratingInstance)) { instanceReport.addFailure("There is no migration instruction for this instance's activity"); } } @Override public void validate(MigratingCompensationEventSubscriptionInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) { if (isInvalid(migratingInstance)) { ancestorInstanceReport.addFailure( "Cannot migrate subscription for compensation handler '" + migratingInstance.getSourceScope().getId() + "'. " + "There is no migration instruction for the compensation boundary event"); } } @Override public void validate(MigratingEventScopeInstance migratingInstance, MigratingProcessInstance migratingProcessInstance, MigratingActivityInstanceValidationReportImpl ancestorInstanceReport) { if (isInvalid(migratingInstance)) { ancestorInstanceReport.addFailure( "Cannot migrate subscription for compensation handler '" + migratingInstance.getEventSubscription().getSourceScope().getId() + "'. " + "There is no migration instruction for the compensation start event"); } } protected boolean isInvalid(MigratingActivityInstance migratingInstance) {
return hasNoInstruction(migratingInstance) && migratingInstance.getChildren().isEmpty(); } protected boolean isInvalid(MigratingEventScopeInstance migratingInstance) { return hasNoInstruction(migratingInstance.getEventSubscription()) && migratingInstance.getChildren().isEmpty(); } protected boolean isInvalid(MigratingTransitionInstance migratingInstance) { return hasNoInstruction(migratingInstance); } protected boolean isInvalid(MigratingCompensationEventSubscriptionInstance migratingInstance) { return hasNoInstruction(migratingInstance); } protected boolean hasNoInstruction(MigratingProcessElementInstance migratingInstance) { return migratingInstance.getMigrationInstruction() == null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\NoUnmappedLeafInstanceValidator.java
1
请完成以下Java代码
public void setShipperRouteCodeName (final @Nullable java.lang.String ShipperRouteCodeName) { set_Value (COLUMNNAME_ShipperRouteCodeName, ShipperRouteCodeName); } @Override public java.lang.String getShipperRouteCodeName() { return get_ValueAsString(COLUMNNAME_ShipperRouteCodeName); } @Override public void setShortDescription (final @Nullable java.lang.String ShortDescription) { set_Value (COLUMNNAME_ShortDescription, ShortDescription); } @Override public java.lang.String getShortDescription() { return get_ValueAsString(COLUMNNAME_ShortDescription); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } @Override public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override
public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } @Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请在Spring Boot框架中完成以下Java代码
static class GeodeGatewaySenderConfiguration { @Bean GatewaySenderFactoryBean customersByNameGatewaySender(Cache cache, @Value("${geode.distributed-system.remote.id:1}") int remoteDistributedSystemId) { GatewaySenderFactoryBean gatewaySender = new GatewaySenderFactoryBean(cache); gatewaySender.setPersistent(PERSISTENT); gatewaySender.setRemoteDistributedSystemId(remoteDistributedSystemId); return gatewaySender; } @Bean RegionConfigurer customersByNameConfigurer(GatewaySender gatewaySender) { return new RegionConfigurer() {
@Override public void configure(String beanName, PeerRegionFactoryBean<?, ?> regionBean) { if (CUSTOMERS_BY_NAME_REGION.equals(beanName)) { regionBean.setGatewaySenders(ArrayUtils.asArray(gatewaySender)); } } }; } } // end::gateway-sender-configuration[] // end::gateway-configuration[] } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\server\BootGeodeMultiSiteCachingServerApplication.java
2
请在Spring Boot框架中完成以下Java代码
public BackChannelLogoutConfigurer logoutHandler(LogoutHandler logoutHandler) { this.logoutHandler = (http) -> logoutHandler; return this; } void configure(B http) { LogoutHandler oidcLogout = this.logoutHandler.apply(http); LogoutHandler sessionLogout = new SecurityContextLogoutHandler(); LogoutConfigurer<B> logout = http.getConfigurer(LogoutConfigurer.class); if (logout != null) { sessionLogout = new CompositeLogoutHandler(logout.getLogoutHandlers()); } OidcBackChannelLogoutFilter filter = new OidcBackChannelLogoutFilter(authenticationConverter(http), authenticationManager(), new EitherLogoutHandler(oidcLogout, sessionLogout)); http.addFilterBefore(filter, CsrfFilter.class); } @SuppressWarnings("unchecked") private <T> T getBeanOrNull(Class<?> clazz) { ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class); if (context == null) { return null; } return (T) context.getBeanProvider(clazz).getIfUnique(); }
private static final class EitherLogoutHandler implements LogoutHandler { private final LogoutHandler left; private final LogoutHandler right; EitherLogoutHandler(LogoutHandler left, LogoutHandler right) { this.left = left; this.right = right; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (request.getParameter("_spring_security_internal_logout") == null) { this.left.logout(request, response, authentication); } else { this.right.logout(request, response, authentication); } } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutConfigurer.java
2
请完成以下Java代码
public String[] getCaseActivityInstanceIds() { return caseActivityInstanceIds; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseDefinitionId() { return caseDefinitionId; } public String[] getCaseActivityIds() { return caseActivityIds; } public String getCaseActivityName() { return caseActivityName; } public String getCaseActivityType() { return caseActivityType; } public Date getCreatedBefore() { return createdBefore; } public Date getCreatedAfter() { return createdAfter; } public Date getEndedBefore() { return endedBefore; } public Date getEndedAfter() { return endedAfter; }
public Boolean getEnded() { return ended; } public Integer getCaseActivityInstanceState() { return caseActivityInstanceState; } public Boolean isRequired() { return required; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseActivityInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class NettyServerProperties { /** * Connection timeout of the Netty channel. */ private @Nullable Duration connectionTimeout; /** * Maximum content length of an H2C upgrade request. */ private DataSize h2cMaxContentLength = DataSize.ofBytes(0); /** * Initial buffer size for HTTP request decoding. */ private DataSize initialBufferSize = DataSize.ofBytes(128); /** * Maximum length that can be decoded for an HTTP request's initial line. */ private DataSize maxInitialLineLength = DataSize.ofKilobytes(4); /** * Maximum number of requests that can be made per connection. By default, a * connection serves unlimited number of requests. */ private @Nullable Integer maxKeepAliveRequests; /** * Whether to validate headers when decoding requests. */ private boolean validateHeaders = true; /** * Idle timeout of the Netty channel. When not specified, an infinite timeout is used. */ private @Nullable Duration idleTimeout; public @Nullable Duration getConnectionTimeout() { return this.connectionTimeout; } public void setConnectionTimeout(@Nullable Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; } public DataSize getH2cMaxContentLength() { return this.h2cMaxContentLength; } public void setH2cMaxContentLength(DataSize h2cMaxContentLength) { this.h2cMaxContentLength = h2cMaxContentLength; } public DataSize getInitialBufferSize() { return this.initialBufferSize; } public void setInitialBufferSize(DataSize initialBufferSize) { this.initialBufferSize = initialBufferSize;
} public DataSize getMaxInitialLineLength() { return this.maxInitialLineLength; } public void setMaxInitialLineLength(DataSize maxInitialLineLength) { this.maxInitialLineLength = maxInitialLineLength; } public @Nullable Integer getMaxKeepAliveRequests() { return this.maxKeepAliveRequests; } public void setMaxKeepAliveRequests(@Nullable Integer maxKeepAliveRequests) { this.maxKeepAliveRequests = maxKeepAliveRequests; } public boolean isValidateHeaders() { return this.validateHeaders; } public void setValidateHeaders(boolean validateHeaders) { this.validateHeaders = validateHeaders; } public @Nullable Duration getIdleTimeout() { return this.idleTimeout; } public void setIdleTimeout(@Nullable Duration idleTimeout) { this.idleTimeout = idleTimeout; } }
repos\spring-boot-4.0.1\module\spring-boot-reactor-netty\src\main\java\org\springframework\boot\reactor\netty\autoconfigure\NettyServerProperties.java
2
请完成以下Java代码
public PlatformTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public String getDeploymentName() { return deploymentName; } public void setDeploymentName(String deploymentName) { this.deploymentName = deploymentName; } public Resource[] getDeploymentResources() { return deploymentResources; } public void setDeploymentResources(Resource[] deploymentResources) { this.deploymentResources = deploymentResources; } public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }
public String getDeploymentMode() { return deploymentMode; } public void setDeploymentMode(String deploymentMode) { this.deploymentMode = deploymentMode; } /** * Gets the {@link AutoDeploymentStrategy} for the provided mode. This method may be overridden to implement custom deployment strategies if required, but implementors should take care not to return * <code>null</code>. * * @param mode * the mode to get the strategy for * @return the deployment strategy to use for the mode. Never <code>null</code> */ protected AutoDeploymentStrategy getAutoDeploymentStrategy(final String mode) { AutoDeploymentStrategy result = defaultAutoDeploymentStrategy; for (final AutoDeploymentStrategy strategy : deploymentStrategies) { if (strategy.handlesMode(mode)) { result = strategy; break; } } return result; } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringProcessEngineConfiguration.java
1
请完成以下Java代码
public void remove() { throw new UnsupportedOperationException("Remove operation not supported."); } private Iterator<ET> getBufferIterator() { // Buffer iterator was not initialized yet, loading first page if (bufferIterator == null) { loadNextPage(); return bufferIterator; } // Buffer iterator has reached the end. We load the next page only if current page was fully load. // Else, makes no sense to load next page because last page was a short one so we are sure that there are no more pages if (!bufferIterator.hasNext() && bufferFullyLoaded) { loadNextPage(); } return bufferIterator; } private void loadNextPage() { final TypedSqlQuery<T> queryToUse; query.setLimit(QueryLimit.ofInt(bufferSize)); if (Check.isEmpty(rowNumberColumn, true)) { query.setLimit(QueryLimit.ofInt(bufferSize), offset); queryToUse = query; } else { query.setLimit(QueryLimit.ofInt(bufferSize)); queryToUse = query.addWhereClause(true, rowNumberColumn + " > " + offset); } final List<ET> buffer = queryToUse.list(clazz); bufferIterator = buffer.iterator(); final int bufferSizeActual = buffer.size(); bufferFullyLoaded = bufferSizeActual >= bufferSize; if (logger.isDebugEnabled()) { logger.debug("Loaded next page: bufferSize=" + bufferSize + ", offset=" + offset + " -> " + bufferSizeActual + " records (fullyLoaded=" + bufferFullyLoaded + ")"); } offset += bufferSizeActual; } /**
* Sets buffer/page size, i.e. the number of rows to be loaded by this iterator at a time. * * @see IQuery#OPTION_GuaranteedIteratorRequired */ public void setBufferSize(final int bufferSize) { Check.assume(bufferSize > 0, "bufferSize > 0"); this.bufferSize = bufferSize; } public int getBufferSize() { return bufferSize; } @Override public String toString() { return "POBufferedIterator [clazz=" + clazz + ", bufferSize=" + bufferSize + ", offset=" + offset + ", query=" + query + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POBufferedIterator.java
1
请完成以下Java代码
private Throwable extractThrowable(final Object[] msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return null; } final Object lastEntry = msgParameters[msgParameters.length - 1]; return lastEntry instanceof Throwable ? (Throwable)lastEntry : null; } private Object[] removeLastElement(final Object[] msgParameters) { if (msgParameters == null || msgParameters.length == 0) {
return msgParameters; } final int newLen = msgParameters.length - 1; final Object[] msgParametersNew = new Object[newLen]; System.arraycopy(msgParameters, 0, msgParametersNew, 0, newLen); return msgParametersNew; } @Value public static class FormattedMsgWithAdIssueId { String formattedMessage; Optional<AdIssueId> adIsueId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\LoggableWithThrowableUtil.java
1
请完成以下Java代码
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) { this.encodeHashAsBase64 = encodeHashAsBase64; } /** * Encodes the rawPass using a MessageDigest. If a salt is specified it will be merged * with the password before encoding. * @param rawPassword The plain text password * @return Hex string of password digest (or base64 encoded string if * encodeHashAsBase64 is enabled. */ @Override public String encodeNonNullPassword(String rawPassword) { String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX; return digest(salt, rawPassword); } private String digest(String salt, CharSequence rawPassword) { if (rawPassword == null) { rawPassword = ""; } String saltedPassword = rawPassword + salt; byte[] saltedPasswordBytes = Utf8.encode(saltedPassword); Md4 md4 = new Md4(); md4.update(saltedPasswordBytes, 0, saltedPasswordBytes.length); byte[] digest = md4.digest(); String encoded = encodedNonNullPassword(digest); return salt + encoded; } private String encodedNonNullPassword(byte[] digest) { if (this.encodeHashAsBase64) { return Utf8.decode(Base64.getEncoder().encode(digest)); } return new String(Hex.encode(digest)); } /** * Takes a previously encoded password and compares it with a rawpassword after mixing * in the salt and encoding that value
* @param rawPassword plain text password * @param encodedPassword previously encoded password * @return true or false */ @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { String salt = extractSalt(encodedPassword); String rawPasswordEncoded = digest(salt, rawPassword); return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded); } private String extractSalt(String prefixEncodedPassword) { int start = prefixEncodedPassword.indexOf(PREFIX); if (start != 0) { return ""; } int end = prefixEncodedPassword.indexOf(SUFFIX, start); if (end < 0) { return ""; } return prefixEncodedPassword.substring(start, end + 1); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Md4PasswordEncoder.java
1
请在Spring Boot框架中完成以下Java代码
public String url() { return obtain((properties) -> this.connectionDetails.getUrl(), OtlpConfig.super::url); } @Override public AggregationTemporality aggregationTemporality() { return obtain(OtlpMetricsProperties::getAggregationTemporality, OtlpConfig.super::aggregationTemporality); } @Override public Map<String, String> resourceAttributes() { Map<String, String> resourceAttributes = new LinkedHashMap<>(); new OpenTelemetryResourceAttributes(this.environment, this.openTelemetryProperties.getResourceAttributes()) .applyTo(resourceAttributes::put); return Collections.unmodifiableMap(resourceAttributes); } @Override public Map<String, String> headers() { return obtain(OtlpMetricsProperties::getHeaders, OtlpConfig.super::headers); } @Override public HistogramFlavor histogramFlavor() { return obtain(OtlpMetricsProperties::getHistogramFlavor, OtlpConfig.super::histogramFlavor); } @Override public Map<String, HistogramFlavor> histogramFlavorPerMeter() { return obtain(perMeter(Meter::getHistogramFlavor), OtlpConfig.super::histogramFlavorPerMeter); } @Override public Map<String, Integer> maxBucketsPerMeter() { return obtain(perMeter(Meter::getMaxBucketCount), OtlpConfig.super::maxBucketsPerMeter); }
@Override public int maxScale() { return obtain(OtlpMetricsProperties::getMaxScale, OtlpConfig.super::maxScale); } @Override public int maxBucketCount() { return obtain(OtlpMetricsProperties::getMaxBucketCount, OtlpConfig.super::maxBucketCount); } @Override public TimeUnit baseTimeUnit() { return obtain(OtlpMetricsProperties::getBaseTimeUnit, OtlpConfig.super::baseTimeUnit); } private <V> Getter<OtlpMetricsProperties, Map<String, V>> perMeter(Getter<Meter, V> getter) { return (properties) -> { if (CollectionUtils.isEmpty(properties.getMeter())) { return null; } Map<String, V> perMeter = new LinkedHashMap<>(); properties.getMeter().forEach((key, meterProperties) -> { V value = getter.get(meterProperties); if (value != null) { perMeter.put(key, value); } }); return (!perMeter.isEmpty()) ? perMeter : null; }; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsPropertiesConfigAdapter.java
2
请完成以下Java代码
private static String extractLanguagePartFromTag(final String tag) { final int idx = tag.indexOf("-"); return idx > 0 ? tag.substring(0, idx) : null; } public static String toHttpLanguageTag(final String adLanguage) { return adLanguage.replace('_', '-').trim().toLowerCase(); } public boolean isBaseLanguage(final ValueNamePair language) { return isBaseLanguage(language.getValue()); } public boolean isBaseLanguage(final String adLanguage) { if (baseADLanguage == null) { return false; } return baseADLanguage.equals(adLanguage); } // // // // // public static class Builder { private final Map<String, ValueNamePair> languagesByADLanguage = new LinkedHashMap<>(); private String baseADLanguage = null; private Builder()
{ } public ADLanguageList build() { return new ADLanguageList(this); } public Builder addLanguage(@NonNull final String adLanguage, @NonNull final String caption, final boolean isBaseLanguage) { final ValueNamePair languageVNP = ValueNamePair.of(adLanguage, caption); languagesByADLanguage.put(adLanguage, languageVNP); if (isBaseLanguage) { baseADLanguage = adLanguage; } return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ADLanguageList.java
1
请完成以下Java代码
private void touch(String sessionKey) { this.redisOps.hasKey(sessionKey); } private String getSessionKey(String sessionId) { return this.namespace + ":sessions:" + sessionId; } /** * Set the namespace for the keys. * @param namespace the namespace */ public void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; this.expirationsKey = this.namespace + ":sessions:expirations"; } /** * Configure the clock used when retrieving expired sessions for clean-up. * @param clock the clock */
public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * Configures how many sessions will be queried at a time to be cleaned up. Defaults * to 100. * @param cleanupCount how many sessions to be queried, must be bigger than 0. */ public void setCleanupCount(int cleanupCount) { Assert.state(cleanupCount > 0, "cleanupCount must be greater than 0"); this.cleanupCount = cleanupCount; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetRedisSessionExpirationStore.java
1
请完成以下Java代码
public class Sale { @Indexed(unique = true) private SaleId saleId; private Double value; public Sale() { } public Sale(SaleId saleId) { super(); this.saleId = saleId; } public SaleId getSaleId() {
return saleId; } public void setSaleId(SaleId saleId) { this.saleId = saleId; } public Double getValue() { return value; } public void setValue(Double value) { this.value = value; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\unique\field\data\Sale.java
1
请在Spring Boot框架中完成以下Java代码
public List<BPartnerBankAccount> getBpartnerBankAccount(final BankAccountQuery query) { final IQueryBuilder<I_C_BP_BankAccount> queryBuilder = queryBL.createQueryBuilder(I_C_BP_BankAccount.class) .addOnlyActiveRecordsFilter() .orderByDescending(I_C_BP_BankAccount.COLUMNNAME_IsDefault); // DESC (Y, then N) if (query.getBPartnerId() != null) { queryBuilder.addEqualsFilter(org.compiere.model.I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, query.getBPartnerId()); } else if (query.getInvoiceId() != null) { queryBuilder.addInSubQueryFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, I_C_Invoice.COLUMNNAME_C_BPartner_ID, queryBL.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_C_Invoice_ID, query.getInvoiceId()) .create()); } final Collection<BPBankAcctUse> bankAcctUses = query.getBpBankAcctUses(); if (bankAcctUses != null && !bankAcctUses.isEmpty()) { queryBuilder.addInArrayFilter(I_C_BP_BankAccount.COLUMNNAME_BPBankAcctUse, bankAcctUses); } if (query.isContainsQRIBAN()) { queryBuilder.addNotNull(I_C_BP_BankAccount.COLUMNNAME_QR_IBAN); } queryBuilder.orderBy(I_C_BP_BankAccount.COLUMN_C_BP_BankAccount_ID); return queryBuilder.create() .stream() .map(this::of) .collect(ImmutableList.toImmutableList()); } @NonNull private BPartnerBankAccount of(@NonNull final I_C_BP_BankAccount record)
{ return BPartnerBankAccount.builder() .id(BPartnerBankAccountId.ofRepoId(record.getC_BPartner_ID(), record.getC_BP_BankAccount_ID())) .currencyId(CurrencyId.ofRepoId(record.getC_Currency_ID())) .active(record.isActive()) .orgMappingId(OrgMappingId.ofRepoIdOrNull(record.getAD_Org_Mapping_ID())) .iban(record.getIBAN()) .qrIban(record.getQR_IBAN()) .bankId(BankId.ofRepoIdOrNull(record.getC_Bank_ID())) .accountName(record.getA_Name()) .accountStreet(record.getA_Street()) .accountZip(record.getA_Zip()) .accountCity(record.getA_City()) .accountCountry(record.getA_Country()) //.changeLog() .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPBankAccountDAO.java
2