instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void putOutputType(final OutputType outputType) { put(PARAM_OUTPUTTYPE, outputType); } /** * Gets desired output type * * @return {@link OutputType}; never returns null */ public OutputType getOutputTypeEffective() { final Object outputTypeObj = get(PARAM_OUTPUTTYPE); if (outputTypeObj instanceof OutputType) { return (OutputType)outputTypeObj; } else if (outputTypeObj instanceof String) { return OutputType.valueOf(outputTypeObj.toString()); } else { return OutputType.JasperPrint; } } public void putReportLanguage(String adLanguage) { put(PARAM_REPORT_LANGUAGE, adLanguage); } /** * Extracts {@link Language} parameter * * @return {@link Language}; never returns null */ public Language getReportLanguageEffective() { final Object languageObj = get(PARAM_REPORT_LANGUAGE); Language currLang = null; if (languageObj instanceof String) { currLang = Language.getLanguage((String)languageObj); }
else if (languageObj instanceof Language) { currLang = (Language)languageObj; } if (currLang == null) { currLang = Env.getLanguage(Env.getCtx()); } return currLang; } public void putLocale(@Nullable final Locale locale) { put(JRParameter.REPORT_LOCALE, locale); } @Nullable public Locale getLocale() { return (Locale)get(JRParameter.REPORT_LOCALE); } public void putRecordId(final int recordId) { put(PARAM_RECORD_ID, recordId); } public void putTableId(final int tableId) { put(PARAM_AD_Table_ID, tableId); } public void putBarcodeURL(final String barcodeURL) { put(PARAM_BARCODE_URL, barcodeURL); } @Nullable public String getBarcodeUrl() { final Object barcodeUrl = get(PARAM_BARCODE_URL); return barcodeUrl != null ? barcodeUrl.toString() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JRParametersCollector.java
2
请在Spring Boot框架中完成以下Java代码
public void configure() { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager cacheManager = cachingProvider.getCacheManager(); final MutableConfiguration<GetSalutationsRequest, Object> config = new MutableConfiguration<>(); config.setTypes(GetSalutationsRequest.class, Object.class); config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1))); final Cache<GetSalutationsRequest, Object> cache = cacheManager.createCache("salutation", config); final JCachePolicy jcachePolicy = new JCachePolicy(); jcachePolicy.setCache(cache); from(direct(GET_SALUTATION_ROUTE_ID)) .id(GET_SALUTATION_ROUTE_ID) .streamCache("true") .policy(jcachePolicy) .log("Route invoked. Salutations will be cached") .process(this::getAndAttachSalutations); } private void getAndAttachSalutations(final Exchange exchange) { final GetSalutationsRequest getSalutationsRequest = exchange.getIn().getBody(GetSalutationsRequest.class); if (getSalutationsRequest == null) {
throw new RuntimeException("No getSalutationsRequest provided!"); } final PInstanceLogger pInstanceLogger = PInstanceLogger.of(processLogger); final ShopwareClient shopwareClient = ShopwareClient .of(getSalutationsRequest.getClientId(), getSalutationsRequest.getClientSecret(), getSalutationsRequest.getBaseUrl(), pInstanceLogger); final ImmutableMap<String, String> salutationId2DisplayName = shopwareClient.getSalutations() .map(JsonSalutation::getSalutationList) .map(salutationList -> salutationList .stream() .filter(salutationItem -> salutationItem!= null && !Objects.equals(salutationItem.getSalutationKey(), SALUTATION_KEY_NOT_SPECIFIED)) .collect(ImmutableMap.toImmutableMap(JsonSalutationItem::getId, JsonSalutationItem::getDisplayName))) .orElseGet(ImmutableMap::of); final SalutationInfoProvider salutationInfoProvider = SalutationInfoProvider.builder() .salutationId2DisplayName(salutationId2DisplayName) .build(); exchange.getIn().setBody(salutationInfoProvider); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\salutation\GetSalutationsRoute.java
2
请完成以下Java代码
public WebEndpointHttpMethod getHttpMethod() { return this.httpMethod; } /** * Returns the media types that the operation consumes. * @return the consumed media types */ public Collection<String> getConsumes() { return Collections.unmodifiableCollection(this.consumes); } /** * Returns the media types that the operation produces. * @return the produced media types */ public Collection<String> getProduces() { return Collections.unmodifiableCollection(this.produces); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } WebOperationRequestPredicate other = (WebOperationRequestPredicate) obj; boolean result = true; result = result && this.consumes.equals(other.consumes); result = result && this.httpMethod == other.httpMethod; result = result && this.canonicalPath.equals(other.canonicalPath); result = result && this.produces.equals(other.produces); return result;
} @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.consumes.hashCode(); result = prime * result + this.httpMethod.hashCode(); result = prime * result + this.canonicalPath.hashCode(); result = prime * result + this.produces.hashCode(); return result; } @Override public String toString() { StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'"); if (!CollectionUtils.isEmpty(this.consumes)) { result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes)); } if (!CollectionUtils.isEmpty(this.produces)) { result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces)); } return result.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebOperationRequestPredicate.java
1
请完成以下Java代码
private void createMissingPartitions(Admin adminClient, Map<String, NewPartitions> topicsToModify) { CreatePartitionsResult partitionsResult = adminClient.createPartitions(topicsToModify); try { partitionsResult.all().get(this.operationTimeout, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOGGER.error(e, "Interrupted while waiting for partition creation results"); } catch (TimeoutException e) { throw new KafkaException("Timed out waiting for create partitions results", e); } catch (ExecutionException e) { if (e.getCause() instanceof InvalidPartitionsException) { // Possible race with another app instance LOGGER.debug(e.getCause(), "Failed to create partitions"); } else { LOGGER.error(e.getCause() != null ? e.getCause() : e, "Failed to create partitions"); if (!(e.getCause() instanceof UnsupportedVersionException)) { throw new KafkaException("Failed to create partitions", e.getCause()); // NOSONAR } } } } /** * Wrapper for a collection of {@link NewTopic} to facilitate declaring multiple
* topics as a single bean. * * @since 2.7 * */ public static class NewTopics { private final Collection<NewTopic> newTopics = new ArrayList<>(); /** * Construct an instance with the {@link NewTopic}s. * @param newTopics the topics. */ public NewTopics(NewTopic... newTopics) { this.newTopics.addAll(Arrays.asList(newTopics)); } Collection<NewTopic> getNewTopics() { return this.newTopics; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaAdmin.java
1
请完成以下Java代码
public DocOutBoundRecipient ofUser(@NonNull final User user) { final Language userLanguage = user.getLanguage(); @Nullable final BPartnerId bpartnerId = user.getBpartnerId(); @Nullable final I_C_BPartner bpartnerRecord = bpartnerId != null ? bpartnerBL.getById(bpartnerId, I_C_BPartner.class) : null; @Nullable final Language bPartnerLanguage = bpartnerRecord != null ? bpartnerBL.getLanguage(bpartnerRecord).orElse(null) : null; final boolean isInvoiceAsEmail = computeInvoiceAsEmail(bpartnerRecord, user.getIsInvoiceEmailEnabled()); return DocOutBoundRecipient.builder() .id(DocOutBoundRecipientId.ofUserId(user.getIdNotNull())) .emailAddress(user.getEmailAddress()) .invoiceAsEmail(isInvoiceAsEmail) .userLanguage(userLanguage) .bPartnerLanguage(bPartnerLanguage) .build();
} private boolean computeInvoiceAsEmail(@Nullable final I_C_BPartner bpartnerRecord, @NonNull final OptionalBoolean defaultValue) { return extractInvoiceEmailEnabled(bpartnerRecord) .ifUnknown(defaultValue) .orElseFalse(); } private static OptionalBoolean extractInvoiceEmailEnabled(@Nullable final I_C_BPartner bpartnerRecord) { return bpartnerRecord != null ? OptionalBoolean.ofNullableString(bpartnerRecord.getIsInvoiceEmailEnabled()) : OptionalBoolean.UNKNOWN; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\DocOutBoundRecipientService.java
1
请完成以下Java代码
public void setInvoiceWeekDayCutoff (java.lang.String InvoiceWeekDayCutoff) { set_Value (COLUMNNAME_InvoiceWeekDayCutoff, InvoiceWeekDayCutoff); } /** Get Letzter Wochentag Lieferungen. @return Last day in the week for shipments to be included */ @Override public java.lang.String getInvoiceWeekDayCutoff () { return (java.lang.String)get_Value(COLUMNNAME_InvoiceWeekDayCutoff); } /** Set Betragsgrenze. @param IsAmount Send invoices only if the amount exceeds the limit IMPORTANT: currently not used; */ @Override public void setIsAmount (boolean IsAmount) { set_Value (COLUMNNAME_IsAmount, Boolean.valueOf(IsAmount)); } /** Get Betragsgrenze. @return Send invoices only if the amount exceeds the limit IMPORTANT: currently not used; */ @Override public boolean isAmount () { Object oo = get_Value(COLUMNNAME_IsAmount); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Standard. @param IsDefault Default value */ @Override public void setIsDefault (boolean IsDefault) {
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Standard. @return Default value */ @Override public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceSchedule.java
1
请完成以下Java代码
public class CardSequenceNumberRange1 { @XmlElement(name = "FrstTx") protected String frstTx; @XmlElement(name = "LastTx") protected String lastTx; /** * Gets the value of the frstTx property. * * @return * possible object is * {@link String } * */ public String getFrstTx() { return frstTx; } /** * Sets the value of the frstTx property. * * @param value * allowed object is * {@link String } * */ public void setFrstTx(String value) { this.frstTx = value; } /**
* Gets the value of the lastTx property. * * @return * possible object is * {@link String } * */ public String getLastTx() { return lastTx; } /** * Sets the value of the lastTx property. * * @param value * allowed object is * {@link String } * */ public void setLastTx(String value) { this.lastTx = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardSequenceNumberRange1.java
1
请在Spring Boot框架中完成以下Java代码
public class EmbeddedLdapProperties { /** * Embedded LDAP port. */ private int port; /** * Embedded LDAP credentials. */ private Credential credential = new Credential(); /** * List of base DNs. */ @Delimiter(Delimiter.NONE) private List<String> baseDn = new ArrayList<>(); /** * Schema (LDIF) script resource reference. */ private String ldif = "classpath:schema.ldif"; /** * Schema validation. */ private final Validation validation = new Validation(); public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public Credential getCredential() { return this.credential; } public void setCredential(Credential credential) { this.credential = credential; } public List<String> getBaseDn() { return this.baseDn; } public void setBaseDn(List<String> baseDn) { this.baseDn = baseDn; } public String getLdif() { return this.ldif; } public void setLdif(String ldif) { this.ldif = ldif; } public Validation getValidation() { return this.validation; } public static class Credential { /** * Embedded LDAP username. */ private @Nullable String username; /** * Embedded LDAP password. */ private @Nullable String password; public @Nullable String getUsername() { return this.username; } public void setUsername(@Nullable String username) { this.username = username; }
public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } boolean isAvailable() { return StringUtils.hasText(this.username) && StringUtils.hasText(this.password); } } public static class Validation { /** * Whether to enable LDAP schema validation. */ private boolean enabled = true; /** * Path to the custom schema. */ private @Nullable Resource schema; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable Resource getSchema() { return this.schema; } public void setSchema(@Nullable Resource schema) { this.schema = schema; } } }
repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java
2
请完成以下Java代码
public void setByteArrayValue(byte[] bytes) { byteArrayField.setByteArrayValue(bytes); } public void setValue(TypedValue typedValue) { typedValueField.setValue(typedValue); } public String getSerializerName() { return typedValueField.getSerializerName(); } public void setSerializerName(String serializerName) { typedValueField.setSerializerName(serializerName); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { byteArrayField.deleteByteArrayValue(); Context .getCommandContext() .getDbEntityManager() .delete(this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInputInstanceEntity.java
1
请完成以下Java代码
public static WorkflowLaunchersFacetId ofLocalDate(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final LocalDate localDate) { return ofString(groupId, localDate.toString()); } // NOTE: Quantity class is not accessible from this project :( public static WorkflowLaunchersFacetId ofQuantity(@NonNull final WorkflowLaunchersFacetGroupId groupId, @NonNull final BigDecimal value, @NonNull final RepoIdAware uomId) { return ofString(groupId, value + QTY_SEPARATOR + uomId.getRepoId()); } @Override @Deprecated public String toString() {return toJsonString();} @JsonValue @NonNull public String toJsonString() {return groupId.getAsString() + SEPARATOR + value;} @NonNull public <T extends RepoIdAware> T getAsId(@NonNull final Class<T> type) {return RepoIdAwares.ofObject(value, type);} @NonNull public LocalDate getAsLocalDate() {return LocalDate.parse(value);} // NOTE: Quantity class is not accessible from this project :( @NonNull public ImmutablePair<BigDecimal, Integer> getAsQuantity() { try
{ final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value); if (parts.size() != 2) { throw new AdempiereException("Cannot get Quantity from " + this); } return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1))); } catch (AdempiereException ex) { throw ex; } catch (final Exception ex) { throw new AdempiereException("Cannot get Quantity from " + this, ex); } } @NonNull public String getAsString() {return value;} @NonNull public <T> T deserializeTo(@NonNull final Class<T> targetClass) { return JSONObjectMapper.forClass(targetClass).readValue(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java
1
请完成以下Java代码
class JdbcUrlBuilder { private static final String PARAMETERS_LABEL = "org.springframework.boot.jdbc.parameters"; private final String driverProtocol; private final int containerPort; /** * Create a new {@link JdbcUrlBuilder} instance. * @param driverProtocol the driver protocol * @param containerPort the source container port */ JdbcUrlBuilder(String driverProtocol, int containerPort) { Assert.notNull(driverProtocol, "'driverProtocol' must not be null"); this.driverProtocol = driverProtocol; this.containerPort = containerPort; } /** * Build a JDBC URL for the given {@link RunningService}. * @param service the running service * @return a new JDBC URL */ String build(RunningService service) { return build(service, null); } /** * Build a JDBC URL for the given {@link RunningService} and database. * @param service the running service * @param database the database to connect to * @return a new JDBC URL */ String build(RunningService service, @Nullable String database) { return urlFor(service, database); } private String urlFor(RunningService service, @Nullable String database) { Assert.notNull(service, "'service' must not be null");
StringBuilder url = new StringBuilder("jdbc:%s://%s:%d".formatted(this.driverProtocol, service.host(), service.ports().get(this.containerPort))); if (StringUtils.hasLength(database)) { url.append("/"); url.append(database); } String parameters = getParameters(service); if (StringUtils.hasLength(parameters)) { appendParameters(url, parameters); } return url.toString(); } /** * Appends to the given {@code url} the given {@code parameters}. * <p> * The default implementation appends a {@code ?} followed by the {@code parameters}. * @param url the url * @param parameters the parameters */ protected void appendParameters(StringBuilder url, String parameters) { url.append("?").append(parameters); } private @Nullable String getParameters(RunningService service) { return service.labels().get(PARAMETERS_LABEL); } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\JdbcUrlBuilder.java
1
请完成以下Java代码
public void flushActiveLogFile() { // TODO Auto-generated method stub } public void rotateLogFile() { if (metasfreshRollingPolicy != null) { final TimeBasedFileNamingAndTriggeringPolicy<?> triggeringPolicy = metasfreshRollingPolicy.getTimeBasedFileNamingAndTriggeringPolicy(); if (triggeringPolicy instanceof MetasfreshTimeBasedFileNamingAndTriggeringPolicy) { final MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?> metasfreshTriggeringPolicy = (MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?>)triggeringPolicy; metasfreshTriggeringPolicy.setForceRollover(); } } if (rollingFileAppender != null) { rollingFileAppender.rollover(); } } public void setDisabled(final boolean disabled) { if (rollingFileAppender instanceof MetasfreshFileAppender) { ((MetasfreshFileAppender<?>)rollingFileAppender).setDisabled(disabled);
} } public boolean isDisabled() { if (rollingFileAppender instanceof MetasfreshFileAppender) { return ((MetasfreshFileAppender<?>)rollingFileAppender).isDisabled(); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshFileLoggerHelper.java
1
请在Spring Boot框架中完成以下Java代码
public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, DEFAULT_REDIRECT_URL); builder.scope("read:user"); builder.authorizationUri("https://github.com/login/oauth/authorize"); builder.tokenUri("https://github.com/login/oauth/access_token"); builder.userInfoUri("https://api.github.com/user"); builder.userNameAttributeName("id"); builder.clientName("GitHub"); return builder; } }, FACEBOOK { @Override public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_POST, DEFAULT_REDIRECT_URL); builder.scope("public_profile", "email"); builder.authorizationUri("https://www.facebook.com/v2.8/dialog/oauth"); builder.tokenUri("https://graph.facebook.com/v2.8/oauth/access_token"); builder.userInfoUri("https://graph.facebook.com/me?fields=id,name,email"); builder.userNameAttributeName("id"); builder.clientName("Facebook"); return builder; } }, X { @Override public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_POST, DEFAULT_REDIRECT_URL); builder.scope("users.read", "tweet.read"); builder.authorizationUri("https://x.com/i/oauth2/authorize"); builder.tokenUri("https://api.x.com/2/oauth2/token"); builder.userInfoUri("https://api.x.com/2/users/me"); builder.userNameAttributeName("username"); builder.clientName("X"); return builder; }
}, OKTA { @Override public Builder getBuilder(String registrationId) { ClientRegistration.Builder builder = getBuilder(registrationId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, DEFAULT_REDIRECT_URL); builder.scope("openid", "profile", "email"); builder.userNameAttributeName(IdTokenClaimNames.SUB); builder.clientName("Okta"); return builder; } }; private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}"; protected final ClientRegistration.Builder getBuilder(String registrationId, ClientAuthenticationMethod method, String redirectUri) { ClientRegistration.Builder builder = ClientRegistration.withRegistrationId(registrationId); builder.clientAuthenticationMethod(method); builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE); builder.redirectUri(redirectUri); return builder; } /** * Create a new * {@link org.springframework.security.oauth2.client.registration.ClientRegistration.Builder * ClientRegistration.Builder} pre-configured with provider defaults. * @param registrationId the registration-id used with the new builder * @return a builder instance */ public abstract ClientRegistration.Builder getBuilder(String registrationId); }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\oauth2\client\CommonOAuth2Provider.java
2
请完成以下Java代码
public OAuth2Token getSubjectToken() { return this.subjectToken; } /** * Returns the {@link OAuth2Token actor token}. * @return the {@link OAuth2Token actor token} */ public OAuth2Token getActorToken() { return this.actorToken; } /** * Populate default parameters for the Token Exchange Grant. * @param grantRequest the authorization grant request * @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access * Token Request body */ static MultiValueMap<String, String> defaultParameters(TokenExchangeGrantRequest grantRequest) { ClientRegistration clientRegistration = grantRequest.getClientRegistration(); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { parameters.set(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " ")); } parameters.set(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE);
OAuth2Token subjectToken = grantRequest.getSubjectToken(); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN, subjectToken.getTokenValue()); parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, tokenType(subjectToken)); OAuth2Token actorToken = grantRequest.getActorToken(); if (actorToken != null) { parameters.set(OAuth2ParameterNames.ACTOR_TOKEN, actorToken.getTokenValue()); parameters.set(OAuth2ParameterNames.ACTOR_TOKEN_TYPE, tokenType(actorToken)); } return parameters; } private static String tokenType(OAuth2Token token) { return (token instanceof Jwt) ? JWT_TOKEN_TYPE_VALUE : ACCESS_TOKEN_TYPE_VALUE; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\TokenExchangeGrantRequest.java
1
请完成以下Java代码
public void setExclusionFromSaleReason (java.lang.String ExclusionFromSaleReason) { set_Value (COLUMNNAME_ExclusionFromSaleReason, ExclusionFromSaleReason); } /** Get Exclusion From Sale Reason. @return Exclusion From Sale Reason */ @Override public java.lang.String getExclusionFromSaleReason () { return (java.lang.String)get_Value(COLUMNNAME_ExclusionFromSaleReason); } /** Set Banned Manufacturer . @param M_BannedManufacturer_ID Banned Manufacturer */ @Override public void setM_BannedManufacturer_ID (int M_BannedManufacturer_ID) { if (M_BannedManufacturer_ID < 1) set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, null); else set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, Integer.valueOf(M_BannedManufacturer_ID)); } /** Get Banned Manufacturer . @return Banned Manufacturer */ @Override public int getM_BannedManufacturer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_BannedManufacturer_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner getManufacturer() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setManufacturer(org.compiere.model.I_C_BPartner Manufacturer) {
set_ValueFromPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class, Manufacturer); } /** Set Hersteller. @param Manufacturer_ID Hersteller des Produktes */ @Override public void setManufacturer_ID (int Manufacturer_ID) { if (Manufacturer_ID < 1) set_Value (COLUMNNAME_Manufacturer_ID, null); else set_Value (COLUMNNAME_Manufacturer_ID, Integer.valueOf(Manufacturer_ID)); } /** Get Hersteller. @return Hersteller des Produktes */ @Override public int getManufacturer_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Manufacturer_ID); 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_M_BannedManufacturer.java
1
请在Spring Boot框架中完成以下Java代码
public AppDeploymentQueryImpl latest() { if (key == null) { throw new FlowableIllegalArgumentException("latest can only be used together with a deployment key"); } this.latest = true; return this; } // sorting //////////////////////////////////////////////////////// @Override public AppDeploymentQuery orderByDeploymentId() { return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_ID); } @Override public AppDeploymentQuery orderByDeploymentTime() { return orderBy(AppDeploymentQueryProperty.DEPLOY_TIME); } @Override public AppDeploymentQuery orderByDeploymentName() { return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_NAME); } @Override public AppDeploymentQuery orderByTenantId() { return orderBy(AppDeploymentQueryProperty.DEPLOYMENT_TENANT_ID); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentCountByQueryCriteria(this); } @Override public List<AppDeployment> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDeploymentEntityManager(commandContext).findDeploymentsByQueryCriteria(this); } // getters //////////////////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; }
public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentQueryImpl.java
2
请完成以下Java代码
public void updateHUTrxAttribute(final MutableHUTransactionAttribute huTrxAttribute, final IAttributeValue fromAttributeValue) { huTrxAttribute.setReferencedObject(asi); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected void addChildAttributeStorage(final IAttributeStorage childAttributeStorage) { throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } /** * Method not supported. * * @throws UnsupportedOperationException */ @Override protected IAttributeStorage removeChildAttributeStorage(final IAttributeStorage childAttributeStorage) {
throw new UnsupportedOperationException("Child attribute storages are not supported for " + this); } @Override public void saveChangesIfNeeded() { throw new UnsupportedOperationException(); } @Override public void setSaveOnChange(boolean saveOnChange) { throw new UnsupportedOperationException(); } @Override public UOMType getQtyUOMTypeOrNull() { // ASI attribute storages does not support Qty Storage return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\ASIAttributeStorage.java
1
请完成以下Java代码
public ReturnsInOutHeaderFiller setBPartnerId(final int bpartnerId) { this.bpartnerId = bpartnerId; return this; } private int getBPartnerId() { return bpartnerId; } public ReturnsInOutHeaderFiller setBPartnerLocationId(final int bpartnerLocationId) { this.bpartnerLocationId = bpartnerLocationId; return this; } private int getBPartnerLocationId() { return bpartnerLocationId; } public ReturnsInOutHeaderFiller setMovementDate(final Timestamp movementDate) { this.movementDate = movementDate; return this; } private Timestamp getMovementDate() { return movementDate; } public ReturnsInOutHeaderFiller setWarehouseId(final int warehouseId) { this.warehouseId = warehouseId; return this; } private int getWarehouseId() { return warehouseId; } public ReturnsInOutHeaderFiller setOrder(@Nullable final I_C_Order order) { this.order = order; return this; } private I_C_Order getOrder() { return order;
} public ReturnsInOutHeaderFiller setExternalId(@Nullable final String externalId) { this.externalId = externalId; return this; } private String getExternalId() { return this.externalId; } private String getExternalResourceURL() { return this.externalResourceURL; } public ReturnsInOutHeaderFiller setExternalResourceURL(@Nullable final String externalResourceURL) { this.externalResourceURL = externalResourceURL; return this; } public ReturnsInOutHeaderFiller setDateReceived(@Nullable final Timestamp dateReceived) { this.dateReceived = dateReceived; return this; } private Timestamp getDateReceived() { return dateReceived; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\ReturnsInOutHeaderFiller.java
1
请完成以下Java代码
public boolean isProductUsed(@NonNull final ProductId productId) { return queryBL .createQueryBuilder(I_C_OrderLine.class) .addEqualsFilter(I_C_OrderLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL .createQueryBuilder(I_C_InvoiceLine.class) .addEqualsFilter(I_C_InvoiceLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL .createQueryBuilder(I_M_InOutLine.class) .addEqualsFilter(I_M_InOutLine.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch() || queryBL // Even if a product was not yet ordered/delivered/invoiced, it might be a component and thus end up in a cost-detail.. .createQueryBuilder(I_M_CostDetail.class) .addEqualsFilter(I_M_CostDetail.COLUMNNAME_M_Product_ID, productId.getRepoId()) .addOnlyActiveRecordsFilter() .create() .anyMatch(); } @Override public Set<ProductId> getProductIdsMatchingQueryString( @NonNull final String queryString, @NonNull final ClientId clientId, @NonNull QueryLimit limit) {
final IQueryBuilder<I_M_Product> queryBuilder = queryBL.createQueryBuilder(I_M_Product.class) .setLimit(limit) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId); queryBuilder.addCompositeQueryFilter() .setJoinOr() .addStringLikeFilter(I_M_Product.COLUMNNAME_Value, queryString, true) .addStringLikeFilter(I_M_Product.COLUMNNAME_Name, queryString, true); return queryBuilder.create().idsAsSet(ProductId::ofRepoIdOrNull); } @Override public void save(I_M_Product record) { InterfaceWrapperHelper.save(record); } @Override public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId) { return queryBL.createQueryBuilder(I_M_Product.class) //.addOnlyActiveRecordsFilter() // check inactive records too .addEqualsFilter(I_M_Product.COLUMNNAME_Value, value) .addEqualsFilter(I_M_Product.COLUMNNAME_AD_Client_ID, clientId) .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductDAO.java
1
请完成以下Java代码
public class PPOrderProductStorage extends AbstractProductStorage { private final IPPOrderBOMBL orderBOMBL = Services.get(IPPOrderBOMBL.class); private final I_PP_Order ppOrder; private boolean staled = false; public PPOrderProductStorage(final I_PP_Order ppOrder) { setConsiderForceQtyAllocationFromRequest(false); // TODO: consider changing it to "true" (default) this.ppOrder = ppOrder; } @Override protected Capacity retrieveTotalCapacity() { final ProductId productId = ProductId.ofRepoId(ppOrder.getM_Product_ID()); // we allow negative qty because we want to allow receiving more then expected final PPOrderQuantities ppOrderQtys = getPPOrderQuantities(); final Quantity qtyCapacity = ppOrderQtys.getQtyRequiredToProduce(); // i.e. target Qty To Receive final boolean allowNegativeCapacity = true; return Capacity.createCapacity( qtyCapacity.toBigDecimal(), // qty productId, // product qtyCapacity.getUOM(), // uom allowNegativeCapacity // allowNegativeCapacity ); } private PPOrderQuantities getPPOrderQuantities() { return orderBOMBL.getQuantities(ppOrder); } @Override protected BigDecimal retrieveQtyInitial() { checkStaled(); final PPOrderQuantities ppOrderQtys = getPPOrderQuantities();
final Quantity qtyToReceive = ppOrderQtys.getQtyRemainingToProduce(); return qtyToReceive.toBigDecimal(); } @Override protected void beforeMarkingStalled() { staled = true; } private void checkStaled() { if (!staled) { return; } InterfaceWrapperHelper.refresh(ppOrder); staled = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderProductStorage.java
1
请完成以下Java代码
static class MongoDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements MongoConnectionDetails { private final ConnectionString connectionString; MongoDockerComposeConnectionDetails(RunningService service) { super(service); this.connectionString = buildConnectionString(service); } private ConnectionString buildConnectionString(RunningService service) { MongoEnvironment environment = new MongoEnvironment(service.env()); StringBuilder builder = new StringBuilder("mongodb://"); if (environment.getUsername() != null) { builder.append(environment.getUsername()); builder.append(":"); builder.append((environment.getPassword() != null) ? environment.getPassword() : ""); builder.append("@");
} builder.append(service.host()); builder.append(":"); builder.append(service.ports().get(MONGODB_PORT)); builder.append("/"); builder.append((environment.getDatabase() != null) ? environment.getDatabase() : "test"); if (environment.getUsername() != null) { builder.append("?authSource=admin"); } return new ConnectionString(builder.toString()); } @Override public ConnectionString getConnectionString() { return this.connectionString; } } }
repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\docker\compose\MongoDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public Segment enableCustomDictionary(boolean enable) { throw new UnsupportedOperationException("AhoCorasickDoubleArrayTrieSegment暂时不支持用户词典。"); } public AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> getTrie() { return trie; } public void setTrie(AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> trie) { this.trie = trie; } public AhoCorasickDoubleArrayTrieSegment loadDictionary(String... pathArray) { trie = new AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute>(); TreeMap<String, CoreDictionary.Attribute> map = null; try {
map = IOUtil.loadDictionary(pathArray); } catch (IOException e) { logger.warning("加载词典失败\n" + TextUtility.exceptionToString(e)); return this; } if (map != null && !map.isEmpty()) { trie.build(map); } return this; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\AhoCorasickDoubleArrayTrieSegment.java
1
请完成以下Java代码
public Integer getId() { return id; } public UserDO setId(Integer id) { this.id = id; return this; } public String getUsername() { return username; } public UserDO setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; } public UserDO setPassword(String password) { this.password = password; return this; } public Date getCreateTime() { return createTime; }
public UserDO setCreateTime(Date createTime) { this.createTime = createTime; return this; } @Override public String toString() { return "UserDO{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", createTime=" + createTime + '}'; } }
repos\SpringBoot-Labs-master\lab-14-spring-jdbc-template\lab-14-jdbctemplate\src\main\java\cn\iocoder\springboot\lab14\jdbctemplate\dataobject\UserDO.java
1
请完成以下Java代码
public Task execute(CommandContext commandContext) { if (task == null) { throw new ActivitiIllegalArgumentException("task is null"); } if (task.getRevision() == 0) { commandContext.getTaskEntityManager().insert(task, null); if (commandContext.getEventDispatcher().isEnabled()) { commandContext .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task)); if (task.getAssignee() != null) { commandContext .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task)); }
} } else { TaskInfo originalTaskEntity = null; if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) { originalTaskEntity = commandContext.getHistoricTaskInstanceEntityManager().findById(task.getId()); } if (originalTaskEntity == null) { originalTaskEntity = commandContext.getTaskEntityManager().findById(task.getId()); } TaskUpdater taskUpdater = new TaskUpdater(commandContext); taskUpdater.updateTask(originalTaskEntity, task); return commandContext.getTaskEntityManager().update(task); } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SaveTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
private void createBPartnerExportDirectories(@NonNull final ExportBPartnerRouteContext routeContext) { final JsonExportDirectorySettings jsonExportDirectorySettings = routeContext.getJsonExportDirectorySettings(); final String bpartnerCode = routeContext.getJsonResponseComposite().getBpartner().getCode(); if (jsonExportDirectorySettings == null) { processLogger.logMessage("No export directories settings found for C_BPartner.Value: " + bpartnerCode, routeContext.getPinstanceId()); return; } jsonExportDirectorySettings.getDirectoriesPath(bpartnerCode) .forEach(CreateExportDirectoriesProcessor::createDirectory); routeContext.setBPartnerBasePath(bpartnerCode); }
private static void createDirectory(@NonNull final Path directoryPath) { final File directory = directoryPath.toFile(); if (directory.exists()) { return; } if (!directory.mkdirs()) { throw new RuntimeException("Could not create directory with path: " + directoryPath); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\CreateExportDirectoriesProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public class DeliveryType { @XmlElement(name = "DeliveryRecipient") protected DeliveryRecipientType deliveryRecipient; @XmlElement(name = "DeliveryDetails") protected DeliveryDetailsType deliveryDetails; /** * Details about the recipient of the delivery of goods or services. * * @return * possible object is * {@link DeliveryRecipientType } * */ public DeliveryRecipientType getDeliveryRecipient() { return deliveryRecipient; } /** * Sets the value of the deliveryRecipient property. * * @param value * allowed object is * {@link DeliveryRecipientType } * */ public void setDeliveryRecipient(DeliveryRecipientType value) { this.deliveryRecipient = value; } /** * Details about the delivery of good or services specified in this document. * * @return * possible object is
* {@link DeliveryDetailsType } * */ public DeliveryDetailsType getDeliveryDetails() { return deliveryDetails; } /** * Sets the value of the deliveryDetails property. * * @param value * allowed object is * {@link DeliveryDetailsType } * */ public void setDeliveryDetails(DeliveryDetailsType value) { this.deliveryDetails = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryType.java
2
请完成以下Java代码
private void writeStatusAndHeaders(HttpServletResponse response) { response.setStatus(this.statusCode.value()); writeHeaders(response); writeCookies(response); } private void writeHeaders(HttpServletResponse servletResponse) { this.headers.forEach((headerName, headerValues) -> { for (String headerValue : headerValues) { servletResponse.addHeader(headerName, headerValue); } }); // HttpServletResponse exposes some headers as properties: we should include those // if not already present if (servletResponse.getContentType() == null && this.headers.getContentType() != null) { servletResponse.setContentType(this.headers.getContentType().toString());
} if (servletResponse.getCharacterEncoding() == null && this.headers.getContentType() != null && this.headers.getContentType().getCharset() != null) { servletResponse.setCharacterEncoding(this.headers.getContentType().getCharset().name()); } } private void writeCookies(HttpServletResponse servletResponse) { this.cookies.values().stream().flatMap(Collection::stream).forEach(servletResponse::addCookie); } protected abstract @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response, Context context) throws Exception; }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\AbstractGatewayServerResponse.java
1
请完成以下Java代码
public List<PvmTransition> getIncomingTransitions() { return (List) incomingTransitions; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; } @Override
public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } @Override public boolean isAsync() { return isAsync; } public void setAsync(boolean isAsync) { this.isAsync = isAsync; } @Override public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
1
请完成以下Java代码
public FinishedGoodsReceiveLineId getFinishedGoodsReceiveLineId() {return FinishedGoodsReceiveLineId.ofString(lineId);} } @Nullable ReceiveFrom receiveFrom; @Value @Builder @Jacksonized public static class PickTo { @NonNull String wfProcessId; @NonNull String activityId; @NonNull String lineId; } @Nullable PickTo pickTo; @Builder @Jacksonized private JsonManufacturingOrderEvent(
@NonNull final String wfProcessId, @NonNull final String wfActivityId, // @Nullable final IssueTo issueTo, @Nullable final ReceiveFrom receiveFrom, @Nullable final PickTo pickTo) { if (CoalesceUtil.countNotNulls(issueTo, receiveFrom) != 1) { throw new AdempiereException("One and only one action like issueTo, receiveFrom etc shall be specified in an event."); } this.wfProcessId = wfProcessId; this.wfActivityId = wfActivityId; this.issueTo = issueTo; this.receiveFrom = receiveFrom; this.pickTo = pickTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\rest_api\json\JsonManufacturingOrderEvent.java
1
请完成以下Java代码
public CountResultDto getHistoricBatchesCount(UriInfo uriInfo) { HistoricBatchQueryDto queryDto = new HistoricBatchQueryDto(objectMapper, uriInfo.getQueryParameters()); HistoricBatchQuery query = queryDto.toQuery(processEngine); long count = query.count(); return new CountResultDto(count); } @Override public List<CleanableHistoricBatchReportResultDto> getCleanableHistoricBatchesReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) { CleanableHistoricBatchReportDto queryDto = new CleanableHistoricBatchReportDto(objectMapper, uriInfo.getQueryParameters()); CleanableHistoricBatchReport query = queryDto.toQuery(processEngine); List<CleanableHistoricBatchReportResult> reportResult = QueryUtil.list(query, firstResult, maxResults); return CleanableHistoricBatchReportResultDto.convert(reportResult); } @Override public CountResultDto getCleanableHistoricBatchesReportCount(UriInfo uriInfo) { CleanableHistoricBatchReportDto queryDto = new CleanableHistoricBatchReportDto(objectMapper, uriInfo.getQueryParameters()); queryDto.setObjectMapper(objectMapper); CleanableHistoricBatchReport query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } @Override public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricBatchesDto dto) { HistoryService historyService = processEngine.getHistoryService(); HistoricBatchQuery historicBatchQuery = null; if (dto.getHistoricBatchQuery() != null) { historicBatchQuery = dto.getHistoricBatchQuery().toQuery(processEngine);
} SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = historyService.setRemovalTimeToHistoricBatches(); if (dto.isCalculatedRemovalTime()) { builder.calculatedRemovalTime(); } Date removalTime = dto.getAbsoluteRemovalTime(); if (dto.getAbsoluteRemovalTime() != null) { builder.absoluteRemovalTime(removalTime); } if (dto.isClearedRemovalTime()) { builder.clearedRemovalTime(); } builder.byIds(dto.getHistoricBatchIds()); builder.byQuery(historicBatchQuery); Batch batch = builder.executeAsync(); return BatchDto.fromBatch(batch); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricBatchRestServiceImpl.java
1
请完成以下Java代码
public byte[] decrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException { return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws Exception { final GSSContext context = getTicketValidation().getGssContext(); return context.unwrap(data, offset, length, new MessageProp(true)); } }); } /** * Unwraps an encrypted message using the gss context * @param data the data * @return the decrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] decrypt(final byte[] data) throws PrivilegedActionException { return decrypt(data, 0, data.length); } /** * Wraps an message using the gss context * @param data the data * @param offset data offset * @param length data length * @return the encrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] encrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException { return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() { public byte[] run() throws Exception {
final GSSContext context = getTicketValidation().getGssContext(); return context.wrap(data, offset, length, new MessageProp(true)); } }); } /** * Wraps an message using the gss context * @param data the data * @return the encrypted message * @throws PrivilegedActionException if jaas throws and error */ public byte[] encrypt(final byte[] data) throws PrivilegedActionException { return encrypt(data, 0, data.length); } @Override public JaasSubjectHolder getJaasSubjectHolder() { return this.jaasSubjectHolder; } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceRequestToken.java
1
请完成以下Java代码
public void setUnitOfMeasr(UnitOfMeasure1Code value) { this.unitOfMeasr = value; } /** * Gets the value of the pdctQty property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getPdctQty() { return pdctQty; } /** * Sets the value of the pdctQty property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setPdctQty(BigDecimal value) { this.pdctQty = value; } /** * Gets the value of the unitPric property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getUnitPric() { return unitPric; } /** * Sets the value of the unitPric property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setUnitPric(BigDecimal value) { this.unitPric = value; } /** * Gets the value of the pdctAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getPdctAmt() { return pdctAmt; } /** * Sets the value of the pdctAmt property. * * @param value * allowed object is * {@link BigDecimal } *
*/ public void setPdctAmt(BigDecimal value) { this.pdctAmt = value; } /** * Gets the value of the taxTp property. * * @return * possible object is * {@link String } * */ public String getTaxTp() { return taxTp; } /** * Sets the value of the taxTp property. * * @param value * allowed object is * {@link String } * */ public void setTaxTp(String value) { this.taxTp = value; } /** * Gets the value of the addtlPdctInf property. * * @return * possible object is * {@link String } * */ public String getAddtlPdctInf() { return addtlPdctInf; } /** * Sets the value of the addtlPdctInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlPdctInf(String value) { this.addtlPdctInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Product2.java
1
请完成以下Java代码
public DecisionDefinitionResource getDecisionDefinitionByKey(String decisionDefinitionKey) { DecisionDefinition decisionDefinition = getProcessEngine() .getRepositoryService() .createDecisionDefinitionQuery() .decisionDefinitionKey(decisionDefinitionKey) .withoutTenantId() .latestVersion() .singleResult(); if (decisionDefinition == null) { String errorMessage = String.format("No matching decision definition with key: %s and no tenant-id", decisionDefinitionKey); throw new RestException(Status.NOT_FOUND, errorMessage); } else { return getDecisionDefinitionById(decisionDefinition.getId()); } } @Override public DecisionDefinitionResource getDecisionDefinitionByKeyAndTenantId(String decisionDefinitionKey, String tenantId) { DecisionDefinition decisionDefinition = getProcessEngine() .getRepositoryService() .createDecisionDefinitionQuery() .decisionDefinitionKey(decisionDefinitionKey) .tenantIdIn(tenantId) .latestVersion() .singleResult(); if (decisionDefinition == null) { String errorMessage = String.format("No matching decision definition with key: %s and tenant-id: %s", decisionDefinitionKey, tenantId); throw new RestException(Status.NOT_FOUND, errorMessage); } else { return getDecisionDefinitionById(decisionDefinition.getId()); } } @Override public DecisionDefinitionResource getDecisionDefinitionById(String decisionDefinitionId) { return new DecisionDefinitionResourceImpl(getProcessEngine(), decisionDefinitionId, relativeRootResourcePath, getObjectMapper()); } @Override
public List<DecisionDefinitionDto> getDecisionDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); List<DecisionDefinitionDto> definitions = new ArrayList<DecisionDefinitionDto>(); ProcessEngine engine = getProcessEngine(); DecisionDefinitionQuery query = queryDto.toQuery(engine); List<DecisionDefinition> matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); for (DecisionDefinition definition : matchingDefinitions) { DecisionDefinitionDto def = DecisionDefinitionDto.fromDecisionDefinition(definition); definitions.add(def); } return definitions; } @Override public CountResultDto getDecisionDefinitionsCount(UriInfo uriInfo) { DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); ProcessEngine engine = getProcessEngine(); DecisionDefinitionQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DecisionDefinitionRestServiceImpl.java
1
请完成以下Java代码
public void setAuthorityPrefix(String authorityPrefix) { Assert.notNull(authorityPrefix, "authorityPrefix cannot be null"); this.authorityPrefix = authorityPrefix; } /** * Extract {@link GrantedAuthority}s from the given {@link Jwt}. * @param jwt The {@link Jwt} token * @return The {@link GrantedAuthority authorities} read from the token scopes */ @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; } private Collection<String> getAuthorities(Jwt jwt) { Object authorities; try { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for authorities with expression. expression=%s", this.authoritiesClaimExpression.getExpressionString())); } authorities = this.authoritiesClaimExpression.getValue(jwt.getClaims(), Collection.class); if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Found authorities with expression. authorities=%s", authorities)); }
} catch (ExpressionException ee) { if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Failed to evaluate expression. error=%s", ee.getMessage())); } authorities = Collections.emptyList(); } if (authorities != null) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\ExpressionJwtGrantedAuthoritiesConverter.java
1
请完成以下Java代码
public String getSerialNumber() { return serialNumber; } public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InvoiceEntity that = (InvoiceEntity) o; return Objects.equals(serialNumber, that.serialNumber); } @Override public int hashCode() { return Objects.hash(serialNumber); } }
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\continuetransactionafterexception\model\InvoiceEntity.java
1
请完成以下Java代码
public JsonGetTransactionResponse getTransactionById(@NonNull final SumUpTransactionExternalId id) { final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL) .pathSegment("me", "transactions") .queryParam("id", id.getAsString()) .toUriString(); final String json = httpCall(uri, HttpMethod.GET, null, String.class); try { return jsonObjectMapper.readValue(json, JsonGetTransactionResponse.class) .withJson(json); } catch (JsonProcessingException ex)
{ throw AdempiereException.wrapIfNeeded(ex); } } public void refundTransaction(@NonNull final SumUpTransactionExternalId id) { final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL) .pathSegment("me", "refund", id.getAsString()) .toUriString(); httpCall(uri, HttpMethod.POST, null, null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\SumUpClient.java
1
请完成以下Java代码
class SQLRowLoaderUtils { public static KPIDataValue retrieveValue(final ResultSet rs, final KPIField field) throws SQLException { final String fieldName = field.getFieldName(); final KPIFieldValueType valueType = field.getValueType(); if (valueType == KPIFieldValueType.String || valueType == KPIFieldValueType.URL) { final String valueStr = rs.getString(fieldName); return KPIDataValue.ofValueAndField(valueStr, field); } else if (valueType == KPIFieldValueType.Number) {
final BigDecimal valueBD = rs.getBigDecimal(fieldName); return KPIDataValue.ofValueAndField(valueBD, field); } else if (valueType == KPIFieldValueType.Date || valueType == KPIFieldValueType.DateTime) { final Timestamp valueTS = rs.getTimestamp(fieldName); return KPIDataValue.ofValueAndField(valueTS != null ? valueTS.toInstant() : null, field); } else { throw new AdempiereException("Unknown value type `" + valueType + "` for " + field); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\SQLRowLoaderUtils.java
1
请完成以下Java代码
public XMLGregorianCalendar getCreDtTm() { return creDtTm; } /** * Sets the value of the creDtTm property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreDtTm(XMLGregorianCalendar value) { this.creDtTm = value; } /** * Gets the value of the msgRcpt property. * * @return * possible object is * {@link PartyIdentification32 } * */ public PartyIdentification32 getMsgRcpt() { return msgRcpt; } /** * Sets the value of the msgRcpt property. * * @param value * allowed object is * {@link PartyIdentification32 } * */ public void setMsgRcpt(PartyIdentification32 value) { this.msgRcpt = value; } /** * Gets the value of the msgPgntn property. * * @return * possible object is * {@link Pagination } * */ public Pagination getMsgPgntn() {
return msgPgntn; } /** * Sets the value of the msgPgntn property. * * @param value * allowed object is * {@link Pagination } * */ public void setMsgPgntn(Pagination value) { this.msgPgntn = value; } /** * Gets the value of the addtlInf property. * * @return * possible object is * {@link String } * */ public String getAddtlInf() { return addtlInf; } /** * Sets the value of the addtlInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlInf(String value) { this.addtlInf = value; } }
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\GroupHeader42.java
1
请完成以下Java代码
public LookupValuesList getM_HU_PI_Item_IDs() { return getPackingInfoParams().getM_HU_PI_Item_IDs(p_M_HU_PI_Item_Product); } @Override @RunOutOfTrx protected String doIt() { final IPPOrderReceiptHUProducer producer = newReceiptCandidatesProducer() .bestBeforeDate(computeBestBeforeDate()); if (isReceiveIndividualCUs) { producer.withPPOrderLocatorId() .receiveIndividualPlanningCUs(getIndividualCUsCount()); } else { producer.packUsingLUTUConfiguration(getPackingInfoParams().createAndSaveNewLUTUConfig()) .createDraftReceiptCandidatesAndPlanningHUs(); } return MSG_OK; } @Override protected void postProcess(final boolean success) { // Invalidate the view because for sure we have changes final PPOrderLinesView ppOrderLinesView = getView(); ppOrderLinesView.invalidateAll(); getViewsRepo().notifyRecordsChangedAsync(I_PP_Order.Table_Name, ppOrderLinesView.getPpOrderId().getRepoId()); } @Nullable LocalDate computeBestBeforeDate() { if (attributesBL.isAutomaticallySetBestBeforeDate()) { final PPOrderLineRow row = getSingleSelectedRow(); final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(row.getProductId()); if (guaranteeDaysMin <= 0) { return null; } final I_PP_Order ppOrderPO = huPPOrderBL.getById(row.getOrderId());
final LocalDate datePromised = TimeUtil.asLocalDate(ppOrderPO.getDatePromised()); return datePromised.plusDays(guaranteeDaysMin); } else { return null; } } private IPPOrderReceiptHUProducer newReceiptCandidatesProducer() { final PPOrderLineRow row = getSingleSelectedRow(); final PPOrderLineType type = row.getType(); if (type == PPOrderLineType.MainProduct) { final PPOrderId ppOrderId = row.getOrderId(); return huPPOrderBL.receivingMainProduct(ppOrderId); } else if (type == PPOrderLineType.BOMLine_ByCoProduct) { final PPOrderBOMLineId ppOrderBOMLineId = row.getOrderBOMLineId(); return huPPOrderBL.receivingByOrCoProduct(ppOrderBOMLineId); } else { throw new AdempiereException("Receiving is not allowed"); } } @NonNull private Quantity getIndividualCUsCount() { if (p_NumberOfCUs <= 0) { throw new FillMandatoryException(PARAM_NumberOfCUs); } return Quantity.of(p_NumberOfCUs, getSingleSelectedRow().getUomNotNull()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Receipt.java
1
请在Spring Boot框架中完成以下Java代码
private static @Nullable Access determineDefaultAccess(PropertyResolver properties) { Access defaultAccess = properties.getProperty(DEFAULT_ACCESS_KEY, Access.class); Boolean endpointsEnabledByDefault = properties.getProperty(ENABLED_BY_DEFAULT_KEY, Boolean.class); MutuallyExclusiveConfigurationPropertiesException.throwIfMultipleNonNullValuesIn((entries) -> { entries.put(DEFAULT_ACCESS_KEY, defaultAccess); entries.put(ENABLED_BY_DEFAULT_KEY, endpointsEnabledByDefault); }); if (defaultAccess != null) { return defaultAccess; } if (endpointsEnabledByDefault != null) { return endpointsEnabledByDefault ? org.springframework.boot.actuate.endpoint.Access.UNRESTRICTED : org.springframework.boot.actuate.endpoint.Access.NONE; } return null; } @Override public Access accessFor(EndpointId endpointId, Access defaultAccess) { return this.accessCache.computeIfAbsent(endpointId, (key) -> resolveAccess(endpointId.toLowerCaseString(), defaultAccess).cap(this.maxPermittedAccess)); }
private Access resolveAccess(String endpointId, Access defaultAccess) { String accessKey = "management.endpoint.%s.access".formatted(endpointId); String enabledKey = "management.endpoint.%s.enabled".formatted(endpointId); Access access = this.properties.getProperty(accessKey, Access.class); Boolean enabled = this.properties.getProperty(enabledKey, Boolean.class); MutuallyExclusiveConfigurationPropertiesException.throwIfMultipleNonNullValuesIn((entries) -> { entries.put(accessKey, access); entries.put(enabledKey, enabled); }); if (access != null) { return access; } if (enabled != null) { return (enabled) ? Access.UNRESTRICTED : Access.NONE; } return (this.endpointsDefaultAccess != null) ? this.endpointsDefaultAccess : defaultAccess; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\PropertiesEndpointAccessResolver.java
2
请在Spring Boot框架中完成以下Java代码
public class RoleId { private final String id; @JsonCreator public RoleId(@JsonProperty("id") String id) { this.id = id; } public String getId() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
RoleId roleId = (RoleId) o; return Objects.equals(id, roleId.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return id; } }
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\services\dto\RoleId.java
2
请完成以下Java代码
public class LocalStorage extends BaseEntity implements Serializable { @Id @Column(name = "storage_id") @ApiModelProperty(value = "ID", hidden = true) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ApiModelProperty(value = "真实文件名") private String realName; @ApiModelProperty(value = "文件名") private String name; @ApiModelProperty(value = "后缀") private String suffix; @ApiModelProperty(value = "路径") private String path;
@ApiModelProperty(value = "类型") private String type; @ApiModelProperty(value = "大小") private String size; public LocalStorage(String realName,String name, String suffix, String path, String type, String size) { this.realName = realName; this.name = name; this.suffix = suffix; this.path = path; this.type = type; this.size = size; } public void copy(LocalStorage source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\domain\LocalStorage.java
1
请完成以下Java代码
private void accept(@NonNull final WorkpackageProcessedEvent workpackageLifeCycleEvent) { if (isNoopConsumer) { logger.info("accept - isNoopConsumer; -> return directly"); return; // accept "should" not be called because we are not subscribed anywhere } final boolean eventShallBeCounted = (DONE.equals(workpackageLifeCycleEvent.getStatus()) || ERROR.equals(workpackageLifeCycleEvent.getStatus())) && correlationId.equals(workpackageLifeCycleEvent.getCorrelationId()); if (!eventShallBeCounted) { logger.info("accept - workpackageLifeCycleEvent shall not be counted; -> return directly; event={}", workpackageLifeCycleEvent); return; } synchronized (this) { if (countDownLatch != null) { logger.info("accept - invoke countDownLatch.countDown()"); countDownLatch.countDown(); } else { logger.info("accept - countDownLatch == null; increase eventsReceivedBeforeWaitStarted"); eventsReceivedBeforeWaitStarted++; } } } public void waitForWorkpackagesDone(final int enqueuedWorkpackages) { if (isNoopConsumer) { logger.info("waitForWorkpackagesDone - isNoopConsumer; -> return directly");
return; } final boolean alreadyDoneBeforeWeStarted; synchronized (this) { final int remainingWorkpackages = enqueuedWorkpackages - eventsReceivedBeforeWaitStarted; alreadyDoneBeforeWeStarted = remainingWorkpackages <= 0; logger.info("waitForWorkpackagesDone - param enqueuedWorkpackages={}; field eventsReceivedBeforeWaitStarted={}; -> create latch={}", enqueuedWorkpackages, eventsReceivedBeforeWaitStarted, !alreadyDoneBeforeWeStarted); if (!alreadyDoneBeforeWeStarted) { countDownLatch = new CountDownLatch(remainingWorkpackages); } } if (alreadyDoneBeforeWeStarted) { eventBus.unsubscribe(eventListener); return; // the workpackages were already processed before we even started waiting; => nothing more to do) } try { logger.info("waitForWorkpackagesDone - invoke countDownLatch.await()"); countDownLatch.await(); } catch (final InterruptedException e) { throw AdempiereException.wrapIfNeeded(e).appendParametersToMessage().setParameter("this", this); } finally { eventBus.unsubscribe(eventListener); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\event\WorkpackagesProcessedWaiter.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } final I_C_Async_Batch record = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(AsyncBatchId.ofRepoId(context.getSingleSelectedRecordId())); if (!hasAttachments(record)) { return ProcessPreconditionsResolution.rejectWithInternalReason("No attachments found"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final I_C_Async_Batch record = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(AsyncBatchId.ofRepoId(getRecord_ID())); final List<AttachmentEntry> attachments = getAttachmentEntries(record); if (!attachments.isEmpty()) { final AttachmentEntry attachment = attachments.get(0); // take first one final Resource data = attachmentEntryService.retrieveDataResource(attachment.getId());
getResult().setReportData(data, attachment.getFilename(), attachment.getMimeType()); } return MSG_OK; } private boolean hasAttachments(@NonNull final I_C_Async_Batch record) { final List<AttachmentEntry> attachments = getAttachmentEntries(record); return !attachments.isEmpty(); } private List<AttachmentEntry> getAttachmentEntries(@NonNull final I_C_Async_Batch record) { final AttachmentEntryService.AttachmentEntryQuery attachmentQuery = AttachmentEntryService.AttachmentEntryQuery.builder() .referencedRecord(TableRecordReference.of(record)) .mimeType(MimeType.TYPE_PDF) .build(); return attachmentEntryService.getByQuery(attachmentQuery); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\process\C_Async_Batch_DownloadFileFromAttachment.java
1
请完成以下Java代码
public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<M, M> get(int index) { return pipeList.get(index); } @Override public Pipe<M, M> set(int index, Pipe<M, M> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<M, M> element) { pipeList.add(index, element); } /** * 以最高优先级加入管道 * * @param pipe */ public void addFirst(Pipe<M, M> pipe) { pipeList.addFirst(pipe); } /** * 以最低优先级加入管道 * * @param pipe */ public void addLast(Pipe<M, M> pipe) { pipeList.addLast(pipe); } @Override public Pipe<M, M> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) {
return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<M, M>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<M, M>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<M, M>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java
1
请在Spring Boot框架中完成以下Java代码
public class MyUserDetailsService implements UserDetailsService { private final Log logger = LogFactory.getLog(this.getClass()); private final Map<String, User> availableUsers = new HashMap<String, User>(); public MyUserDetailsService() { populateDemoUsers(); } @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { throw new UsernameNotFoundException(username); } return user; } /**
* Create demo users (note: obviously in a real system these would be persisted * in database or retrieved from another system). */ private void populateDemoUsers() { logger.info("Populate demo users"); availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER))); availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } private User createUser(final String username, final String password, final List<SecurityRole> roles) { logger.info("Create user " + username); final List<GrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); return new User(username, password, true, true, true, true, authorities); } }
repos\tutorials-master\spring-security-modules\spring-security-web-persistent-login\src\main\java\com\baeldung\service\MyUserDetailsService.java
2
请在Spring Boot框架中完成以下Java代码
public class MvcStreamingController { private static final Path UPLOAD_DIR = Path.of("mvc-uploads"); @PostMapping("/upload") public ResponseEntity<String> uploadFileStreaming(@RequestPart("filePart") MultipartFile filePart) throws IOException { Path targetPath = UPLOAD_DIR.resolve(filePart.getOriginalFilename()); Files.createDirectories(targetPath.getParent()); try (InputStream inputStream = filePart.getInputStream(); OutputStream outputStream = Files.newOutputStream(targetPath)) { inputStream.transferTo(outputStream); } return ResponseEntity.ok("Upload successful: " + filePart.getOriginalFilename()); } @GetMapping("/download") public StreamingResponseBody downloadFiles(HttpServletResponse response) throws IOException { String boundary = "filesBoundary"; response.setContentType("multipart/mixed; boundary=" + boundary); List<Path> files = List.of(UPLOAD_DIR.resolve("file1.txt"), UPLOAD_DIR.resolve("file2.txt")); return outputStream -> { try (BufferedOutputStream bos = new BufferedOutputStream(outputStream); OutputStreamWriter writer = new OutputStreamWriter(bos)) {
for (Path file : files) { writer.write("--" + boundary + "\r\n"); writer.write("Content-Type: application/octet-stream\r\n"); writer.write("Content-Disposition: attachment; filename=\"" + file.getFileName() + "\"\r\n\r\n"); writer.flush(); Files.copy(file, bos); bos.write("\r\n".getBytes()); bos.flush(); } writer.write("--" + boundary + "--\r\n"); writer.flush(); } }; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\streaming\MvcStreamingController.java
2
请完成以下Java代码
public BigDecimal computeActualQty() { return getTransactionDetails() .stream() .map(TransactionDetail::getQuantity) .reduce(BigDecimal.ZERO, BigDecimal::add); } public DemandDetail getDemandDetail() { return CoalesceUtil.coalesce(DemandDetail.castOrNull(businessCaseDetail), additionalDemandDetail); } public BigDecimal getBusinessCaseDetailQty() { if (businessCaseDetail == null) { return BigDecimal.ZERO; } return businessCaseDetail.getQty(); } @Nullable public OrderAndLineId getSalesOrderLineId() { final DemandDetail demandDetail = getDemandDetail(); if (demandDetail == null) { return null; } return OrderAndLineId.ofRepoIdsOrNull(demandDetail.getOrderId(), demandDetail.getOrderLineId()); } @NonNull public BusinessCaseDetail getBusinessCaseDetailNotNull() { return Check.assumeNotNull(getBusinessCaseDetail(), "businessCaseDetail is not null: {}", this); } public <T extends BusinessCaseDetail> Optional<T> getBusinessCaseDetail(@NonNull final Class<T> type) { return type.isInstance(businessCaseDetail) ? Optional.of(type.cast(businessCaseDetail)) : Optional.empty(); } public <T extends BusinessCaseDetail> T getBusinessCaseDetailNotNull(@NonNull final Class<T> type) { if (type.isInstance(businessCaseDetail)) { return type.cast(businessCaseDetail); } else { throw new AdempiereException("businessCaseDetail is not matching " + type.getSimpleName() + ": " + this); } } public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper) { final T businessCaseDetail = getBusinessCaseDetailNotNull(type);
final T businessCaseDetailChanged = mapper.apply(businessCaseDetail); if (Objects.equals(businessCaseDetail, businessCaseDetailChanged)) { return this; } return withBusinessCaseDetail(businessCaseDetailChanged); } @Nullable public String getTraceId() { final DemandDetail demandDetail = getDemandDetail(); return demandDetail != null ? demandDetail.getTraceId() : null; } /** * This is enabled by the current usage of {@link #parentId} */ public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate) { if (potentialStockCandidate.type != CandidateType.STOCK) { return false; } switch (type) { case DEMAND: return potentialStockCandidate.getParentId().equals(id); case SUPPLY: return potentialStockCandidate.getId().equals(parentId); default: return false; } } /** * The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock. */ public BigDecimal getStockImpactPlannedQuantity() { switch (getType()) { case DEMAND: case UNEXPECTED_DECREASE: case INVENTORY_DOWN: return getQuantity().negate(); default: return getQuantity(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java
1
请完成以下Java代码
public static void clearCachedRequestBody(ServerWebExchange exchange) { Object attribute = exchange.getAttributes().remove(CACHED_REQUEST_BODY_ATTR); if (attribute != null && attribute instanceof PooledDataBuffer) { PooledDataBuffer dataBuffer = (PooledDataBuffer) attribute; if (dataBuffer.isAllocated()) { if (log.isTraceEnabled()) { log.trace("releasing cached body in exchange attribute"); } // ensure proper release while (!dataBuffer.release()) { // release() counts down until zero, will never be infinite loop } } } } private static ServerHttpRequest decorate(ServerWebExchange exchange, DataBuffer dataBuffer, boolean cacheDecoratedRequest) { if (dataBuffer.readableByteCount() > 0) { if (log.isTraceEnabled()) { log.trace("retaining body in exchange attribute"); } Object cachedDataBuffer = exchange.getAttribute(CACHED_REQUEST_BODY_ATTR); // don't cache if body is already cached if (!(cachedDataBuffer instanceof DataBuffer)) { exchange.getAttributes().put(CACHED_REQUEST_BODY_ATTR, dataBuffer); } } ServerHttpRequest decorator = new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public Flux<DataBuffer> getBody() { return Mono.fromSupplier(() -> { if (exchange.getAttribute(CACHED_REQUEST_BODY_ATTR) == null) { // probably == downstream closed or no body return null; } if (dataBuffer instanceof NettyDataBuffer) { NettyDataBuffer pdb = (NettyDataBuffer) dataBuffer; return pdb.factory().wrap(pdb.getNativeBuffer().retainedSlice()); } else if (dataBuffer instanceof DefaultDataBuffer) { DefaultDataBuffer ddf = (DefaultDataBuffer) dataBuffer; return ddf.factory().wrap(Unpooled.wrappedBuffer(ddf.getNativeBuffer()).nioBuffer()); } else {
throw new IllegalArgumentException( "Unable to handle DataBuffer of type " + dataBuffer.getClass()); } }).flux(); } }; if (cacheDecoratedRequest) { exchange.getAttributes().put(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR, decorator); } return decorator; } /** * One place to handle forwarding using DispatcherHandler. Allows for common code to * be reused. * @param handler The DispatcherHandler. * @param exchange The ServerWebExchange. * @return value from handler. */ public static Mono<Void> handle(DispatcherHandler handler, ServerWebExchange exchange) { // remove attributes that may disrupt the forwarded request exchange.getAttributes().remove(GATEWAY_PREDICATE_PATH_CONTAINER_ATTR); // CORS check is applied to the original request, but should not be applied to // internally forwarded requests. // See https://github.com/spring-cloud/spring-cloud-gateway/issues/3350. exchange = exchange.mutate().request(request -> request.headers(headers -> headers.setOrigin(null))).build(); return handler.handle(exchange); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ServerWebExchangeUtils.java
1
请完成以下Java代码
public CurrencyPrecision getCurrencyPrecision() {return currency.getPrecision();} public boolean isCashJournalOpen() {return cashJournalId != null;} @NonNull public POSCashJournalId getCashJournalIdNotNull() { if (cashJournalId == null) { throw new AdempiereException("No open journals found"); } return cashJournalId; } public POSTerminal openingCashJournal(@NonNull final POSCashJournalId cashJournalId) { if (this.cashJournalId != null) { throw new AdempiereException("Cash journal already open");
} return toBuilder() .cashJournalId(cashJournalId) .build(); } public POSTerminal closingCashJournal(@NonNull final Money cashEndingBalance) { cashEndingBalance.assertCurrencyId(currency.getId()); return toBuilder() .cashJournalId(null) .cashLastBalance(cashEndingBalance) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminal.java
1
请在Spring Boot框架中完成以下Java代码
public Page<Author> fetchAuthorsPageSortWhere() { return authorRepository.fetchPageSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSort() { return authorRepository.fetchSliceSort(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhere() { return authorRepository.fetchSliceSortWhere(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public List<Author> fetchAllAuthorsNative() { return authorRepository.fetchAllNative(); } public Author fetchAuthorByNameAndAgeNative() { return authorRepository.fetchByNameAndAgeNative("Joana Nimar", 34); } /* causes exception public List<Author> fetchAuthorsViaSortNative() { return authorRepository.fetchViaSortNative(Sort.by(Direction.DESC, "name")); } */
/* causes exception public List<Author> fetchAuthorsViaSortWhereNative() { return authorRepository.fetchViaSortWhereNative(30, Sort.by(Direction.DESC, "name")); } */ public Page<Author> fetchAuthorsPageSortNative() { return authorRepository.fetchPageSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Page<Author> fetchAuthorsPageSortWhereNative() { return authorRepository.fetchPageSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortNative() { return authorRepository.fetchSliceSortNative(PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } public Slice<Author> fetchAuthorsSliceSortWhereNative() { return authorRepository.fetchSliceSortWhereNative(30, PageRequest.of(1, 3, Sort.by(Sort.Direction.DESC, "name"))); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedQueriesInOrmXml\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setMatchErrorMsg (final @Nullable java.lang.String MatchErrorMsg) { set_Value (COLUMNNAME_MatchErrorMsg, MatchErrorMsg); } @Override public java.lang.String getMatchErrorMsg() { return get_ValueAsString(COLUMNNAME_MatchErrorMsg); } @Override public void setOrg_ID (final int Org_ID) { if (Org_ID < 1) set_Value (COLUMNNAME_Org_ID, null); else set_Value (COLUMNNAME_Org_ID, Org_ID); } @Override public int getOrg_ID() { return get_ValueAsInt(COLUMNNAME_Org_ID); } @Override public void setPaymentDate (final @Nullable java.sql.Timestamp PaymentDate) { set_Value (COLUMNNAME_PaymentDate, PaymentDate); } @Override public java.sql.Timestamp getPaymentDate() { return get_ValueAsTimestamp(COLUMNNAME_PaymentDate); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed()
{ return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setSektionNo (final @Nullable java.lang.String SektionNo) { set_Value (COLUMNNAME_SektionNo, SektionNo); } @Override public java.lang.String getSektionNo() { return get_ValueAsString(COLUMNNAME_SektionNo); } /** * Type AD_Reference_ID=541287 * Reference name: ESR_Type */ public static final int TYPE_AD_Reference_ID=541287; /** QRR = QRR */ public static final String TYPE_QRR = "QRR"; /** ESR = ISR Reference */ public static final String TYPE_ESR = "ISR Reference"; /** SCOR = SCOR Reference */ public static final String TYPE_SCOR = "SCOR"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportLine.java
1
请完成以下Java代码
public class X_M_Product_Exclude_FlatrateConditions extends org.compiere.model.PO implements I_M_Product_Exclude_FlatrateConditions, org.compiere.model.I_Persistent { private static final long serialVersionUID = 816936915L; /** Standard Constructor */ public X_M_Product_Exclude_FlatrateConditions (final Properties ctx, final int M_Product_Exclude_FlatrateConditions_ID, @Nullable final String trxName) { super (ctx, M_Product_Exclude_FlatrateConditions_ID, trxName); } /** Load Constructor */ public X_M_Product_Exclude_FlatrateConditions (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public de.metas.order.model.I_C_CompensationGroup_Schema getC_CompensationGroup_Schema() { return get_ValueAsPO(COLUMNNAME_C_CompensationGroup_Schema_ID, de.metas.order.model.I_C_CompensationGroup_Schema.class); } @Override public void setC_CompensationGroup_Schema(final de.metas.order.model.I_C_CompensationGroup_Schema C_CompensationGroup_Schema) { set_ValueFromPO(COLUMNNAME_C_CompensationGroup_Schema_ID, de.metas.order.model.I_C_CompensationGroup_Schema.class, C_CompensationGroup_Schema); } @Override public void setC_CompensationGroup_Schema_ID (final int C_CompensationGroup_Schema_ID) { if (C_CompensationGroup_Schema_ID < 1)
set_Value (COLUMNNAME_C_CompensationGroup_Schema_ID, null); else set_Value (COLUMNNAME_C_CompensationGroup_Schema_ID, C_CompensationGroup_Schema_ID); } @Override public int getC_CompensationGroup_Schema_ID() { return get_ValueAsInt(COLUMNNAME_C_CompensationGroup_Schema_ID); } @Override public void setM_Product_Exclude_FlatrateConditions_ID (final int M_Product_Exclude_FlatrateConditions_ID) { if (M_Product_Exclude_FlatrateConditions_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID, M_Product_Exclude_FlatrateConditions_ID); } @Override public int getM_Product_Exclude_FlatrateConditions_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Exclude_FlatrateConditions_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Exclude_FlatrateConditions.java
1
请完成以下Java代码
public class CustomIdentityLinkParser extends BaseChildElementParser { @Override public String getElementName() { return ELEMENT_CUSTOM_RESOURCE; } @Override public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { String identityLinkType = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_NAME); // the attribute value may be unqualified if (identityLinkType == null) { identityLinkType = xtr.getAttributeValue(null, ATTRIBUTE_NAME); } if (identityLinkType == null) return; String resourceElement = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(resourceElement) && ELEMENT_RESOURCE_ASSIGNMENT.equals(resourceElement)) { String expression = XMLStreamReaderUtil.moveDown(xtr); if (StringUtils.isNotEmpty(expression) && ELEMENT_FORMAL_EXPRESSION.equals(expression)) { List<String> assignmentList = CommaSplitter.splitCommas(xtr.getElementText()); for (String assignmentValue : assignmentList) { if (assignmentValue == null) { continue; } assignmentValue = assignmentValue.trim(); if (assignmentValue.length() == 0) { continue; } String userPrefix = "user("; String groupPrefix = "group("; if (assignmentValue.startsWith(userPrefix)) {
assignmentValue = assignmentValue .substring(userPrefix.length(), assignmentValue.length() - 1) .trim(); ((UserTask) parentElement).addCustomUserIdentityLink(assignmentValue, identityLinkType); } else if (assignmentValue.startsWith(groupPrefix)) { assignmentValue = assignmentValue .substring(groupPrefix.length(), assignmentValue.length() - 1) .trim(); ((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType); } else { ((UserTask) parentElement).addCustomGroupIdentityLink(assignmentValue, identityLinkType); } } } } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\UserTaskXMLConverter.java
1
请完成以下Java代码
public static EMailAttachment of(@NonNull final String filename, @NonNull final File file) { return of(filename, Util.readBytes(file)); } public static EMailAttachment of(@NonNull final String filename, final byte[] content) { return new EMailAttachment(filename, content, null); } public static EMailAttachment ofNullable(@NonNull final String filename, @Nullable final byte[] content) { return content != null && content.length != 0 ? of(filename, content) : null; } public static EMailAttachment of(@NonNull final URI uri) { return new EMailAttachment(null, null, uri); } public static EMailAttachment of(@NonNull final Resource resource) { try { return of(resource.getURI()); } catch (IOException e) { //noinspection DataFlowIssue throw AdempiereException.wrapIfNeeded(e); } } @JsonProperty("filename") String filename; @JsonProperty("content") byte[] content; @JsonProperty("uri") URI uri; @JsonCreator private EMailAttachment( @JsonProperty("filename") final String filename, @JsonProperty("content") final byte[] content, @JsonProperty("uri") final URI uri) { this.filename = filename; this.content = content; this.uri = uri;
} @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("filename", filename) .add("uri", uri) .add("content.size", content != null ? content.length : null) .toString(); } @JsonIgnore public DataSource createDataSource() { if (uri != null) { try { return new URLDataSource(uri.toURL()); } catch (final MalformedURLException ex) { throw new AdempiereException("@Invalid@ @URL@: " + uri, ex); } } else { return ByteArrayBackedDataSource.of(filename, content); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAttachment.java
1
请在Spring Boot框架中完成以下Java代码
public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override
public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserDetailsImpl user = (UserDetailsImpl) o; return Objects.equals(id, user.id); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\userservice\UserDetailsImpl.java
2
请完成以下Java代码
public abstract class AbstractCoapTransportResource extends CoapResource { protected final CoapTransportContext transportContext; protected final TransportService transportService; public AbstractCoapTransportResource(CoapTransportContext context, String name) { super(name); this.transportContext = context; this.transportService = context.getTransportService(); } @Override public void handleGET(CoapExchange exchange) { processHandleGet(exchange); } @Override public void handlePOST(CoapExchange exchange) {
processHandlePost(exchange); } protected abstract void processHandleGet(CoapExchange exchange); protected abstract void processHandlePost(CoapExchange exchange); protected void reportSubscriptionInfo(TransportProtos.SessionInfoProto sessionInfo, boolean hasAttributeSubscription, boolean hasRpcSubscription) { transportContext.getTransportService().process(sessionInfo, TransportProtos.SubscriptionInfoProto.newBuilder() .setAttributeSubscription(hasAttributeSubscription) .setRpcSubscription(hasRpcSubscription) .setLastActivityTime(System.currentTimeMillis()) .build(), TransportServiceCallback.EMPTY); } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\AbstractCoapTransportResource.java
1
请完成以下Java代码
public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) {
this.roles = roles; } public User() { } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + ", roles=" + roles + '}'; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\model\User.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { ppOrderCandidateService.closeCandidates(getPinstanceId()); return MSG_OK; } @Override @RunOutOfTrx protected void prepare() { if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } private int createSelection() {
final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .createSelection(adPInstanceId); } @NonNull private IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder() { final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_CloseSelection.java
1
请完成以下Java代码
public void onOpen(Session session,@PathParam("sid") String sid) { this.session = session; //如果存在就先删除一个,防止重复推送消息 webSocketSet.removeIf(webSocket -> webSocket.sid.equals(sid)); webSocketSet.add(this); this.sid=sid; } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("收到来"+sid+"的信息:"+message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { log.error(e.getMessage(),e); } } } @OnError public void onError(Session session, Throwable error) { log.error("发生错误", error); } /** * 实现服务器主动推送 */ private void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 * */ public static void sendInfo(SocketMsg socketMsg,@PathParam("sid") String sid) throws IOException { String message = JSON.toJSONString(socketMsg); log.info("推送消息到"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) { try { //这里可以设定只推送给这个sid的,为null则全部推送 if(sid==null) { item.sendMessage(message); }else if(item.sid.equals(sid)){ item.sendMessage(message); } } catch (IOException ignored) { } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WebSocketServer that = (WebSocketServer) o; return Objects.equals(session, that.session) && Objects.equals(sid, that.sid); } @Override public int hashCode() { return Objects.hash(session, sid); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\websocket\WebSocketServer.java
1
请完成以下Java代码
Builder withRawHtml(String key, String value) { if (!value.isEmpty() && value.charAt(value.length() - 1) == '\n') { value = value.substring(0, value.length() - 1); } this.values.put(key, value); return this; } /** * Render the template. All placeholders MUST have a corresponding value. If a * placeholder does not have a corresponding value, throws * {@link IllegalStateException}. * @return the rendered template */ String render() { String template = this.template; for (String key : this.values.keySet()) { String pattern = Pattern.quote("{{" + key + "}}");
template = template.replaceAll(pattern, this.values.get(key)); } String unusedPlaceholders = Pattern.compile("\\{\\{([a-zA-Z0-9]+)}}") .matcher(template) .results() .map((result) -> result.group(1)) .collect(Collectors.joining(", ")); if (StringUtils.hasLength(unusedPlaceholders)) { throw new IllegalStateException("Unused placeholders in template: [%s]".formatted(unusedPlaceholders)); } return template; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ui\HtmlTemplates.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isFullyAllocated() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().isZero(); } /** * Computes projected over under amt taking into account discount. * * @implNote for purchase invoices used as inbound payment, the discount needs to be subtracted from the open amount. */ @Override public Money calculateProjectedOverUnderAmt(final Money amountToAllocate) { final Money discountAmt = purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getDiscountAmt(); final Money openAmtWithDiscount = purchaseInvoicePayableDoc.getOpenAmtInitial().subtract(discountAmt); final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(purchaseInvoicePayableDoc.getTotalAllocatedAmount()); final Money adjustedAmountToAllocate = amountToAllocate.negate(); return remainingOpenAmtWithDiscount.subtract(adjustedAmountToAllocate); } @Override public boolean canPay(@NonNull final PayableDocument payable) { // A purchase invoice can compensate only on a sales invoice if (payable.getType() != PayableDocumentType.Invoice) { return false; } if (!payable.getSoTrx().isSales()) { return false; } // if currency differs, do not allow payment return CurrencyId.equals(payable.getCurrencyId(), purchaseInvoicePayableDoc.getCurrencyId()); }
@Override public CurrencyId getCurrencyId() { return purchaseInvoicePayableDoc.getCurrencyId(); } @Override public LocalDate getDate() { return purchaseInvoicePayableDoc.getDate(); } @Override public PaymentCurrencyContext getPaymentCurrencyContext() { return PaymentCurrencyContext.builder() .paymentCurrencyId(purchaseInvoicePayableDoc.getCurrencyId()) .currencyConversionTypeId(purchaseInvoicePayableDoc.getCurrencyConversionTypeId()) .build(); } @Override public Money getPaymentDiscountAmt() { return purchaseInvoicePayableDoc.getAmountsToAllocate().getDiscountAmt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PurchaseInvoiceAsInboundPaymentDocumentWrapper.java
2
请完成以下Java代码
final class CurrencyConversionTypesMap { private final ImmutableList<CurrencyConversionTypeRouting> routings; private final ImmutableMap<CurrencyConversionTypeId, CurrencyConversionType> typesById; private final ImmutableMap<ConversionTypeMethod, CurrencyConversionType> typesByMethod; @Builder private CurrencyConversionTypesMap( final Collection<CurrencyConversionTypeRouting> routings, final Collection<CurrencyConversionType> types) { this.routings = ImmutableList.copyOf(routings); typesById = Maps.uniqueIndex(types, CurrencyConversionType::getId); typesByMethod = Maps.uniqueIndex(types, CurrencyConversionType::getMethod); } public CurrencyConversionType getById(@NonNull final CurrencyConversionTypeId id) { final CurrencyConversionType conversionType = typesById.get(id); if (conversionType == null) { throw new AdempiereException("@NotFound@ @C_ConversionType_ID@: " + id); } return conversionType; } public CurrencyConversionType getByMethod(@NonNull final ConversionTypeMethod method) { final CurrencyConversionType conversionType = typesByMethod.get(method); if (conversionType == null)
{ throw new AdempiereException("@NotFound@ @C_ConversionType_ID@: " + method); } return conversionType; } @NonNull public CurrencyConversionType getDefaultConversionType( @NonNull final ClientId adClientId, @NonNull final OrgId adOrgId, @NonNull final Instant date) { final CurrencyConversionTypeRouting bestMatchingRouting = routings.stream() .filter(routing -> routing.isMatching(adClientId, adOrgId, date)) .min(CurrencyConversionTypeRouting.moreSpecificFirstComparator()) .orElseThrow(() -> new AdempiereException("@NotFound@ @C_ConversionType_ID@") .setParameter("adClientId", adClientId) .setParameter("adOrgId", adOrgId) .setParameter("date", date) .appendParametersToMessage()); return getById(bestMatchingRouting.getConversionTypeId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\impl\CurrencyConversionTypesMap.java
1
请完成以下Java代码
public class TodoItem { private String description; private LocalDateTime createDate; public TodoItem(String description, LocalDateTime createDate) { this.description = description; this.createDate = createDate; } public TodoItem() { // default no arg constructor } public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; } public LocalDateTime getCreateDate() { return createDate; } public void setCreateDate(LocalDateTime createDate) { this.createDate = createDate; } @Override public String toString() { return "TodoItem [description=" + description + ", createDate=" + createDate + "]"; } }
repos\tutorials-master\spring-web-modules\spring-mvc-forms-thymeleaf\src\main\java\com\baeldung\sessionattrs\TodoItem.java
1
请完成以下Java代码
private void copyStage (MTreeNode node, String path) { org.compiere.cm.CacheHandler thisHandler = new org.compiere.cm.CacheHandler(org.compiere.cm.CacheHandler.convertJNPURLToCacheURL(getCtx().getProperty("java.naming.provider.url")), log, getCtx(), get_TrxName()); Integer ID = new Integer(node.getNode_ID()); MCStage stage = m_map.get(ID); // int size = node.getChildCount(); for (int i = 0; i < size; i++) { MTreeNode child = (MTreeNode)node.getChildAt(i); ID = new Integer(child.getNode_ID()); stage = m_map.get(ID); if (stage == null) { log.warn("Not Found ID=" + ID); continue; } if (!stage.isActive()) continue; // if (stage != null && stage.isModified()) { MContainer cc = MContainer.copy (m_project, stage, path); if (cc != null) {
addLog (0, null, null, "@Copied@: " + cc.getName()); m_idList.add(ID); } // Remove Container from cache thisHandler.cleanContainer(cc.get_ID()); // Reset Modified flag... stage.setIsModified(false); stage.save(stage.get_TrxName()); } if (child.isSummary()) copyStage (child, path + stage.getRelativeURL() + "/"); } } // copyStage } // WebProjectDeploy
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\WebProjectDeploy.java
1
请完成以下Java代码
private static <T, R> Function<T, Optional<R>> withFallback( @NonNull final Function<T, Optional<R>> primary, @NonNull final Function<T, Optional<R>> fallback) { return t -> { final Optional<R> value = primary.apply(t); return value.isPresent() ? value : fallback.apply(t); }; } private static JsonDeliveryResponse buildJsonDeliveryResponse(@NonNull final JsonShipmentResponse response, @NonNull final JsonDeliveryRequest deliveryRequest) { final Map<String, JsonShipmentResponseLabel> labelsByPkgNo = response.getLabels() != null ? response.getLabels().stream() .filter(label -> label.getPkgNo() != null) .collect(Collectors.toMap( JsonShipmentResponseLabel::getPkgNo, Function.identity(), (first, second) -> first)) // In case of duplicate pkgNo, take the first. : Collections.emptyMap(); final List<JsonDeliveryOrderParcel> requestParcels = deliveryRequest.getDeliveryOrderParcels(); final List<JsonLine> responseLines = response.getLines() != null ? response.getLines() : Collections.emptyList(); Check.assume(requestParcels.size() == responseLines.size(), "Request and response line counts do not match. Request: %s, Response: %s", requestParcels.size(), responseLines.size()); final List<JsonDeliveryResponseItem> items = Streams.zip( requestParcels.stream(), responseLines.stream(), (requestParcel, responseLine) -> { final JsonPackage pkg = responseLine.getPkgs().get(0); final JsonShipmentResponseLabel label = labelsByPkgNo.get(pkg.getPkgNo()); final byte[] labelPdf = (label != null && label.getContent() != null) ? label.getContent().getBytes() : null; return JsonDeliveryResponseItem.builder()
.lineId(requestParcel.getId()) .awb(pkg.getPkgNo()) .trackingUrl(pkg.getReferences().stream() .filter(ref -> ref.getKind() == LINE_REFERENCE_KIND_TRACKING_URL) .map(JsonReference::getValue) .findFirst() .orElse(null)) .labelPdfBase64(labelPdf) .build(); }) .collect(Collectors.toList()); return JsonDeliveryResponse.builder() .requestId(deliveryRequest.getId()) .items(items) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftShipmentService.java
1
请在Spring Boot框架中完成以下Java代码
public class JpaUsersConfig { @Resource(name = "hibernateVendorProperties") private Map<String, Object> hibernateVendorProperties; /** * 创建 users 数据源 */ @Bean(name = "usersDataSource") @ConfigurationProperties(prefix = "spring.datasource.users") public DataSource dataSource() { return DataSourceBuilder.create().build(); } /** * 创建 LocalContainerEntityManagerFactoryBean */ @Bean(name = DBConstants.ENTITY_MANAGER_FACTORY_USERS) public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) { return builder .dataSource(this.dataSource()) // 数据源
.properties(hibernateVendorProperties) // 获取并注入 Hibernate Vendor 相关配置 .packages("cn.iocoder.springboot.lab17.dynamicdatasource.dataobject") // 数据库实体 entity 所在包 .persistenceUnit("usersPersistenceUnit") // 设置持久单元的名字,需要唯一 .build(); } /** * 创建 PlatformTransactionManager */ @Bean(name = DBConstants.TX_MANAGER_USERS) public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactory(builder).getObject()); } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-springdatajpa\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\config\JpaUsersConfig.java
2
请在Spring Boot框架中完成以下Java代码
public String deleteTodo(@RequestParam long id) { todoService.deleteTodo(id); // service.deleteTodo(id); return "redirect:/list-todos"; } @RequestMapping(value = "/update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam long id, ModelMap model) { Todo todo = todoService.getTodoById(id).get(); model.put("todo", todo); return "todo"; } @RequestMapping(value = "/update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; }
// todo.setUserName(getLoggedInUserName(model)); todoService.updateTodo(todo); return "redirect:/list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.POST) public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } // todo.setUserName(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list-todos"; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDBNoSec\src\main\java\spring\hibernate\controller\TodoController.java
2
请完成以下Java代码
public CoreActivity findActivity(String activityId) { CoreActivity localActivity = getChildActivity(activityId); if (localActivity!=null) { return localActivity; } for (CoreActivity activity: getActivities()) { CoreActivity nestedActivity = activity.findActivity(activityId); if (nestedActivity!=null) { return nestedActivity; } } return null; } public CoreActivity createActivity() { return createActivity(null); } /** searches for the activity locally */ public abstract CoreActivity getChildActivity(String activityId);
public abstract CoreActivity createActivity(String activityId); public abstract List<? extends CoreActivity> getActivities(); public abstract CoreActivityBehavior<? extends BaseDelegateExecution> getActivityBehavior(); public IoMapping getIoMapping() { return ioMapping; } public void setIoMapping(IoMapping ioMapping) { this.ioMapping = ioMapping; } public String toString() { return "Activity("+id+")"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CoreActivity.java
1
请完成以下Java代码
protected final IEventBus delegate() { return delegate; } @Override public String toString() { return delegate().toString(); } @Override @NonNull public Topic getTopic() { return delegate().getTopic(); } @Override public void subscribe(final IEventListener listener) { delegate().subscribe(listener); } @Override public void subscribe(final Consumer<Event> eventConsumer) { delegate().subscribe(eventConsumer); } @Override public <T> IEventListener subscribeOn(final Class<T> type, final Consumer<T> eventConsumer) { return delegate().subscribeOn(type, eventConsumer); } @Override public void unsubscribe(final IEventListener listener) { delegate().unsubscribe(listener); } @Override public void processEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().processEvent(event); } } @Override public void enqueueEvent(final Event event) {
try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().enqueueEvent(event); } } @Override public void enqueueObject(final Object obj) { delegate().enqueueObject(obj); } @Override public void enqueueObjectsCollection(@NonNull final Collection<?> objs) { delegate().enqueueObjectsCollection(objs); } @Override public boolean isDestroyed() { return delegate().isDestroyed(); } @Override public boolean isAsync() { return delegate().isAsync(); } @Override public EventBusStats getStats() { return delegate().getStats(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\ForwardingEventBus.java
1
请完成以下Java代码
public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped) { set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped); } @Override public BigDecimal getQtyToBeShipped() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQueryNo (final int QueryNo) { set_Value (COLUMNNAME_QueryNo, QueryNo); }
@Override public int getQueryNo() { return get_ValueAsInt(COLUMNNAME_QueryNo); } @Override public void setStorageAttributesKey (final @Nullable String StorageAttributesKey) { set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public String getStorageAttributesKey() { return get_ValueAsString(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Available_For_Sales_QueryResult.java
1
请完成以下Java代码
public class CWSTagSet extends TagSet { public final int B; public final int M; public final int E; public final int S; public CWSTagSet(int b, int m, int e, int s) { super(TaskType.CWS); B = b; M = m; E = e; S = s; String[] id2tag = new String[4]; id2tag[b] = "B"; id2tag[m] = "M"; id2tag[e] = "E"; id2tag[s] = "S"; for (String tag : id2tag)
{ add(tag); } lock(); } public CWSTagSet() { super(TaskType.CWS); B = add("B"); M = add("M"); E = add("E"); S = add("S"); lock(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\CWSTagSet.java
1
请完成以下Java代码
public class ShipmentScheduleAvailableStock { public static ShipmentScheduleAvailableStock of(@NonNull final Collection<ShipmentScheduleAvailableStockDetail> list) { return !list.isEmpty() ? new ShipmentScheduleAvailableStock(list) : EMPTY; } public static ShipmentScheduleAvailableStock of() { return EMPTY; } private static final ShipmentScheduleAvailableStock EMPTY = new ShipmentScheduleAvailableStock(); private final ImmutableList<ShipmentScheduleAvailableStockDetail> list; private ShipmentScheduleAvailableStock(@NonNull final Collection<ShipmentScheduleAvailableStockDetail> list) { this.list = ImmutableList.copyOf(list); } private ShipmentScheduleAvailableStock() { this.list = ImmutableList.of(); } public BigDecimal getTotalQtyAvailable() { return list.stream() .map(ShipmentScheduleAvailableStockDetail::getQtyAvailable) .reduce(BigDecimal.ZERO, BigDecimal::add); } public boolean isEmpty() { return list.isEmpty(); }
public int size() { return list.size(); } public BigDecimal getQtyAvailable(final int storageIndex) { return getStorageDetail(storageIndex).getQtyAvailable(); } public void subtractQtyOnHand(final int storageIndex, @NonNull final BigDecimal qtyOnHandToRemove) { getStorageDetail(storageIndex).subtractQtyOnHand(qtyOnHandToRemove); } public ShipmentScheduleAvailableStockDetail getStorageDetail(final int storageIndex) { return list.get(storageIndex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleAvailableStock.java
1
请完成以下Java代码
public void setPaymentId(@NonNull final PaymentId paymentId) { this.paymentId = paymentId; } /** * @return true, if acknowledged status changed, false otherwise */ public boolean recomputeIsDocumentAcknowledged() { final boolean isDocumentAcknowledged_refreshedValue = lines.stream().allMatch(RemittanceAdviceLine::isReadyForCompletion); final boolean hasAcknowledgedStatusChanged = isDocumentAcknowledged != isDocumentAcknowledged_refreshedValue; this.isDocumentAcknowledged = isDocumentAcknowledged_refreshedValue; return hasAcknowledgedStatusChanged; } /** * @return true, if read only currencies flag changed, false otherwise */ public boolean recomputeCurrenciesReadOnlyFlag() {
final boolean currenciesReadOnlyFlag_refreshedValue = lines.stream().anyMatch(RemittanceAdviceLine::isInvoiceResolved); final boolean currenciesReadOnlyFlagChanged = currenciesReadOnlyFlag != currenciesReadOnlyFlag_refreshedValue; this.currenciesReadOnlyFlag = currenciesReadOnlyFlag_refreshedValue; return currenciesReadOnlyFlagChanged; } public void setProcessedFlag(final boolean processed) { this.processed = processed; getLines().forEach(line -> line.setProcessed(processed)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\RemittanceAdvice.java
1
请在Spring Boot框架中完成以下Java代码
public InsuranceContractMaxPermanentPrescriptionPeriod timePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; return this; } /** * Zeitintervall (Unbekannt &#x3D; 0, Minute &#x3D; 1, Stunde &#x3D; 2, Tag &#x3D; 3, Woche &#x3D; 4, Monat &#x3D; 5, Quartal &#x3D; 6, Halbjahr &#x3D; 7, Jahr &#x3D; 8) * @return timePeriod **/ @Schema(example = "6", description = "Zeitintervall (Unbekannt = 0, Minute = 1, Stunde = 2, Tag = 3, Woche = 4, Monat = 5, Quartal = 6, Halbjahr = 7, Jahr = 8)") public BigDecimal getTimePeriod() { return timePeriod; } public void setTimePeriod(BigDecimal timePeriod) { this.timePeriod = timePeriod; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InsuranceContractMaxPermanentPrescriptionPeriod insuranceContractMaxPermanentPrescriptionPeriod = (InsuranceContractMaxPermanentPrescriptionPeriod) o; return Objects.equals(this.amount, insuranceContractMaxPermanentPrescriptionPeriod.amount) && Objects.equals(this.timePeriod, insuranceContractMaxPermanentPrescriptionPeriod.timePeriod); } @Override public int hashCode() { return Objects.hash(amount, timePeriod); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractMaxPermanentPrescriptionPeriod {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" timePeriod: ").append(toIndentedString(timePeriod)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaxPermanentPrescriptionPeriod.java
2
请完成以下Java代码
public static Pair<DataType, Object> castValue(String value) { if (isNumber(value)) { String formattedValue = value.replace(',', '.'); try { BigDecimal bd = new BigDecimal(formattedValue); if (bd.stripTrailingZeros().scale() > 0 || isSimpleDouble(formattedValue)) { if (bd.scale() <= 16) { return Pair.of(DataType.DOUBLE, bd.doubleValue()); } } else { return Pair.of(DataType.LONG, bd.longValueExact()); } } catch (RuntimeException ignored) {} } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) { return Pair.of(DataType.BOOLEAN, Boolean.parseBoolean(value)); } else if (looksLikeJson(value)) { try { return Pair.of(DataType.JSON, JsonParser.parseString(value)); } catch (Exception ignored) { } } return Pair.of(DataType.STRING, value); } public static Pair<DataType, Number> castToNumber(String value) { if (isNumber(value)) { String formattedValue = value.replace(',', '.'); BigDecimal bd = new BigDecimal(formattedValue); if (bd.stripTrailingZeros().scale() > 0 || isSimpleDouble(formattedValue)) { if (bd.scale() <= 16) { return Pair.of(DataType.DOUBLE, bd.doubleValue()); } else { return Pair.of(DataType.DOUBLE, bd); } } else { return Pair.of(DataType.LONG, bd.longValueExact());
} } else { throw new IllegalArgumentException("'" + value + "' can't be parsed as number"); } } private static boolean isNumber(String value) { return NumberUtils.isNumber(value.replace(',', '.')); } private static boolean isSimpleDouble(String valueAsString) { return valueAsString.contains(".") && !valueAsString.contains("E") && !valueAsString.contains("e"); } private static boolean looksLikeJson(String value) { String trimmed = value.trim(); return (trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]")); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\util\TypeCastUtil.java
1
请完成以下Java代码
private static class RegisteredSslBundle { private final String name; private final List<Consumer<SslBundle>> updateHandlers = new CopyOnWriteArrayList<>(); private volatile SslBundle bundle; RegisteredSslBundle(String name, SslBundle bundle) { this.name = name; this.bundle = bundle; } void update(SslBundle updatedBundle) { Assert.notNull(updatedBundle, "'updatedBundle' must not be null"); this.bundle = updatedBundle; if (this.updateHandlers.isEmpty()) { logger.warn(LogMessage.format( "SSL bundle '%s' has been updated but may be in use by a technology that doesn't support SSL reloading", this.name)); }
this.updateHandlers.forEach((handler) -> handler.accept(updatedBundle)); } SslBundle getBundle() { return this.bundle; } void addUpdateHandler(Consumer<SslBundle> updateHandler) { Assert.notNull(updateHandler, "'updateHandler' must not be null"); this.updateHandlers.add(updateHandler); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\DefaultSslBundleRegistry.java
1
请在Spring Boot框架中完成以下Java代码
public class AddressParser { public static Address analyzeAddresses(String query, JSONArray jsonAddresses){ List<Address> addresses = new ArrayList<Address>(); for(int i=0; i < jsonAddresses.size(); i++) { Address address = new Address((JSONObject)jsonAddresses.get(i)); address.sd = (int)Math.round(StringSimilarity.editDistanceWord(address.getAddr(), query)); addresses.add(address); } List<Address> cleanAddresses = new ArrayList<Address>(); for(Address a : addresses) if(a.sd < 55 && a.lon != 0.0d && a.lat != 0.0d) cleanAddresses.add(a); Collections.sort(cleanAddresses, new StringSimilarity<Address>(query)); List<Address> newAddresses = new ArrayList<Address>(); if(cleanAddresses.size() > 0) { newAddresses.add(cleanAddresses.get(0)); for(int i = 1; i < cleanAddresses.size(); i++) { boolean b = false; for(int j = 0; j < newAddresses.size(); j++) { Double lat = cleanAddresses.get(i).lat; Double lon = cleanAddresses.get(i).lon; Double alat = newAddresses.get(j).lat; Double alon = newAddresses.get(j).lon; if((lat - alat <= 0.001) && (lon - alon <= 0.001)) { cleanAddresses.get(i).lat = (alat + lat) / 2;
cleanAddresses.get(i).lon = (alon + lon) / 2; b = true; break; } } if(!b) newAddresses.add(cleanAddresses.get(i)); } } if(newAddresses.size() > 0) return newAddresses.get(0); else return null; } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\AddressParser.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + ", email=" + email + ", address=" + address + ", rating=" + rating + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDynamicProjection\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getWeight() {
return weight; } public void setWeight(int weight) { this.weight = weight; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ManyToOne @JoinColumn(name = "customer_id") private User customer; }
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\Product.java
1
请完成以下Java代码
public class Main { public static void main(final String[] args) { final CommandlineParams commandlineParams = new CommandlineParams(); final RolloutMigrationConfig config = commandlineParams.init(args); main(config); } /** * Alternative main method to be called directly from other code, rather than the command-line. * Allows to run the toll without the presence of a settings-file */ public static void main(@NonNull final RolloutMigrationConfig config) { final DirectoryChecker directoryChecker = new DirectoryChecker(); final PropertiesFileLoader propertiesFileLoader = new PropertiesFileLoader(directoryChecker); final SettingsLoader settingsLoader = new SettingsLoader(directoryChecker, propertiesFileLoader); final RolloutVersionLoader rolloutVersionLoader = new RolloutVersionLoader(propertiesFileLoader); final DBConnectionMaker dbConnectionMaker = new DBConnectionMaker(); final DBVersionGetter dbVersionGetter = new DBVersionGetter(dbConnectionMaker); final MigrationScriptApplier migrationScriptApplier = new MigrationScriptApplier(directoryChecker, dbConnectionMaker);
final RolloutMigrate rolloutMigrate = new RolloutMigrate( directoryChecker, propertiesFileLoader, settingsLoader, rolloutVersionLoader, dbConnectionMaker, dbVersionGetter, migrationScriptApplier); if (config.isCanRun()) { rolloutMigrate.run(config); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\Main.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(HttpSecurity builder) { AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class); AuthorizationServerSettings authorizationServerSettings = OAuth2ConfigurerUtils .getAuthorizationServerSettings(builder); String deviceAuthorizationEndpointUri = authorizationServerSettings.isMultipleIssuersAllowed() ? OAuth2ConfigurerUtils .withMultipleIssuersPattern(authorizationServerSettings.getDeviceAuthorizationEndpoint()) : authorizationServerSettings.getDeviceAuthorizationEndpoint(); OAuth2DeviceAuthorizationEndpointFilter deviceAuthorizationEndpointFilter = new OAuth2DeviceAuthorizationEndpointFilter( authenticationManager, deviceAuthorizationEndpointUri); List<AuthenticationConverter> authenticationConverters = createDefaultAuthenticationConverters(); if (!this.deviceAuthorizationRequestConverters.isEmpty()) { authenticationConverters.addAll(0, this.deviceAuthorizationRequestConverters); } this.deviceAuthorizationRequestConvertersConsumer.accept(authenticationConverters); deviceAuthorizationEndpointFilter .setAuthenticationConverter(new DelegatingAuthenticationConverter(authenticationConverters)); if (this.deviceAuthorizationResponseHandler != null) { deviceAuthorizationEndpointFilter.setAuthenticationSuccessHandler(this.deviceAuthorizationResponseHandler); } if (this.errorResponseHandler != null) { deviceAuthorizationEndpointFilter.setAuthenticationFailureHandler(this.errorResponseHandler); } if (StringUtils.hasText(this.verificationUri)) { deviceAuthorizationEndpointFilter.setVerificationUri(this.verificationUri); } builder.addFilterAfter(postProcess(deviceAuthorizationEndpointFilter), AuthorizationFilter.class); } @Override RequestMatcher getRequestMatcher() { return this.requestMatcher; }
private static List<AuthenticationConverter> createDefaultAuthenticationConverters() { List<AuthenticationConverter> authenticationConverters = new ArrayList<>(); authenticationConverters.add(new OAuth2DeviceAuthorizationRequestAuthenticationConverter()); return authenticationConverters; } private static List<AuthenticationProvider> createDefaultAuthenticationProviders(HttpSecurity builder) { List<AuthenticationProvider> authenticationProviders = new ArrayList<>(); OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(builder); OAuth2DeviceAuthorizationRequestAuthenticationProvider deviceAuthorizationRequestAuthenticationProvider = new OAuth2DeviceAuthorizationRequestAuthenticationProvider( authorizationService); authenticationProviders.add(deviceAuthorizationRequestAuthenticationProvider); return authenticationProviders; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2DeviceAuthorizationEndpointConfigurer.java
2
请完成以下Java代码
public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level;
} public SchoolShallowCopy getSchool() { return school; } public void setSchool(SchoolShallowCopy school) { this.school = school; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
repos\tutorials-master\core-java-modules\core-java-lang-5\src\main\java\com\baeldung\deepshallowcopy\StudentShallowCopy.java
1
请完成以下Java代码
public void updateAllM_HU_PI_Item_Products(final I_M_Product product) { final List<I_M_HU_PI_Item_Product> huPIPs = Services.get(IHUPIItemProductDAO.class).retrieveAllForProduct(product); final int productStockingUomId = product.getC_UOM_ID(); for (final I_M_HU_PI_Item_Product huPIP : huPIPs) { huPIP.setC_UOM_ID(productStockingUomId); InterfaceWrapperHelper.save(huPIP); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_M_Product.COLUMNNAME_IsActive) public void isActive(@NonNull final I_M_Product product) { if (product.isActive()) { return; }
final IStorageEngine storageEngine = storageEngineProvider.getStorageEngine(); final IStorageQuery storageQuery = storageEngine.newStorageQuery() .addProductId(ProductId.ofRepoId(product.getM_Product_ID())) .setExcludeAfterPickingLocator(false) .setOnlyActiveHUs(true); final IContextAware context = PlainContextAware.createUsingOutOfTransaction(); final boolean isAvailableStock = storageEngine.anyMatch(context, storageQuery); if (isAvailableStock) { throw new AdempiereException(INACTIVE_PRODUCTS_WITH_STOCK); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_Product.java
1
请在Spring Boot框架中完成以下Java代码
private PickingJobCandidateProduct allocate(final PickingJobCandidateProduct product) { final Quantity qtyToDeliver = product.getQtyToDeliver(); if (qtyToDeliver == null) { return product; } final ProductId productId = product.getProductId(); final Quantity qtyAvailableToPick = allocateQty(productId, qtyToDeliver); return product.withQtyAvailableToPick(qtyAvailableToPick); } public Quantity allocateQty(@NonNull final ProductId productId, @NonNull final Quantity qtyToDeliver) { return getByProductId(productId) .allocateQty(qtyToDeliver) .toZeroIfNegative(); } private ProductAvailableStock getByProductId(final ProductId productId) { return CollectionUtils.getOrLoad(map, productId, this::loadByProductIds); } public void warmUpByProductIds(final Set<ProductId> productIds) { CollectionUtils.getAllOrLoad(map, productIds, this::loadByProductIds); } private Map<ProductId, ProductAvailableStock> loadByProductIds(final Set<ProductId> productIds)
{ final HashMap<ProductId, ProductAvailableStock> result = new HashMap<>(); productIds.forEach(productId -> result.put(productId, new ProductAvailableStock())); streamHUProductStorages(productIds) .forEach(huStorageProduct -> result.get(huStorageProduct.getProductId()).addQtyOnHand(huStorageProduct.getQty())); return result; } private Stream<IHUProductStorage> streamHUProductStorages(final Set<ProductId> productIds) { final List<I_M_HU> hus = handlingUnitsBL.createHUQueryBuilder() .onlyContextClient(false) // fails when running from non-context threads like websockets value producers .addOnlyWithProductIds(productIds) .addOnlyInLocatorIds(pickFromLocatorIds) .setOnlyActiveHUs(true) .list(); final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory(); return storageFactory.streamHUProductStorages(hus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\ProductAvailableStocks.java
2
请在Spring Boot框架中完成以下Java代码
public class RenameObjectService { private S3Client s3Client; public RenameObjectService(S3Client s3Client) { this.s3Client = s3Client; } public RenameObjectService() { init(); } public void init() { this.s3Client = S3Client.builder() .region(Region.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create("default")) .build(); } public void renameFile(String bucketName, String keyName, String destinationKeyName) { CopyObjectRequest copyObjRequest = CopyObjectRequest.builder() .sourceBucket(bucketName) .sourceKey(keyName) .destinationBucket(destinationKeyName) .destinationKey(bucketName) .build(); s3Client.copyObject(copyObjRequest); DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder() .bucket(bucketName) .key(keyName) .build(); s3Client.deleteObject(deleteRequest); } public void renameFolder(String bucketName, String sourceFolderKey, String destinationFolderKey) { ListObjectsV2Request listRequest = ListObjectsV2Request.builder() .bucket(bucketName) .prefix(sourceFolderKey) .build(); ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest);
List<S3Object> objects = listResponse.contents(); for (S3Object s3Object : objects) { String newKey = destinationFolderKey + s3Object.key() .substring(sourceFolderKey.length()); // Copy object to destination folder CopyObjectRequest copyRequest = CopyObjectRequest.builder() .sourceBucket(bucketName) .sourceKey(s3Object.key()) .destinationBucket(bucketName) .destinationKey(newKey) .build(); s3Client.copyObject(copyRequest); // Delete object from source folder DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder() .bucket(bucketName) .key(s3Object.key()) .build(); s3Client.deleteObject(deleteRequest); } } }
repos\tutorials-master\aws-modules\aws-s3\src\main\java\com\baeldung\s3\RenameObjectService.java
2
请在Spring Boot框架中完成以下Java代码
public void accept(Resilience4JConfigBuilder resilience4JConfigBuilder) { // 创建 TimeLimiterConfig 对象 TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)) // 自定义 .build(); // 创建 CircuitBreakerConfig 对象 CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() // 自定义 .slidingWindow(5, 5, CircuitBreakerConfig.SlidingWindowType.COUNT_BASED) .build(); // 设置 Resilience4JCircuitBreakerConfiguration 对象 resilience4JConfigBuilder .timeLimiterConfig(timeLimiterConfig) .circuitBreakerConfig(circuitBreakerConfig); } }, "slow"); } }; } // @Bean // public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() { // return factory -> factory.configureDefault(
// id -> new Resilience4JConfigBuilder(id) // .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(4)).build()) // .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()) // .build()); // } // @Bean // public Customizer<Resilience4JCircuitBreakerFactory> slowCustomizer() { // return factory -> factory.configure(builder -> builder // .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(2)).build()) // .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults()), // "slow"); // } }
repos\SpringBoot-Labs-master\labx-24\labx-24-resilience4j-demo02\src\main\java\cn\iocoder\springcloud\labx24\resilience4jdemo\config\Resilience4jConfig.java
2
请完成以下Java代码
public long[] getBestPosition() { return bestPosition; } /** * Gets the {@link #bestFitness}. * * @return the {@link #bestFitness} */ public double getBestFitness() { return bestFitness; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(bestFitness); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(bestPosition); result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode()); result = prime * result + ((random == null) ? 0 : random.hashCode()); result = prime * result + Arrays.hashCode(swarms); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false;
if (getClass() != obj.getClass()) return false; Multiswarm other = (Multiswarm) obj; if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness)) return false; if (!Arrays.equals(bestPosition, other.bestPosition)) return false; if (fitnessFunction == null) { if (other.fitnessFunction != null) return false; } else if (!fitnessFunction.equals(other.fitnessFunction)) return false; if (random == null) { if (other.random != null) return false; } else if (!random.equals(other.random)) return false; if (!Arrays.equals(swarms, other.swarms)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]"; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Multiswarm.java
1
请完成以下Java代码
public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Charge getC_Charge() throws RuntimeException { return (I_C_Charge)MTable.get(getCtx(), I_C_Charge.Table_Name) .getPO(getC_Charge_ID(), get_TrxName()); } /** Set Charge. @param C_Charge_ID Additional document charges */ public void setC_Charge_ID (int C_Charge_ID) { if (C_Charge_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Charge_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Charge_ID, Integer.valueOf(C_Charge_ID)); } /** Get Charge. @return Additional document charges */ public int getC_Charge_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Charge_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCh_Expense_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCh_Expense_Acct(), get_TrxName()); } /** Set Charge Expense. @param Ch_Expense_Acct Charge Expense Account */ public void setCh_Expense_Acct (int Ch_Expense_Acct) { set_Value (COLUMNNAME_Ch_Expense_Acct, Integer.valueOf(Ch_Expense_Acct)); }
/** Get Charge Expense. @return Charge Expense Account */ public int getCh_Expense_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Expense_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCh_Revenue_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCh_Revenue_Acct(), get_TrxName()); } /** Set Charge Revenue. @param Ch_Revenue_Acct Charge Revenue Account */ public void setCh_Revenue_Acct (int Ch_Revenue_Acct) { set_Value (COLUMNNAME_Ch_Revenue_Acct, Integer.valueOf(Ch_Revenue_Acct)); } /** Get Charge Revenue. @return Charge Revenue Account */ public int getCh_Revenue_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_Ch_Revenue_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_Charge_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public void setClientBackoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; LOG.backoffStrategyFound(); } @Override public Class<ExternalTaskClient> getObjectType() { return ExternalTaskClient.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { } public ClientConfiguration getClientConfiguration() { return clientConfiguration; } public void setClientConfiguration(ClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } public List<ClientRequestInterceptor> getRequestInterceptors() { return requestInterceptors; } protected void close() { if (client != null) { client.stop(); } } @Autowired(required = false)
protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) { PropertySources appliedPropertySources = configurer.getAppliedPropertySources(); propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources); } protected String resolve(String property) { if (propertyResolver == null) { return property; } if (property != null) { return propertyResolver.resolvePlaceholders(property); } else { return null; } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java
2
请完成以下Java代码
public static PPOrderRef ofPPOrderBOMLineId(@NonNull final PPOrderAndBOMLineId ppOrderAndBOMLineId) { return ofPPOrderBOMLineId(ppOrderAndBOMLineId.getPpOrderId(), ppOrderAndBOMLineId.getLineId()); } @Nullable public static PPOrderRef ofPPOrderAndLineIdOrNull(final int ppOrderRepoId, final int ppOrderBOMLineRepoId) { final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ppOrderRepoId); if (ppOrderId == null) { return null; } return builder().ppOrderId(ppOrderId).ppOrderBOMLineId(PPOrderBOMLineId.ofRepoIdOrNull(ppOrderBOMLineRepoId)).build(); } public boolean isFinishedGoods() { return !isBOMLine(); } public boolean isBOMLine() { return ppOrderBOMLineId != null; } public PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { final PPOrderId ppOrderIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getPpOrderId() : null; final PPOrderBOMLineId lineIdNew = newPPOrderAndBOMLineId != null ? newPPOrderAndBOMLineId.getLineId() : null; return PPOrderId.equals(this.ppOrderId, ppOrderIdNew) && PPOrderBOMLineId.equals(this.ppOrderBOMLineId, lineIdNew) ? this : toBuilder().ppOrderId(ppOrderIdNew).ppOrderBOMLineId(lineIdNew).build(); } public PPOrderRef withPPOrderId(@Nullable final PPOrderId ppOrderId) { if (PPOrderId.equals(this.ppOrderId, ppOrderId)) { return this; } return toBuilder().ppOrderId(ppOrderId).build(); }
@Nullable public static PPOrderRef withPPOrderId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderId newPPOrderId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderId(newPPOrderId); } else if (newPPOrderId != null) { return ofPPOrderId(newPPOrderId); } else { return null; } } @Nullable public static PPOrderRef withPPOrderAndBOMLineId(@Nullable final PPOrderRef ppOrderRef, @Nullable final PPOrderAndBOMLineId newPPOrderAndBOMLineId) { if (ppOrderRef != null) { return ppOrderRef.withPPOrderAndBOMLineId(newPPOrderAndBOMLineId); } else if (newPPOrderAndBOMLineId != null) { return ofPPOrderBOMLineId(newPPOrderAndBOMLineId); } else { return null; } } @Nullable public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return PPOrderAndBOMLineId.ofNullable(ppOrderId, ppOrderBOMLineId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\pporder\PPOrderRef.java
1
请完成以下Java代码
public void setC_NonBusinessDay_ID (int C_NonBusinessDay_ID) { if (C_NonBusinessDay_ID < 1) set_ValueNoCheck (COLUMNNAME_C_NonBusinessDay_ID, null); else set_ValueNoCheck (COLUMNNAME_C_NonBusinessDay_ID, Integer.valueOf(C_NonBusinessDay_ID)); } /** Get Geschäftsfreier Tag. @return Day on which business is not transacted */ @Override public int getC_NonBusinessDay_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_NonBusinessDay_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum. @param Date1 Date when business is not conducted */ @Override public void setDate1 (java.sql.Timestamp Date1) { set_Value (COLUMNNAME_Date1, Date1); } /** Get Datum. @return Date when business is not conducted */ @Override public java.sql.Timestamp getDate1 () { return (java.sql.Timestamp)get_Value(COLUMNNAME_Date1); } /** Set Enddatum. @param EndDate Last effective date (inclusive) */ @Override public void setEndDate (java.sql.Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get Enddatum. @return Last effective date (inclusive) */ @Override public java.sql.Timestamp getEndDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_EndDate); } /** * Frequency AD_Reference_ID=540870 * Reference name: C_NonBusinessDay_Frequency */ public static final int FREQUENCY_AD_Reference_ID=540870; /** Weekly = W */ public static final String FREQUENCY_Weekly = "W"; /** Yearly = Y */ public static final String FREQUENCY_Yearly = "Y"; /** Set Häufigkeit. @param Frequency Häufigkeit von Ereignissen */ @Override public void setFrequency (java.lang.String Frequency) { set_Value (COLUMNNAME_Frequency, Frequency); } /** Get Häufigkeit. @return Häufigkeit von Ereignissen
*/ @Override public java.lang.String getFrequency () { return (java.lang.String)get_Value(COLUMNNAME_Frequency); } /** Set Repeat. @param IsRepeat Repeat */ @Override public void setIsRepeat (boolean IsRepeat) { set_Value (COLUMNNAME_IsRepeat, Boolean.valueOf(IsRepeat)); } /** Get Repeat. @return Repeat */ @Override public boolean isRepeat () { Object oo = get_Value(COLUMNNAME_IsRepeat); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_NonBusinessDay.java
1
请完成以下Java代码
public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) { // start and end event listener are set by parseBoundaryEvent() } @Override public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) { } @Override public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); }
@Override public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) { addStartEventListener(activity); addEndEventListener(activity); } @Override public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) { } @Override public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) { } @Override public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) { } @Override public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) { } @Override public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) { } public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) { } @Override public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) { } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventParseListener.java
1
请完成以下Java代码
public static char convert(char c) { return CONVERT[c]; } public static char[] convert(char[] charArray) { char[] result = new char[charArray.length]; for (int i = 0; i < charArray.length; i++) { result[i] = CONVERT[charArray[i]]; } return result; } public static String convert(String sentence) { assert sentence != null; char[] result = new char[sentence.length()]; convert(sentence, result); return new String(result); } public static void convert(String charArray, char[] result) { for (int i = 0; i < charArray.length(); i++) { result[i] = CONVERT[charArray.charAt(i)]; } } /** * 正规化一些字符(原地正规化) * @param charArray 字符 */ public static void normalization(char[] charArray) { assert charArray != null; for (int i = 0; i < charArray.length; i++)
{ charArray[i] = CONVERT[charArray[i]]; } } public static void normalize(Sentence sentence) { for (IWord word : sentence) { if (word instanceof CompoundWord) { for (Word w : ((CompoundWord) word).innerList) { w.value = convert(w.value); } } else word.setValue(word.getValue()); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\other\CharTable.java
1
请完成以下Java代码
protected <T extends BasicClassicHttpRequest> T createHttpRequestBase(Q request) { String url = request.getUrl(); if (url != null && !url.trim().isEmpty()) { String method = request.getMethod(); if (HttpGet.METHOD_NAME.equals(method)) { return (T) new HttpGet(url); } else if (HttpPost.METHOD_NAME.equals(method)) { return (T) new HttpPost(url); } else if (HttpPut.METHOD_NAME.equals(method)) { return (T) new HttpPut(url); } else if (HttpDelete.METHOD_NAME.equals(method)) { return (T) new HttpDelete(url); } else if (HttpPatch.METHOD_NAME.equals(method)) { return (T) new HttpPatch(url); } else if (HttpHead.METHOD_NAME.equals(method)) { return (T) new HttpHead(url); } else if (HttpOptions.METHOD_NAME.equals(method)) { return (T) new HttpOptions(url); } else if (HttpTrace.METHOD_NAME.equals(method)) { return (T) new HttpTrace(url); } else { throw LOG.unknownHttpMethod(method); } } else { throw LOG.requestUrlRequired(); } } protected <T extends BasicClassicHttpRequest> void applyHeaders(T httpRequest, Map<String, String> headers) { if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpRequest.setHeader(entry.getKey(), entry.getValue()); LOG.setHeader(entry.getKey(), entry.getValue()); } } } protected <T extends BasicClassicHttpRequest> void applyPayload(T httpRequest, Q request) {
if (httpMethodSupportsPayload(httpRequest)) { if (request.getPayload() != null) { byte[] bytes = request.getPayload().getBytes(charset); ByteArrayInputStream payload = new ByteArrayInputStream(bytes); InputStreamEntity entity = new InputStreamEntity(payload, bytes.length, ContentType.parse(request.getContentType())); httpRequest.setEntity(entity); } } else if (request.getPayload() != null) { LOG.payloadIgnoredForHttpMethod(request.getMethod()); } } protected <T extends BasicClassicHttpRequest> boolean httpMethodSupportsPayload(T httpRequest) { return httpRequest instanceof HttpUriRequestBase; } protected <T extends BasicClassicHttpRequest> void applyConfig(T httpRequest, Map<String, Object> configOptions) { if (httpMethodSupportsPayload(httpRequest)) { Builder configBuilder = RequestConfig.custom(); if (configOptions != null && !configOptions.isEmpty()) { ParseUtil.parseConfigOptions(configOptions, configBuilder); } RequestConfig requestConfig = configBuilder.build(); ((HttpUriRequestBase) httpRequest).setConfig(requestConfig); } } }
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpConnector.java
1
请完成以下Java代码
public String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public org.compiere.model.I_AD_Color getInsufficientQtyAvailableForSalesColor() { return get_ValueAsPO(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, org.compiere.model.I_AD_Color.class); } @Override public void setInsufficientQtyAvailableForSalesColor(final org.compiere.model.I_AD_Color InsufficientQtyAvailableForSalesColor) { set_ValueFromPO(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, org.compiere.model.I_AD_Color.class, InsufficientQtyAvailableForSalesColor); } @Override public void setInsufficientQtyAvailableForSalesColor_ID (final int InsufficientQtyAvailableForSalesColor_ID) { if (InsufficientQtyAvailableForSalesColor_ID < 1) set_Value (COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, null); else set_Value (COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, InsufficientQtyAvailableForSalesColor_ID); } @Override public int getInsufficientQtyAvailableForSalesColor_ID() { return get_ValueAsInt(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID); } @Override public void setIsAsync (final boolean IsAsync) { set_Value (COLUMNNAME_IsAsync, IsAsync); } @Override public boolean isAsync() { return get_ValueAsBoolean(COLUMNNAME_IsAsync); } @Override public void setIsFeatureActivated (final boolean IsFeatureActivated) { set_Value (COLUMNNAME_IsFeatureActivated, IsFeatureActivated); } @Override public boolean isFeatureActivated() { return get_ValueAsBoolean(COLUMNNAME_IsFeatureActivated); } @Override public void setIsQtyPerWarehouse (final boolean IsQtyPerWarehouse) { set_Value (COLUMNNAME_IsQtyPerWarehouse, IsQtyPerWarehouse); } @Override public boolean isQtyPerWarehouse() { return get_ValueAsBoolean(COLUMNNAME_IsQtyPerWarehouse); } @Override public void setMD_AvailableForSales_Config_ID (final int MD_AvailableForSales_Config_ID)
{ if (MD_AvailableForSales_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_AvailableForSales_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_AvailableForSales_Config_ID, MD_AvailableForSales_Config_ID); } @Override public int getMD_AvailableForSales_Config_ID() { return get_ValueAsInt(COLUMNNAME_MD_AvailableForSales_Config_ID); } @Override public void setSalesOrderLookBehindHours (final int SalesOrderLookBehindHours) { set_Value (COLUMNNAME_SalesOrderLookBehindHours, SalesOrderLookBehindHours); } @Override public int getSalesOrderLookBehindHours() { return get_ValueAsInt(COLUMNNAME_SalesOrderLookBehindHours); } @Override public void setShipmentDateLookAheadHours (final int ShipmentDateLookAheadHours) { set_Value (COLUMNNAME_ShipmentDateLookAheadHours, ShipmentDateLookAheadHours); } @Override public int getShipmentDateLookAheadHours() { return get_ValueAsInt(COLUMNNAME_ShipmentDateLookAheadHours); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_AvailableForSales_Config.java
1
请完成以下Java代码
public void setUserId(String userId) { this.userId = userId; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public byte[] getPasswordBytes() { return passwordBytes; } public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return key; } public String getUsername() { return value; }
public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public Map<String, String> getDetails() { return details; } public void setDetails(Map<String, String> details) { this.details = details; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", type=" + type + ", userId=" + userId + ", key=" + key + ", value=" + value + ", password=" + password + ", parentId=" + parentId + ", details=" + details + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java
1
请完成以下Java代码
public int getC_BPartner_Department_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Department_ID); } @Override public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Department.java
1
请完成以下Java代码
public class GenericFinancialIdentification1CH { @XmlElement(name = "Id", required = true) protected String id; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id;
} /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\GenericFinancialIdentification1CH.java
1
请在Spring Boot框架中完成以下Java代码
public ShipFromType getShipFrom() { return shipFrom; } /** * Sets the value of the shipFrom property. * * @param value * allowed object is * {@link ShipFromType } * */ public void setShipFrom(ShipFromType value) { this.shipFrom = value; } /** * Gets the value of the deliveryOrTransportTermsFunctionCode property. * * @return * possible object is * {@link String } * */ public String getDeliveryOrTransportTermsFunctionCode() { return deliveryOrTransportTermsFunctionCode; } /** * Sets the value of the deliveryOrTransportTermsFunctionCode property. * * @param value * allowed object is * {@link String } * */ public void setDeliveryOrTransportTermsFunctionCode(String value) { this.deliveryOrTransportTermsFunctionCode = value; } /** * Gets the value of the shipmentNetWeight property. * * @return * possible object is * {@link UnitType } * */ public UnitType getShipmentNetWeight() { return shipmentNetWeight; } /** * Sets the value of the shipmentNetWeight property. * * @param value * allowed object is * {@link UnitType } * */ public void setShipmentNetWeight(UnitType value) { this.shipmentNetWeight = value; } /** * Gets the value of the shipmentGrossWeight property. * * @return * possible object is * {@link UnitType } * */ public UnitType getShipmentGrossWeight() { return shipmentGrossWeight; } /** * Sets the value of the shipmentGrossWeight property.
* * @param value * allowed object is * {@link UnitType } * */ public void setShipmentGrossWeight(UnitType value) { this.shipmentGrossWeight = value; } /** * Gets the value of the shipmentNumberOfPackages property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getShipmentNumberOfPackages() { return shipmentNumberOfPackages; } /** * Sets the value of the shipmentNumberOfPackages property. * * @param value * allowed object is * {@link BigInteger } * */ public void setShipmentNumberOfPackages(BigInteger value) { this.shipmentNumberOfPackages = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DeliveryDetailsExtensionType.java
2