instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private static boolean validateScope(String scope) { return scope == null || scope.chars() .allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); } private static boolean withinTheRangeOf(int c, int min, int max) { return c >= min && c <= max; } private void validateRedirectUris() { if (CollectionUtils.isEmpty(this.redirectUris)) { return; } for (String redirectUri : this.redirectUris) { Assert.isTrue(validateRedirectUri(redirectUri), "redirect_uri \"" + redirectUri + "\" is not a valid redirect URI or contains fragment"); } } private void validatePostLogoutRedirectUris() { if (CollectionUtils.isEmpty(this.postLogoutRedirectUris)) { return; } for (String postLogoutRedirectUri : this.postLogoutRedirectUris) { Assert.isTrue(validateRedirectUri(postLogoutRedirectUri), "post_logout_redirect_uri \""
+ postLogoutRedirectUri + "\" is not a valid post logout redirect URI or contains fragment"); } } private static boolean validateRedirectUri(String redirectUri) { try { URI validRedirectUri = new URI(redirectUri); return validRedirectUri.getFragment() == null; } catch (URISyntaxException ex) { return false; } } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\RegisteredClient.java
1
请完成以下Java代码
public String getDescription() { return description; } } class CreateUserMessage implements Serializable { private static final long serialVersionUID = 1L; private final User user; public CreateUserMessage(User user) { this.user = user; } public User getUser() { return user; } }
class GetUserMessage implements Serializable { private static final long serialVersionUID = 1L; private final Long userId; public GetUserMessage(Long userId) { this.userId = userId; } public Long getUserId() { return userId; } } }
repos\tutorials-master\akka-modules\akka-http\src\main\java\com\baeldung\akkahttp\UserMessages.java
1
请完成以下Java代码
private static String expandRedirectUri(ServerHttpRequest request, ClientRegistration clientRegistration) { Map<String, String> uriVariables = new HashMap<>(); uriVariables.put("registrationId", clientRegistration.getRegistrationId()); // @formatter:off UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()) .replacePath(request.getPath().contextPath().value()) .replaceQuery(null) .fragment(null) .build(); // @formatter:on String scheme = uriComponents.getScheme(); uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path)) { if (path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } } uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); String action = ""; if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) { action = "login"; } uriVariables.put("action", action); // @formatter:off return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri()) .buildAndExpand(uriVariables) .toUriString(); // @formatter:on } /**
* Creates nonce and its hash for use in OpenID Connect 1.0 Authentication Requests. * @param builder where the {@link OidcParameterNames#NONCE} and hash is stored for * the authentication request * * @since 5.2 * @see <a target="_blank" href= * "https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest">3.1.2.1. * Authentication Request</a> */ private static void applyNonce(OAuth2AuthorizationRequest.Builder builder) { try { String nonce = DEFAULT_SECURE_KEY_GENERATOR.generateKey(); String nonceHash = createHash(nonce); builder.attributes((attrs) -> attrs.put(OidcParameterNames.NONCE, nonce)); builder.additionalParameters((params) -> params.put(OidcParameterNames.NONCE, nonceHash)); } catch (NoSuchAlgorithmException ex) { } } private static String createHash(String value) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolver.java
1
请完成以下Java代码
public class TextApplication { public static void main(String[] args) throws NamingException { TextProcessorRemote textProcessor = EJBFactory.createTextProcessorBeanFromJNDI("ejb:"); System.out.print(textProcessor.processText("sample text")); } private static class EJBFactory { private static TextProcessorRemote createTextProcessorBeanFromJNDI(String namespace) throws NamingException { return lookupTextProcessorBean(namespace); } private static TextProcessorRemote lookupTextProcessorBean(String namespace) throws NamingException { Context ctx = createInitialContext(); final String appName = ""; final String moduleName = "spring-ejb-remote";
final String distinctName = ""; final String beanName = TextProcessorBean.class.getSimpleName(); final String viewClassName = TextProcessorRemote.class.getName(); return (TextProcessorRemote) ctx.lookup(namespace + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName); } private static Context createInitialContext() throws NamingException { Properties jndiProperties = new Properties(); jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080"); jndiProperties.put("jboss.naming.client.ejb.context", true); return new InitialContext(jndiProperties); } } }
repos\tutorials-master\spring-ejb-modules\spring-ejb-client\src\main\java\com\baeldung\ejb\wildfly\TextApplication.java
1
请完成以下Java代码
public static Sql ofSql(@NonNull final String sql, @Nullable SqlParams sqlParamsMap) { return new Sql(sql, sqlParamsMap, null); } public static Sql ofComment(@NonNull final String comment) {return new Sql(null, null, comment);} private Sql( @Nullable final String sqlCommand, @Nullable final SqlParams sqlParams, @Nullable final String comment) { this.sqlCommand2 = StringUtils.trimBlankToNull(sqlCommand); this.sqlParams = sqlParams != null ? sqlParams : SqlParams.EMPTY; this.comment = StringUtils.trimBlankToNull(comment); } @Override @Deprecated public String toString() {return toSql();} public boolean isEmpty() {return sqlCommand2 == null && comment == null;} public String getSqlCommand() {return sqlCommand2 != null ? sqlCommand2 : "";} public String toSql() { String sqlWithInlinedParams = this._sqlWithInlinedParams; if (sqlWithInlinedParams == null) { sqlWithInlinedParams = this._sqlWithInlinedParams = buildFinalSql(); } return sqlWithInlinedParams; } private String buildFinalSql() { final StringBuilder finalSql = new StringBuilder(); final String sqlComment = toSqlCommentLine(comment); if (sqlComment != null) { finalSql.append(sqlComment); } if (sqlCommand2 != null && !sqlCommand2.isEmpty()) {
finalSql.append(toSqlCommentLine(timestamp.toString())); final String sqlWithParams = !sqlParams.isEmpty() ? sqlParamsInliner.inline(sqlCommand2, sqlParams.toList()) : sqlCommand2; finalSql.append(sqlWithParams).append("\n;\n\n"); } return finalSql.toString(); } private static String toSqlCommentLine(@Nullable final String comment) { final String commentNorm = StringUtils.trimBlankToNull(comment); if (commentNorm == null) { return null; } return "-- " + commentNorm .replace("\r\n", "\n") .replace("\n", "\n-- ") + "\n"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\Sql.java
1
请在Spring Boot框架中完成以下Java代码
public List<Product> getProducts(Integer pageSize, Integer pageNumber) { return PRODUCT_LIST.stream() .skip((long) pageSize * pageNumber) .limit(pageSize) .collect(Collectors.toList()); } @Override public Product getProduct(Integer id) { return PRODUCT_LIST.stream() .filter(product -> product.getId().equals(id)) .findFirst().orElse(null); } @Override public Product save(ProductModel productModel) { Product product = new Product(PRODUCT_LIST.size() + 1, productModel); PRODUCT_LIST.add(product); return product; } @Override public Product update(Integer productId, ProductModel productModel) {
Product product = getProduct(productId); if (product != null) { update(product, productModel); } return product; } private void update(Product product, ProductModel productModel) { if (productModel != null) { System.out.println(productModel); Optional.ofNullable(productModel.getName()).ifPresent(product::setName); Optional.ofNullable(productModel.getDescription()).ifPresent(product::setDescription); Optional.ofNullable(productModel.getCurrency()).ifPresent(product::setCurrency); Optional.ofNullable(productModel.getImageUrls()).ifPresent(product::setImageUrls); Optional.ofNullable(productModel.getStock()).ifPresent(product::setStock); Optional.ofNullable(productModel.getStatus()).ifPresent(product::setStatus); Optional.ofNullable(productModel.getVideoUrls()).ifPresent(product::setVideoUrls); Optional.ofNullable(productModel.getPrice()).ifPresent(product::setPrice); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\repository\impl\ProductRepositoryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public static class ReactiveRestApiConfiguration { private final AdminServerProperties adminServerProperties; public ReactiveRestApiConfiguration(AdminServerProperties adminServerProperties) { this.adminServerProperties = adminServerProperties; } @Bean @ConditionalOnMissingBean public de.codecentric.boot.admin.server.web.reactive.InstancesProxyController instancesProxyController( InstanceRegistry instanceRegistry, InstanceWebClient.Builder instanceWebClientBuilder) { return new de.codecentric.boot.admin.server.web.reactive.InstancesProxyController( this.adminServerProperties.getContextPath(), this.adminServerProperties.getInstanceProxy().getIgnoredHeaders(), instanceRegistry, instanceWebClientBuilder.build()); } @Bean public org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping adminHandlerMapping( RequestedContentTypeResolver webFluxContentTypeResolver) { org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping mapping = new de.codecentric.boot.admin.server.web.reactive.AdminControllerHandlerMapping( this.adminServerProperties.getContextPath()); mapping.setOrder(0); mapping.setContentTypeResolver(webFluxContentTypeResolver); return mapping; } } @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @AutoConfigureAfter(WebMvcAutoConfiguration.class) public static class ServletRestApiConfiguration { private final AdminServerProperties adminServerProperties; public ServletRestApiConfiguration(AdminServerProperties adminServerProperties) { this.adminServerProperties = adminServerProperties; } @Bean
@ConditionalOnMissingBean public de.codecentric.boot.admin.server.web.servlet.InstancesProxyController instancesProxyController( InstanceRegistry instanceRegistry, InstanceWebClient.Builder instanceWebClientBuilder) { return new de.codecentric.boot.admin.server.web.servlet.InstancesProxyController( this.adminServerProperties.getContextPath(), this.adminServerProperties.getInstanceProxy().getIgnoredHeaders(), instanceRegistry, instanceWebClientBuilder.build()); } @Bean public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping adminHandlerMapping( ContentNegotiationManager contentNegotiationManager) { org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping mapping = new de.codecentric.boot.admin.server.web.servlet.AdminControllerHandlerMapping( this.adminServerProperties.getContextPath()); mapping.setOrder(0); mapping.setContentNegotiationManager(contentNegotiationManager); return mapping; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerWebConfiguration.java
2
请完成以下Java代码
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } CustomAuthenticationToken authRequest = getAuthRequest(request); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } private CustomAuthenticationToken getAuthRequest(HttpServletRequest request) { String username = obtainUsername(request); String password = obtainPassword(request); String domain = obtainDomain(request);
if (username == null) { username = ""; } if (password == null) { password = ""; } if (domain == null) { domain = ""; } return new CustomAuthenticationToken(username, password, domain); } private String obtainDomain(HttpServletRequest request) { return request.getParameter(SPRING_SECURITY_FORM_DOMAIN_KEY); } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\CustomAuthenticationFilter.java
1
请完成以下Java代码
class VTreePanelSearchSupport { // services private final transient IMsgBL msgBL = Services.get(IMsgBL.class); // UI private final CLabel treeSearchLabel = new CLabel(); private final CTextField treeSearch = new CTextField(10); private final TreeSearchAutoCompleter treeSearchAutoCompleter; public VTreePanelSearchSupport() { super(); treeSearchAutoCompleter = new TreeSearchAutoCompleter(treeSearch) { @Override protected void onCurrentItemChanged(MTreeNode node) { onTreeNodeSelected(node); } }; treeSearchLabel.setText(msgBL.getMsg(Env.getCtx(), "TreeSearch") + " "); treeSearchLabel.setLabelFor(treeSearch); treeSearchLabel.setToolTipText(msgBL.getMsg(Env.getCtx(), "TreeSearchText")); treeSearch.setBackground(AdempierePLAF.getInfoBackground()); } /** * Executed when a node is selected by the user. * * @param node */ protected void onTreeNodeSelected(final MTreeNode node) { // nothing } /** * Loads the auto-complete suggestions. *
* @param root */ public final void setTreeNodesFromRoot(final MTreeNode root) { treeSearchAutoCompleter.setTreeNodes(root); } /** @return the search label of {@link #getSearchField()} */ public final CLabel getSearchFieldLabel() { return treeSearchLabel; } /** @return the search field (with auto-complete support) */ public final CTextField getSearchField() { return treeSearch; } public final void requestFocus() { treeSearch.requestFocus(); } public final boolean requestFocusInWindow() { return treeSearch.requestFocusInWindow(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreePanelSearchSupport.java
1
请在Spring Boot框架中完成以下Java代码
public void configure() { final CachingProvider cachingProvider = Caching.getCachingProvider(); final CacheManager cacheManager = cachingProvider.getCacheManager(); final MutableConfiguration<de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest, Object> config = new MutableConfiguration<>(); config.setTypes(de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest.class, Object.class); config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1))); final Cache<de.metas.camel.externalsystems.shopware6.unit.GetUnitsRequest, Object> cache = cacheManager.createCache("unit", config); final JCachePolicy jcachePolicy = new JCachePolicy(); jcachePolicy.setCache(cache); from(direct(GET_UOM_MAPPINGS_ROUTE_ID)) .id(GET_UOM_MAPPINGS_ROUTE_ID) .streamCache("true") .policy(jcachePolicy) .log("Route invoked. Results will be cached") .process(this::getUnits); } private void getUnits(final Exchange exchange) { final GetUnitsRequest getUnitsRequest = exchange.getIn().getBody(GetUnitsRequest.class); if (getUnitsRequest == null)
{ throw new RuntimeException("No getUnitsRequest provided!"); } final ShopwareClient shopwareClient = ShopwareClient .of(getUnitsRequest.getClientId(), getUnitsRequest.getClientSecret(), getUnitsRequest.getBaseUrl(), PInstanceLogger.of(processLogger)); final JsonUnits units = shopwareClient.getUnits(); if (CollectionUtils.isEmpty(units.getUnitList())) { throw new RuntimeException("No units return from Shopware!"); } final ImmutableMap<String, String> unitId2Code = units.getUnitList() .stream() .collect(ImmutableMap.toImmutableMap(JsonUOM::getId, JsonUOM::getShortCode)); final UOMInfoProvider uomInfoProvider = UOMInfoProvider.builder() .unitId2Code(unitId2Code) .build(); exchange.getIn().setBody(uomInfoProvider); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\unit\GetUnitsRouteBuilder.java
2
请完成以下Java代码
public static <T> void sort(List<T> list, Comparator<T> comparator) { sort(list, 0, list.size() - 1, comparator); } public static <T> void sort(List<T> list, int low, int high, Comparator<T> comparator) { if (low < high) { int partitionIndex = partition(list, low, high, comparator); sort(list, low, partitionIndex - 1, comparator); sort(list, partitionIndex + 1, high, comparator); } } private static <T> int partition(List<T> list, int begin, int end, Comparator<T> comparator) { T pivot = list.get(end); int i = (begin-1); for (int j = begin; j < end; j++) { if (comparator.compare(list.get(j), pivot) <= 0) {
i++; T swapTemp = list.get(i); list.set(i, list.get(j)); list.set(j, swapTemp); } } T swapTemp = list.get(i+1); list.set(i+1,list.get(end)); list.set(end, swapTemp); return i+1; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\collectionsvsarrays\sorting\Quicksort.java
1
请完成以下Java代码
public DbOperation addRemovalTimeToAuthorizationsByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(AuthorizationEntity.class, "updateAuthorizationsByRootProcessInstanceId", parameters); } public DbOperation addRemovalTimeToAuthorizationsByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(AuthorizationEntity.class,
"updateAuthorizationsByProcessInstanceId", parameters); } public DbOperation deleteAuthorizationsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(AuthorizationEntity.class, "deleteAuthorizationsByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationManager.java
1
请完成以下Java代码
public int getAD_Modification_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Modification_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_ValueNoCheck (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Version. @param Version Version of the table definition */ public void setVersion (String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ public String getVersion () { return (String)get_Value(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Modification.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDeployResources() { return deployResources; } public void setDeployResources(boolean deployResources) { this.deployResources = deployResources; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnableSafeXml() { return enableSafeXml; } public void setEnableSafeXml(boolean enableSafeXml) { this.enableSafeXml = enableSafeXml; } public boolean isEventRegistryStartCaseInstanceAsync() { return eventRegistryStartCaseInstanceAsync; } public void setEventRegistryStartCaseInstanceAsync(boolean eventRegistryStartCaseInstanceAsync) { this.eventRegistryStartCaseInstanceAsync = eventRegistryStartCaseInstanceAsync; } public boolean isEventRegistryUniqueCaseInstanceCheckWithLock() { return eventRegistryUniqueCaseInstanceCheckWithLock;
} public void setEventRegistryUniqueCaseInstanceCheckWithLock(boolean eventRegistryUniqueCaseInstanceCheckWithLock) { this.eventRegistryUniqueCaseInstanceCheckWithLock = eventRegistryUniqueCaseInstanceCheckWithLock; } public Duration getEventRegistryUniqueCaseInstanceStartLockTime() { return eventRegistryUniqueCaseInstanceStartLockTime; } public void setEventRegistryUniqueCaseInstanceStartLockTime(Duration eventRegistryUniqueCaseInstanceStartLockTime) { this.eventRegistryUniqueCaseInstanceStartLockTime = eventRegistryUniqueCaseInstanceStartLockTime; } public FlowableServlet getServlet() { return servlet; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\FlowableCmmnProperties.java
2
请完成以下Java代码
protected ExecutionEntity findNextParentScopeExecutionWithAllEndedChildExecutions( ExecutionEntity executionEntity, ExecutionEntity executionEntityToIgnore ) { if (executionEntity.getParentId() != null) { ExecutionEntity scopeExecutionEntity = executionEntity.getParent(); // Find next scope while (!scopeExecutionEntity.isScope() || !scopeExecutionEntity.isProcessInstanceType()) { scopeExecutionEntity = scopeExecutionEntity.getParent(); } // Return when all child executions for it are ended if (allChildExecutionsEnded(scopeExecutionEntity, executionEntityToIgnore)) { return scopeExecutionEntity; } } return null; } protected boolean allChildExecutionsEnded( ExecutionEntity parentExecutionEntity, ExecutionEntity executionEntityToIgnore ) { for (ExecutionEntity childExecutionEntity : parentExecutionEntity.getExecutions()) { if (
executionEntityToIgnore == null || !executionEntityToIgnore.getId().equals(childExecutionEntity.getId()) ) { if (!childExecutionEntity.isEnded()) { return false; } if (childExecutionEntity.getExecutions() != null && childExecutionEntity.getExecutions().size() > 0) { if (!allChildExecutionsEnded(childExecutionEntity, executionEntityToIgnore)) { return false; } } } } return true; } private void handleBoundaryEvent(FlowNode flowNode) { if (flowNode instanceof BoundaryEvent) { BoundaryEvent event = (BoundaryEvent) flowNode; final Activity activity = event.getAttachedToRef(); if (CollectionUtil.isNotEmpty(activity.getExecutionListeners())) { executeExecutionListeners(activity, ExecutionListener.EVENTNAME_END); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\TakeOutgoingSequenceFlowsOperation.java
1
请完成以下Java代码
public void deleteByCaseDefinitionId(String caseDefinitionId) { getDbSqlSession().delete("deleteHistoricPlanItemInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass()); } @Override public void bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(Collection<String> caseInstanceIds) { getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesByCaseInstanceIds", createSafeInValuesList(caseInstanceIds), getManagedEntityClass()); } @Override public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesForNonExistingCaseInstances", null, getManagedEntityClass()); } @Override @SuppressWarnings("unchecked") public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) { setSafeInValueLists(historicPlanItemInstanceQuery); return getDbSqlSession().selectList("selectHistoricPlanItemInstancesWithLocalVariablesByQueryCriteria", historicPlanItemInstanceQuery, getManagedEntityClass()); } @Override public Class<? extends HistoricPlanItemInstanceEntity> getManagedEntityClass() { return HistoricPlanItemInstanceEntityImpl.class; } @Override public HistoricPlanItemInstanceEntity create() { return new HistoricPlanItemInstanceEntityImpl();
} @Override public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) { return new HistoricPlanItemInstanceEntityImpl(planItemInstance); } protected void setSafeInValueLists(HistoricPlanItemInstanceQueryImpl planItemInstanceQuery) { if (planItemInstanceQuery.getInvolvedGroups() != null) { planItemInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(planItemInstanceQuery.getInvolvedGroups())); } if(planItemInstanceQuery.getCaseInstanceIds() != null) { planItemInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(planItemInstanceQuery.getCaseInstanceIds())); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricPlanItemInstanceDataManager.java
1
请完成以下Java代码
public class Person { int age; String name; String email; public Person(int age, String name, String email) { super(); this.age = age; this.name = name; this.email = email; } public int getAge() { return age; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Person [age="); builder.append(age); builder.append(", name="); builder.append(name); builder.append(", email="); builder.append(email);
builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; return true; } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\nullaway\Person.java
1
请完成以下Java代码
public class DbGroupQueryImpl extends GroupQueryImpl { private static final long serialVersionUID = 1L; public DbGroupQueryImpl() { super(); } public DbGroupQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } //results //////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) {
checkQueryOk(); DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext); return identityProvider.findGroupCountByQueryCriteria(this); } public List<Group> executeList(CommandContext commandContext, Page page) { checkQueryOk(); DbReadOnlyIdentityServiceProvider identityProvider = getIdentityProvider(commandContext); return identityProvider.findGroupByQueryCriteria(this); } protected DbReadOnlyIdentityServiceProvider getIdentityProvider(CommandContext commandContext) { return (DbReadOnlyIdentityServiceProvider) commandContext.getReadOnlyIdentityProvider(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbGroupQueryImpl.java
1
请完成以下Java代码
public boolean waitForLoad (Image image) { long start = System.currentTimeMillis(); Thread.yield(); int count = 0; try { Toolkit toolkit = Toolkit.getDefaultToolkit(); while (!toolkit.prepareImage(image, -1, -1, this)) // ImageObserver calls imageUpdate { // Timeout if (count > 1000) // about 20+ sec overall { log.error(this + " - Timeout - " + (System.currentTimeMillis()-start) + "ms - #" + count); return false; } try { if (count < 10) Thread.sleep(10); else if (count < 100) Thread.sleep(15); else Thread.sleep(20); } catch (InterruptedException ex) { log.error("", ex); break; } count++; } } catch (Exception e) // java.lang.SecurityException { log.error("", e); return false; } if (count > 0) log.debug((System.currentTimeMillis()-start) + "ms - #" + count); return true; } // waitForLoad /** * Get Detail Info from Sub-Class * @return detail info */
protected String getDetailInfo() { return ""; } // getDetailInfo /** * String Representation * @return info */ public String toString() { String cn = getClass().getName(); StringBuffer sb = new StringBuffer(); sb.append(cn.substring(cn.lastIndexOf('.')+1)).append("["); sb.append("Bounds=").append(getBounds()) .append(",Height=").append(p_height).append("(").append(p_maxHeight) .append("),Width=").append(p_width).append("(").append(p_maxHeight) .append("),PageLocation=").append(p_pageLocation); sb.append("]"); return sb.toString(); } // toString } // PrintElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\PrintElement.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Boolean getFailed() { return failed; } public void setFailed(Boolean failed) { this.failed = failed; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java
2
请完成以下Java代码
public final class DWZ { /** * Ajax请求成功,statusCode 为200. */ public static final String SUCCESS = "200"; /** * Ajax请求失败,statusCode 为300. */ public static final String ERROR = "300"; /** * Ajax请求超时,statusCode 为301. */ public static final String TIMEOUT = "301"; // ////////////////////////////////////////// /** * callbackType ajax请求回调类型. <br/> * callbackType如果是closeCurrent就会关闭当前tab选项, */ public static final String CLOSE = "closeCurrent";
/** * 只有callbackType="forward"时需要forwardUrl值,以重定向到另一个URL. */ public static final String FORWARD = "forward"; public static final String AJAX_DONE = "common/ajaxDone"; public static final String SUCCESS_MSG = "操作成功"; /** * 私有构造方法,单例模式. */ private DWZ() { } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\dwz\DWZ.java
1
请在Spring Boot框架中完成以下Java代码
public class Editor { @Id @GeneratedValue(generator = "uuid") @GenericGenerator(name = "uuid", strategy = "uuid2") private String editorId; private String editorName; @OneToMany(mappedBy = "editor", cascade = CascadeType.PERSIST) private Set<Author> assignedAuthors = new HashSet<>(); // constructors, getters and setters... Editor() { } public Editor(String editorName) { this.editorName = editorName; } public String getEditorId() { return editorId; } public void setEditorId(String editorId) { this.editorId = editorId; } public String getEditorName() {
return editorName; } public void setEditorName(String editorName) { this.editorName = editorName; } public Set<Author> getAssignedAuthors() { return assignedAuthors; } public void setAssignedAuthors(Set<Author> assignedAuthors) { this.assignedAuthors = assignedAuthors; } }
repos\tutorials-master\persistence-modules\hibernate-ogm\src\main\java\com\baeldung\hibernate\ogm\Editor.java
2
请在Spring Boot框架中完成以下Java代码
private void init() { NotificationTemplateConfig templateConfig = notificationTemplate.getConfiguration(); templateConfig.getDeliveryMethodsTemplates().forEach((deliveryMethod, template) -> { if (template.isEnabled()) { template = processTemplate(template, null); // processing template with immutable params templates.put(deliveryMethod, template); } }); } public <C extends NotificationDeliveryMethodConfig> C getDeliveryMethodConfig(NotificationDeliveryMethod deliveryMethod) { NotificationSettings settings; if (deliveryMethod == NotificationDeliveryMethod.MOBILE_APP) { settings = this.systemSettings; } else { settings = this.settings; } return (C) settings.getDeliveryMethodsConfigs().get(deliveryMethod); } public <T extends DeliveryMethodNotificationTemplate> T getProcessedTemplate(NotificationDeliveryMethod deliveryMethod, NotificationRecipient recipient) { T template = (T) templates.get(deliveryMethod); if (recipient != null) { Map<String, String> additionalTemplateContext = createTemplateContextForRecipient(recipient); if (template.getTemplatableValues().stream().anyMatch(value -> value.containsParams(additionalTemplateContext.keySet()))) { template = processTemplate(template, additionalTemplateContext); } } return template; } private <T extends DeliveryMethodNotificationTemplate> T processTemplate(T template, Map<String, String> additionalTemplateContext) { Map<String, String> templateContext = new HashMap<>(); if (request.getInfo() != null) { templateContext.putAll(request.getInfo().getTemplateData()); }
if (additionalTemplateContext != null) { templateContext.putAll(additionalTemplateContext); } if (templateContext.isEmpty()) return template; template = (T) template.copy(); template.getTemplatableValues().forEach(templatableValue -> { String value = templatableValue.get(); if (StringUtils.isNotEmpty(value)) { value = TemplateUtils.processTemplate(value, templateContext); templatableValue.set(value); } }); return template; } private Map<String, String> createTemplateContextForRecipient(NotificationRecipient recipient) { return Map.of( "recipientTitle", recipient.getTitle(), "recipientEmail", Strings.nullToEmpty(recipient.getEmail()), "recipientFirstName", Strings.nullToEmpty(recipient.getFirstName()), "recipientLastName", Strings.nullToEmpty(recipient.getLastName()) ); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\NotificationProcessingContext.java
2
请在Spring Boot框架中完成以下Java代码
public List<City> searchCity(Integer pageNumber, Integer pageSize, String searchContent) { // 校验分页参数 if (pageSize == null || pageSize <= 0) { pageSize = PAGE_SIZE; } if (pageNumber == null || pageNumber < DEFAULT_PAGE_NUMBER) { pageNumber = DEFAULT_PAGE_NUMBER; } LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n "); // 构建搜索查询 SearchQuery searchQuery = getCitySearchQuery(pageNumber,pageSize,searchContent); LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString()); Page<City> cityPage = cityRepository.search(searchQuery); return cityPage.getContent(); } /** * 根据搜索词构造搜索查询语句 * * 代码流程: * - 权重分查询 * - 短语匹配 * - 设置权重分最小值 * - 设置分页参数 * * @param pageNumber 当前页码 * @param pageSize 每页大小 * @param searchContent 搜索内容 * @return */
private SearchQuery getCitySearchQuery(Integer pageNumber, Integer pageSize,String searchContent) { // 短语匹配到的搜索词,求和模式累加权重分 // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html // - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html // - 字段对应权重分设置,可以优化成 enum // - 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.matchPhraseQuery("name", searchContent), ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.matchPhraseQuery("description", searchContent), ScoreFunctionBuilders.weightFactorFunction(500)) .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE); // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize); return new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); } }
repos\springboot-learning-example-master\spring-data-elasticsearch-query\src\main\java\org\spring\springboot\service\impl\CityESServiceImpl.java
2
请完成以下Spring Boot application配置
# Spring boot application spring.application.name=dubbo-spring-boot-servlet-container-provider-sample # Base packages to scan Dubbo Component: @org.apache.dubbo.config.annotation.Service dubbo.scan.base-packages=org.apache.dubbo.spring.boot.sample.provider.service # Dubbo Application # Dubbo Protocol dubbo.protoc
ol.name=dubbo dubbo.protocol.port=23456 ## Dubbo Registry dubbo.registry.address=N/A ## DemoService version demo.service.version=1.0.0
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\servlet-container-samples\provider-sample\src\main\resources\application.properties
2
请完成以下Java代码
public @Nullable String getGroup() { return get("group"); } /** * Return the artifactId of the project or {@code null}. * @return the artifact */ public @Nullable String getArtifact() { return get("artifact"); } /** * Return the name of the project or {@code null}. * @return the name */ public @Nullable String getName() { return get("name"); } /** * Return the version of the project or {@code null}. * @return the version */ public @Nullable String getVersion() { return get("version"); } /** * Return the timestamp of the build or {@code null}. * <p> * If the original value could not be parsed properly, it is still available with the * {@code time} key. * @return the build time * @see #get(String) */ public @Nullable Instant getTime() { return getInstant("time"); } private static Properties processEntries(Properties properties) { coerceDate(properties, "time");
return properties; } private static void coerceDate(Properties properties, String key) { String value = properties.getProperty(key); if (value != null) { try { String updatedValue = String .valueOf(DateTimeFormatter.ISO_INSTANT.parse(value, Instant::from).toEpochMilli()); properties.setProperty(key, updatedValue); } catch (DateTimeException ex) { // Ignore and store the original value } } } static class BuildPropertiesRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("META-INF/build-info.properties"); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\BuildProperties.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final BookMultipleIdsRepository bookMultipleIdsRepository; private final BookRepository bookRepository; public BookstoreService(BookMultipleIdsRepository bookMultipleIdsRepository, BookRepository bookRepository) { this.bookMultipleIdsRepository = bookMultipleIdsRepository; this.bookRepository = bookRepository; } public void fetchByMultipleIdsIn() { List<Book> books = bookRepository.fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books); } public void fetchByMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books); } public void fetchInBatchesByMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchInBatchesByMultipleIds(List.of(1L, 2L, 5L), 2); System.out.println(books); } @Transactional(readOnly = true)
public void fetchBySessionCheckMultipleIds() { List<Book> books1 = bookMultipleIdsRepository .fetchByMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books1); // loaded from Persistence Context List<Book> books2 = bookMultipleIdsRepository .fetchBySessionCheckMultipleIds(List.of(1L, 2L, 5L)); System.out.println(books2); } public void fetchInBatchesBySessionCheckMultipleIds() { List<Book> books = bookMultipleIdsRepository .fetchInBatchesBySessionCheckMultipleIds(List.of(1L, 2L, 3L), 2); System.out.println(books); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLoadMultipleIds\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
private static int deletePauseBeginEndRecordsAndUpdatePausedRecords(@NonNull final List<I_C_SubscriptionProgress> allPauseRecords) { int seqNoOffset = 0; for (final I_C_SubscriptionProgress pauseRecord : allPauseRecords) { final boolean pauseStartOrEnd = X_C_SubscriptionProgress.EVENTTYPE_BeginOfPause.equals(pauseRecord.getEventType()) || X_C_SubscriptionProgress.EVENTTYPE_EndOfPause.equals(pauseRecord.getEventType()); if (pauseStartOrEnd) { delete(pauseRecord); seqNoOffset++; continue; } else if (isWithinPause(pauseRecord)) { pauseRecord.setContractStatus(X_C_SubscriptionProgress.CONTRACTSTATUS_Running); if (pauseRecord.getM_ShipmentSchedule_ID() > 0)
{ Services.get(IShipmentScheduleBL.class).openShipmentSchedule(InterfaceWrapperHelper.load(pauseRecord.getM_ShipmentSchedule_ID(), I_M_ShipmentSchedule.class)); } } subtractFromSeqNoAndSave(pauseRecord, seqNoOffset); } return seqNoOffset; } private static void subtractFromSeqNoAndSave(final I_C_SubscriptionProgress record, final int seqNoOffset) { record.setSeqNo(record.getSeqNo() - seqNoOffset); // might be a not-within-pause-record if there are multiple pause periods between pausesFrom and pausesUntil save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\RemovePauses.java
1
请完成以下Java代码
public void unregister() { if (reg != null) { reg.unregister(); } } @SuppressWarnings({"rawtypes"}) @Override public ScriptEngine resolveScriptEngine(String name) { try { String className; try (InputStream input = configFile.openStream()) { className = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines() .map(line -> line.split("#", 2)[0].trim()) .filter(Predicate.not(String::isBlank)) .findFirst().orElse(null); } Class<?> cls = bundle.loadClass(className); if (!ScriptEngineFactory.class.isAssignableFrom(cls)) { throw new IllegalStateException("Invalid ScriptEngineFactory: " + cls.getName()); } ScriptEngineFactory factory = (ScriptEngineFactory) cls.getConstructor().newInstance(); List<String> names = factory.getNames(); for (String test : names) { if (test.equals(name)) { ClassLoader old = Thread.currentThread().getContextClassLoader(); ScriptEngine engine; try { // JRuby seems to require the correct TCCL to call
// getScriptEngine Thread.currentThread().setContextClassLoader(factory.getClass().getClassLoader()); engine = factory.getScriptEngine(); } finally { Thread.currentThread().setContextClassLoader(old); } LOGGER.trace("Resolved ScriptEngineFactory: {} for expected name: {}", engine, name); return engine; } } LOGGER.debug("ScriptEngineFactory: {} does not match expected name: {}", factory.getEngineName(), name); return null; } catch (Exception e) { LOGGER.warn("Cannot create ScriptEngineFactory: {}", e.getClass().getName(), e); return null; } } @Override public String toString() { return "OSGi script engine resolver for " + bundle.getSymbolicName(); } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\Extender.java
1
请完成以下Java代码
public void setGrade(Integer grade) { this.grade = grade; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; }
public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public DegradeRule toRule() { DegradeRule rule = new DegradeRule(); rule.setResource(resource); rule.setLimitApp(limitApp); rule.setCount(count); rule.setTimeWindow(timeWindow); rule.setGrade(grade); return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\DegradeRuleEntity.java
1
请完成以下Java代码
public class DatasourceManager { /** * 默认释放时间 */ private static final Long DEFAULT_RELEASE = 10L; /** * 数据源 */ @Getter private HikariDataSource dataSource; /** * 上一次使用时间 */ private LocalDateTime lastUseTime; public DatasourceManager(HikariDataSource dataSource) { this.dataSource = dataSource; this.lastUseTime = LocalDateTime.now(); } /**
* 是否已过期,如果过期则关闭数据源 * * @return 是否过期,{@code true} 过期,{@code false} 未过期 */ public boolean isExpired() { if (LocalDateTime.now().isBefore(this.lastUseTime.plusMinutes(DEFAULT_RELEASE))) { return false; } this.dataSource.close(); return true; } /** * 刷新上次使用时间 */ public void refreshTime() { this.lastUseTime = LocalDateTime.now(); } }
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\datasource\DatasourceManager.java
1
请完成以下Java代码
public final void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage workpackage) { this.workpackage = workpackage; } @NonNull protected final I_C_Queue_WorkPackage getC_Queue_WorkPackage() { Check.assumeNotNull(workpackage, "workpackage not null"); return this.workpackage; } @NonNull protected final QueueWorkPackageId getQueueWorkPackageId() { Check.assumeNotNull(workpackage, "workpackage not null"); return QueueWorkPackageId.ofRepoId(this.workpackage.getC_Queue_WorkPackage_ID()); } /** * @return <code>true</code>, i.e. ask the executor to run this processor in transaction (backward compatibility) */ @Override public boolean isRunInTransaction() { return true; } @Override public boolean isAllowRetryOnError() { return true; } @Override public final Optional<ILock> getElementsLock() { final String elementsLockOwnerName = getParameters().getParameterAsString(PARAMETERNAME_ElementsLockOwner); if (Check.isBlank(elementsLockOwnerName)) { return Optional.empty(); // no lock was created for this workpackage } final LockOwner elementsLockOwner = LockOwner.forOwnerName(elementsLockOwnerName); try { final ILock existingLockForOwner = Services.get(ILockManager.class).getExistingLockForOwner(elementsLockOwner); return Optional.of(existingLockForOwner); } catch (final LockFailedException e) { // this can happen, if e.g. there was a restart, or if the WP was flagged as error once Loggables.addLog("Missing lock for ownerName={}; was probably cleaned up meanwhile", elementsLockOwnerName); return Optional.empty(); }
} /** * Returns the {@link NullLatchStrategy}. */ @Override public ILatchStragegy getLatchStrategy() { return NullLatchStrategy.INSTANCE; } public final <T> List<T> retrieveItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType); } /** * Retrieves all active POs, even the ones that are caught in other packages */ public final <T> List<T> retrieveAllItems(final Class<T> modelType) { return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType); } public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems) { return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems); } /** * retrieves all active PO's IDs, even the ones that are caught in other packages */ public final Set<Integer> retrieveAllItemIds() { return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java
1
请完成以下Java代码
public Element setLang(String lang) { addAttribute("lang",lang); addAttribute("xml:lang",lang); return this; } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public bdo addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public bdo addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element.
*/ public bdo addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public bdo addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public bdo removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\bdo.java
1
请完成以下Java代码
public void setConnectionRequestTimeout(Duration connectionRequestTimeout) { setConnectionRequestTimeout(Math.toIntExact(connectionRequestTimeout.toMillis())); } public void setConnectTimeout(Duration connectTimeout) { setConnectTimeout(Math.toIntExact(connectTimeout.toMillis())); } public void setSocketTimeout(Duration socketTimeout) { setSocketTimeout(Math.toIntExact(socketTimeout.toMillis())); } public FlowableHttpClient getHttpClient() { return httpClient; } public void setHttpClient(FlowableHttpClient httpClient) { this.httpClient = httpClient; this.closeRunnable = null; } public FlowableHttpClient determineHttpClient() { if (httpClient != null) { return httpClient; } else if (isApacheHttpComponentsPresent) { // Backwards compatibility, if apache HTTP Components is present then it has priority this.httpClient = new ApacheHttpComponentsFlowableHttpClient(this); return this.httpClient; } else if (isSpringWebClientPresent && isReactorHttpClientPresent) { this.httpClient = new SpringWebClientFlowableHttpClient(this); return httpClient; } else if (isApacheHttpComponents5Present) { ApacheHttpComponents5FlowableHttpClient httpClient = new ApacheHttpComponents5FlowableHttpClient(this); this.httpClient = httpClient; this.closeRunnable = httpClient::close; return this.httpClient;
} else { throw new FlowableException("Failed to determine FlowableHttpClient"); } } public boolean isDefaultParallelInSameTransaction() { return defaultParallelInSameTransaction; } public void setDefaultParallelInSameTransaction(boolean defaultParallelInSameTransaction) { this.defaultParallelInSameTransaction = defaultParallelInSameTransaction; } public void close() { if (closeRunnable != null) { closeRunnable.run(); } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\HttpClientConfig.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableList<PickingJob> execute() { initialPickingJobs.forEach(PickingJob::assertNotProcessed); final boolean isAbortAllowed = initialPickingJobs.stream().allMatch(PickingJob::isAllowAbort); if (!isAbortAllowed) { throw new AdempiereException(ABORT_IS_NOT_ALLOWED); } return trxManager.callInThreadInheritedTrx(this::executeInTrx); } private ImmutableList<PickingJob> executeInTrx() { final ImmutableList.Builder<PickingJob> result = ImmutableList.builder(); for (final PickingJob initialPickingJob : initialPickingJobs) { final PickingJob pickingJob = execute(initialPickingJob); result.add(pickingJob); } return result.build(); } private PickingJob execute(@NonNull final PickingJob initialPickingJob) { //noinspection OptionalGetWithoutIsPresent return Stream.of(initialPickingJob) .sequential() .map(this::releasePickingSlotAndSave) // NOTE: abort is not "reversing", so we don't have to reverse (unpick) what we picked. // Even more, imagine that those picked things are already phisically splitted out. //.map(this::unpickAllStepsAndSave) .peek(huService::releaseAllReservations) .peek(pickingJobLockService::unlockSchedules) .map(this::markAsVoidedAndSave) .findFirst() .get(); } private PickingJob markAsVoidedAndSave(PickingJob pickingJob) { pickingJob = pickingJob.withDocStatus(PickingJobDocStatus.Voided); pickingJobRepository.save(pickingJob); return pickingJob; } // private PickingJob unpickAllStepsAndSave(final PickingJob pickingJob) // { // return PickingJobUnPickCommand.builder()
// .pickingJobRepository(pickingJobRepository) // .pickingCandidateService(pickingCandidateService) // .pickingJob(pickingJob) // .build() // .execute(); // } private PickingJob releasePickingSlotAndSave(PickingJob pickingJob) { final PickingJobId pickingJobId = pickingJob.getId(); final PickingSlotId pickingSlotId = pickingJob.getPickingSlotId().orElse(null); if (pickingSlotId != null) { pickingJob = pickingJob.withPickingSlot(null); pickingJobRepository.save(pickingJob); pickingSlotService.release(pickingSlotId, pickingJobId); } return pickingJob; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobAbortCommand.java
2
请在Spring Boot框架中完成以下Java代码
public de.metas.serviceprovider.model.I_S_Issue getS_Parent_Issue() { return get_ValueAsPO(COLUMNNAME_S_Parent_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class); } @Override public void setS_Parent_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Parent_Issue) { set_ValueFromPO(COLUMNNAME_S_Parent_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Parent_Issue); } @Override public void setS_Parent_Issue_ID (final int S_Parent_Issue_ID) { if (S_Parent_Issue_ID < 1) set_Value (COLUMNNAME_S_Parent_Issue_ID, null); else set_Value (COLUMNNAME_S_Parent_Issue_ID, S_Parent_Issue_ID); } @Override public int getS_Parent_Issue_ID() { return get_ValueAsInt(COLUMNNAME_S_Parent_Issue_ID); } /** * Status AD_Reference_ID=541142 * Reference name: S_Issue_Status */ public static final int STATUS_AD_Reference_ID=541142; /** In progress = InProgress */ public static final String STATUS_InProgress = "InProgress"; /** Closed = Closed */ public static final String STATUS_Closed = "Closed"; /** Pending = Pending */ public static final String STATUS_Pending = "Pending"; /** Delivered = Delivered */ public static final String STATUS_Delivered = "Delivered"; /** New = New */ public static final String STATUS_New = "New"; /** Invoiced = Invoiced */ public static final String STATUS_Invoiced = "Invoiced"; @Override public void setStatus (final java.lang.String Status) {
set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } @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.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_Issue.java
2
请完成以下Java代码
protected Authentication createAuthentication(HttpServletRequest request) { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(this.key, this.principal, this.authorities); token.setDetails(this.authenticationDetailsSource.buildDetails(request)); return token; } public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. *
* @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } public Object getPrincipal() { return this.principal; } public List<GrantedAuthority> getAuthorities() { return this.authorities; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AnonymousAuthenticationFilter.java
1
请完成以下Java代码
public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name", nullable = false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "email_address", nullable = false) public String getEmailId() { return emailId;
} public void setEmailId(String emailId) { this.emailId = emailId; } @Column(name = "create_at", nullable = false) @CreatedDate public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringMySQL\src\main\java\spring\restapi\model\Developer.java
1
请在Spring Boot框架中完成以下Java代码
protected final List<String> filter(@Nullable Collection<String> classNames, ClassNameFilter classNameFilter, @Nullable ClassLoader classLoader) { if (CollectionUtils.isEmpty(classNames)) { return Collections.emptyList(); } List<String> matches = new ArrayList<>(classNames.size()); for (String candidate : classNames) { if (classNameFilter.matches(candidate, classLoader)) { matches.add(candidate); } } return matches; } /** * Slightly faster variant of {@link ClassUtils#forName(String, ClassLoader)} that * doesn't deal with primitives, arrays or inner types. * @param className the class name to resolve * @param classLoader the class loader to use * @return a resolved class * @throws ClassNotFoundException if the class cannot be found */ protected static Class<?> resolve(String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException { if (classLoader != null) { return Class.forName(className, false, classLoader); } return Class.forName(className); } protected enum ClassNameFilter { PRESENT {
@Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return isPresent(className, classLoader); } }, MISSING { @Override public boolean matches(String className, @Nullable ClassLoader classLoader) { return !isPresent(className, classLoader); } }; abstract boolean matches(String className, @Nullable ClassLoader classLoader); private static boolean isPresent(String className, @Nullable ClassLoader classLoader) { if (classLoader == null) { classLoader = ClassUtils.getDefaultClassLoader(); } try { resolve(className, classLoader); return true; } catch (Throwable ex) { return false; } } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\FilteringSpringBootCondition.java
2
请完成以下Java代码
protected void paintTabBorder(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { g.translate(x - 4, y); int top = 0; int right = w + 6; // Paint Border g.setColor(selectHighlight); // Paint left g.drawLine(1, h - 1, 4, top + 4); g.fillRect(5, top + 2, 1, 2); g.fillRect(6, top + 1, 1, 1); // Paint top g.fillRect(7, top, right - 12, 1); // Paint right g.setColor(darkShadow); g.drawLine(right, h - 1, right - 3, top + 4); g.fillRect(right - 4, top + 2, 1, 2); g.fillRect(right - 5, top + 1, 1, 1); g.translate(-x + 4, -y); } @Override protected void paintContentBorderTopEdge( Graphics g, int x, int y, int w, int h, boolean drawBroken, Rectangle selRect, boolean isContentBorderPainted) { int right = x + w - 1; int top = y; g.setColor(selectHighlight); if (drawBroken && selRect.x >= x && selRect.x <= x + w) {
// Break line to show visual connection to selected tab g.fillRect(x, top, selRect.x - 2 - x, 1); if (selRect.x + selRect.width < x + w - 2) { g.fillRect(selRect.x + selRect.width + 2, top, right - 2 - selRect.x - selRect.width, 1); } else { g.fillRect(x + w - 2, top, 1, 1); } } else { g.fillRect(x, top, w - 1, 1); } } @Override protected int getTabsOverlay() { return 6; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTabbedPaneUI.java
1
请完成以下Java代码
public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Print Text. @param PrintName The label text to be printed on a document or correspondence. */ public void setPrintName (String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } /** Get Print Text. @return The label text to be printed on a document or correspondence. */ public String getPrintName () { return (String)get_Value(COLUMNNAME_PrintName); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } /** Set X Position. @param XPosition Absolute X (horizontal) position in 1/72 of an inch */ public void setXPosition (int XPosition) { set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition)); }
/** Get X Position. @return Absolute X (horizontal) position in 1/72 of an inch */ public int getXPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_XPosition); if (ii == null) return 0; return ii.intValue(); } /** Set Y Position. @param YPosition Absolute Y (vertical) position in 1/72 of an inch */ public void setYPosition (int YPosition) { set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition)); } /** Get Y Position. @return Absolute Y (vertical) position in 1/72 of an inch */ public int getYPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_YPosition); 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_AD_PrintLabelLine.java
1
请完成以下Java代码
public String webGet(@CliOption(key = { "", "url" }, help = "URL whose contents will be displayed.") URL url) { return getContentsOfUrlAsString(url); } @CliCommand(value = { "web-save", "ws" }, help = "Saves the contents of a URL.") public String webSave(@CliOption(key = { "", "url" }, help = "URL whose contents will be saved.") URL url, @CliOption(key = { "out", "file" }, mandatory = true, help = "The name of the file.") String file) { String contents = getContentsOfUrlAsString(url); try (PrintWriter out = new PrintWriter(file)) { out.write(contents); } catch (FileNotFoundException ex) { // Ignore } return "Done."; } private boolean adminEnableExecuted = false; @CliAvailabilityIndicator(value = { "web-save" }) public boolean isAdminEnabled() {
return adminEnableExecuted; } @CliCommand(value = "admin-enable") public String adminEnable() { adminEnableExecuted = true; return "Admin commands enabled."; } @CliCommand(value = "admin-disable") public String adminDisable() { adminEnableExecuted = false; return "Admin commands disabled."; } }
repos\tutorials-master\spring-shell\src\main\java\com\baeldung\shell\simple\SimpleCLI.java
1
请完成以下Java代码
protected void notifyExecutionListener(DelegateExecution execution) throws Exception { ProcessApplicationReference processApp = Context.getCurrentProcessApplication(); try { ProcessApplicationInterface processApplication = processApp.getProcessApplication(); ExecutionListener executionListener = processApplication.getExecutionListener(); if(executionListener != null) { executionListener.notify(execution); } else { LOG.paDoesNotProvideExecutionListener(processApp.getName()); } } catch (ProcessApplicationUnavailableException e) { // Process Application unavailable => ignore silently LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e); } } protected void notifyTaskListener(DelegateTask task) throws Exception { ProcessApplicationReference processApp = Context.getCurrentProcessApplication();
try { ProcessApplicationInterface processApplication = processApp.getProcessApplication(); TaskListener taskListener = processApplication.getTaskListener(); if(taskListener != null) { taskListener.notify(task); } else { LOG.paDoesNotProvideTaskListener(processApp.getName()); } } catch (ProcessApplicationUnavailableException e) { // Process Application unavailable => ignore silently LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventListenerDelegate.java
1
请完成以下Java代码
public String getColumnSQL () { return (String)get_Value(COLUMNNAME_ColumnSQL); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo)
{ set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); 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_AD_Index_Column.java
1
请完成以下Java代码
public void setPointsBase_Forecasted (final BigDecimal PointsBase_Forecasted) { set_Value (COLUMNNAME_PointsBase_Forecasted, PointsBase_Forecasted); } @Override public BigDecimal getPointsBase_Forecasted() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Forecasted); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiceable (final BigDecimal PointsBase_Invoiceable) { set_Value (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable); } @Override public BigDecimal getPointsBase_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced) { set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); }
@Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java
1
请完成以下Java代码
public static BooleanWithReason falseBecause(@NonNull final String reason) { return falseBecause(toTrl(reason)); } public static BooleanWithReason falseBecause(@NonNull final ITranslatableString reason) { if (TranslatableStrings.isBlank(reason)) { return FALSE; } else { return new BooleanWithReason(false, reason); } } public static BooleanWithReason falseBecause(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return falseBecause(TranslatableStrings.adMessage(adMessage, msgParameters)); } public static BooleanWithReason falseBecause(@NonNull final Exception exception) { return falseBecause(AdempiereException.extractMessageTrl(exception)); } public static BooleanWithReason falseIf(final boolean condition, @NonNull final String falseReason) { return condition ? falseBecause(falseReason) : TRUE; } private static ITranslatableString toTrl(@Nullable final String reasonStr) { if (reasonStr == null || Check.isBlank(reasonStr)) { return TranslatableStrings.empty(); } else { return TranslatableStrings.anyLanguage(reasonStr.trim()); } } public static final BooleanWithReason TRUE = new BooleanWithReason(true, TranslatableStrings.empty()); public static final BooleanWithReason FALSE = new BooleanWithReason(false, TranslatableStrings.empty()); private final boolean value; @NonNull @Getter private final ITranslatableString reason; private BooleanWithReason( final boolean value, @NonNull final ITranslatableString reason) { this.value = value; this.reason = reason; } @Override public String toString() { final String valueStr = String.valueOf(value); final String reasonStr = !TranslatableStrings.isBlank(reason) ? reason.getDefaultValue() : null; return reasonStr != null ? valueStr + " because " + reasonStr : valueStr; }
public boolean toBoolean() { return value; } public boolean isTrue() { return value; } public boolean isFalse() { return !value; } public String getReasonAsString() { return reason.getDefaultValue(); } public void assertTrue() { if (isFalse()) { throw new AdempiereException(reason); } } public BooleanWithReason and(@NonNull final Supplier<BooleanWithReason> otherSupplier) { return isFalse() ? this : Check.assumeNotNull(otherSupplier.get(), "otherSupplier shall not return null"); } public void ifTrue(@NonNull final Consumer<String> consumer) { if (isTrue()) { consumer.accept(getReasonAsString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\BooleanWithReason.java
1
请完成以下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 getSocialSecurityCode() {
return socialSecurityCode; } public void setSocialSecurityCode(String socialSecurityCode) { this.socialSecurityCode = socialSecurityCode; } @Override public String toString() { final StringBuffer sb = new StringBuffer("CustomerDTO{"); sb.append("firstName='").append(firstName).append('\''); sb.append(", lastName='").append(lastName).append('\''); sb.append(", socialSecurityCode='").append(socialSecurityCode).append('\''); sb.append('}'); return sb.toString(); } }
repos\springboot-demo-master\rmi\rmi-common\src\main\java\om\et\rmi\common\CustomerDTO.java
1
请完成以下Java代码
public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java
1
请完成以下Java代码
public SignalEventDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new SignalEventDefinitionImpl(instanceContext); } }); signalRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SIGNAL_REF) .qNameAttributeReference(Signal.class) .build(); /** Camunda Attributes */ camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC) .namespace(CAMUNDA_NS) .defaultValue(false) .build(); typeBuilder.build(); } public SignalEventDefinitionImpl(ModelTypeInstanceContext context) { super(context);
} public Signal getSignal() { return signalRefAttribute.getReferenceTargetElement(this); } public void setSignal(Signal signal) { signalRefAttribute.setReferenceTargetElement(this, signal); } public boolean isCamundaAsync() { return camundaAsyncAttribute.getValue(this); } public void setCamundaAsync(boolean camundaAsync) { camundaAsyncAttribute.setValue(this, camundaAsync); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SignalEventDefinitionImpl.java
1
请完成以下Java代码
private boolean isValidASI(final KeyNamePair asi) { if (asi == null) { return false; } if (asi.getKey() <= 0) { return false; } return true; } @Override public List<String> getDependsOnColumnNames() { return Collections.emptyList(); } @Override public Set<String> getValuePropagationKeyColumnNames(final Info_Column infoColumn) { return Collections.singleton(InfoProductQtyController.COLUMNNAME_M_Product_ID); } @Override public Object gridConvertAfterLoad(final Info_Column infoColumn, final int rowIndexModel, final int rowRecordId, final Object data) { return data; } @Override public int getParameterCount() { return 0; } @Override public String getLabel(final int index) { return null; } @Override public Object getParameterComponent(final int index) { return null; } @Override public Object getParameterToComponent(final int index) { return null; } @Override public Object getParameterValue(final int index, final boolean returnValueTo) { return null;
} @Override public String[] getWhereClauses(final List<Object> params) { return new String[0]; } @Override public String getText() { return null; } @Override public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders) { for (final Map.Entry<Integer, Integer> e : recordId2asi.entrySet()) { final Integer recordId = e.getKey(); if (recordId == null || recordId <= 0) { continue; } final Integer asiId = e.getValue(); if (asiId == null || asiId <= 0) { continue; } final OrderLineProductASIGridRowBuilder productQtyBuilder = new OrderLineProductASIGridRowBuilder(); productQtyBuilder.setSource(recordId, asiId); builders.addGridTabRowBuilder(recordId, productQtyBuilder); } } @Override public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel) { final VPAttributeContext attributeContext = new VPAttributeContext(rowIndexModel); editor.putClientProperty(IVPAttributeContext.ATTR_NAME, attributeContext); // nothing } @Override public String getProductCombinations() { // nothing to do return null; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductASIController.java
1
请在Spring Boot框架中完成以下Java代码
public JwtResponse fixedBuilder() throws UnsupportedEncodingException { String jws = Jwts.builder() .setIssuer("Stormpath") .setSubject("msilverman") .claim("name", "Micah Silverman") .claim("scope", "admins") .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); } @RequestMapping(value = "/parser", method = GET) public JwtResponse parser(@RequestParam String jwt) throws UnsupportedEncodingException { Jws<Claims> jws = Jwts.parser() .setSigningKeyResolver(secretService.getSigningKeyResolver()).build()
.parseClaimsJws(jwt); return new JwtResponse(jws); } @RequestMapping(value = "/parser-enforce", method = GET) public JwtResponse parserEnforce(@RequestParam String jwt) throws UnsupportedEncodingException { Jws<Claims> jws = Jwts.parser() .requireIssuer("Stormpath") .require("hasMotorcycle", true) .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(jwt); return new JwtResponse(jws); } }
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\controller\StaticJWTController.java
2
请在Spring Boot框架中完成以下Java代码
public final class JndiConnectionFactoryAutoConfiguration { // Keep these in sync with the condition below private static final String[] JNDI_LOCATIONS = { "java:/JmsXA", "java:/XAConnectionFactory" }; @Bean ConnectionFactory jmsConnectionFactory(JmsProperties properties) throws NamingException { JndiLocatorDelegate jndiLocatorDelegate = JndiLocatorDelegate.createDefaultResourceRefLocator(); if (StringUtils.hasLength(properties.getJndiName())) { return jndiLocatorDelegate.lookup(properties.getJndiName(), ConnectionFactory.class); } return findJndiConnectionFactory(jndiLocatorDelegate); } private ConnectionFactory findJndiConnectionFactory(JndiLocatorDelegate jndiLocatorDelegate) { for (String name : JNDI_LOCATIONS) { try { return jndiLocatorDelegate.lookup(name, ConnectionFactory.class); } catch (NamingException ex) { // Swallow and continue } } throw new IllegalStateException( "Unable to find ConnectionFactory in JNDI locations " + Arrays.asList(JNDI_LOCATIONS)); } /** * Condition for JNDI name or a specific property. */ static class JndiOrPropertyCondition extends AnyNestedCondition { JndiOrPropertyCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION);
} @ConditionalOnJndi({ "java:/JmsXA", "java:/XAConnectionFactory" }) static class Jndi { } @ConditionalOnProperty("spring.jms.jndi-name") static class Property { } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JndiConnectionFactoryAutoConfiguration.java
2
请完成以下Java代码
private static Map<String, Object> extractParameters(@NonNull final Throwable throwable, @NonNull final String adLanguage) { return convertParametersMapToJson(AdempiereException.extractParameters(throwable), adLanguage); } @NonNull public static Map<String, Object> convertParametersMapToJson(@Nullable final Map<?, Object> map, @NonNull final String adLanguage) { if (map == null || map.isEmpty()) { return ImmutableMap.of(); } return map .entrySet() .stream() .map(e -> GuavaCollectors.entry( convertParameterToStringJson(e.getKey(), adLanguage), convertParameterToJson(e.getValue(), adLanguage))) .collect(GuavaCollectors.toImmutableMap()); } @NonNull private static Object convertParameterToJson(@Nullable final Object value, @NonNull final String adLanguage) { if (value == null || Null.isNull(value)) { return "<null>"; } else if (value instanceof ITranslatableString) { return ((ITranslatableString)value).translate(adLanguage); } else if (value instanceof RepoIdAware) { return String.valueOf(((RepoIdAware)value).getRepoId()); } else if (value instanceof ReferenceListAwareEnum) { return ((ReferenceListAwareEnum)value).getCode(); } else if (value instanceof Collection) { //noinspection unchecked final Collection<Object> collection = (Collection<Object>)value; return collection.stream() .map(item -> convertParameterToJson(item, adLanguage)) .collect(Collectors.toList()); } else if (value instanceof Map) { //noinspection unchecked final Map<Object, Object> map = (Map<Object, Object>)value;
return convertParametersMapToJson(map, adLanguage); } else { return value.toString(); // return JsonObjectMapperHolder.toJsonOrToString(value); } } @NonNull private static String convertParameterToStringJson(@Nullable final Object value, @NonNull final String adLanguage) { if (value == null || Null.isNull(value)) { return "<null>"; } else if (value instanceof ITranslatableString) { return ((ITranslatableString)value).translate(adLanguage); } else if (value instanceof RepoIdAware) { return String.valueOf(((RepoIdAware)value).getRepoId()); } else if (value instanceof ReferenceListAwareEnum) { return ((ReferenceListAwareEnum)value).getCode(); } else { return value.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\v2\JsonErrors.java
1
请完成以下Java代码
public class MResourceAssignment extends X_S_ResourceAssignment { /** * */ private static final long serialVersionUID = 3024759545660161137L; /** * Stnadard Constructor * @param ctx * @param S_ResourceAssignment_ID */ public MResourceAssignment (Properties ctx, int S_ResourceAssignment_ID, String trxName) { super (ctx, S_ResourceAssignment_ID, trxName); // Default values if (S_ResourceAssignment_ID == 0) { setAssignDateFrom(new Timestamp(System.currentTimeMillis())); setQty(new BigDecimal(1.0)); setName("."); setIsConfirmed(false); } } // MResourceAssignment /** * Load Contsructor * @param ctx context * @param rs result set */ public MResourceAssignment (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MResourceAssignment /** * After Save * @param newRecord new * @param success success * @return true */ @Override protected boolean afterSave (boolean newRecord, boolean success) { /* v_Description := :new.Name; IF (:new.Description IS NOT NULL AND LENGTH(:new.Description) > 0) THEN v_Description := v_Description || ' (' || :new.Description || ')'; END IF; -- Update Expense Line UPDATE S_TimeExpenseLine SET Description = v_Description, Qty = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR Qty <> :new.Qty);
-- Update Order Line UPDATE C_OrderLine SET Description = v_Description, QtyOrdered = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR QtyOrdered <> :new.Qty); -- Update Invoice Line UPDATE C_InvoiceLine SET Description = v_Description, QtyInvoiced = :new.Qty WHERE S_ResourceAssignment_ID = :new.S_ResourceAssignment_ID AND (Description <> v_Description OR QtyInvoiced <> :new.Qty); */ return success; } // afterSave /** * String Representation * @return string */ @Override public String toString() { StringBuffer sb = new StringBuffer ("MResourceAssignment[ID="); sb.append(get_ID()) .append(",S_Resource_ID=").append(getS_Resource_ID()) .append(",From=").append(getAssignDateFrom()) .append(",To=").append(getAssignDateTo()) .append(",Qty=").append(getQty()) .append("]"); return sb.toString(); } // toString /** * Before Delete * @return true if not confirmed */ @Override protected boolean beforeDelete () { // allow to delete, when not confirmed if (isConfirmed()) return false; return true; } // beforeDelete } // MResourceAssignment
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MResourceAssignment.java
1
请完成以下Java代码
public GenericEventListenerInstanceQuery caseDefinitionId(String caseDefinitionId) { innerQuery.caseDefinitionId(caseDefinitionId); return this; } @Override public GenericEventListenerInstanceQuery elementId(String elementId) { innerQuery.planItemInstanceElementId(elementId); return this; } @Override public GenericEventListenerInstanceQuery planItemDefinitionId(String planItemDefinitionId) { innerQuery.planItemDefinitionId(planItemDefinitionId); return this; } @Override public GenericEventListenerInstanceQuery name(String name) { innerQuery.planItemInstanceName(name); return this; } @Override public GenericEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public GenericEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public GenericEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public GenericEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public GenericEventListenerInstanceQuery asc() { innerQuery.asc(); return this; } @Override public GenericEventListenerInstanceQuery desc() {
innerQuery.desc(); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public GenericEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return innerQuery.count(); } @Override public GenericEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return GenericEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<GenericEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<GenericEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<GenericEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(GenericEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
public void setValuta(Date valuta) { this.valuta = valuta; } public String getBuchungsschluessel() { return buchungsschluessel; } public void setBuchungsschluessel(String buchungsschluessel) { this.buchungsschluessel = buchungsschluessel; } public String getReferenz() { return referenz; } public void setReferenz(String referenz) { this.referenz = referenz; } public String getBankReferenz() { return bankReferenz; } public void setBankReferenz(String bankReferenz) { this.bankReferenz = bankReferenz; } public BigDecimal getUrsprungsbetrag() { return ursprungsbetrag; } public void setUrsprungsbetrag(BigDecimal ursprungsbetrag) { this.ursprungsbetrag = ursprungsbetrag; } public String getUrsprungsbetragWaehrung() { return ursprungsbetragWaehrung; } public void setUrsprungsbetragWaehrung(String ursprungsbetragWaehrung) { this.ursprungsbetragWaehrung = ursprungsbetragWaehrung; } public BigDecimal getGebuehrenbetrag() { return gebuehrenbetrag; } public void setGebuehrenbetrag(BigDecimal gebuehrenbetrag) { this.gebuehrenbetrag = gebuehrenbetrag; } public String getGebuehrenbetragWaehrung() { return gebuehrenbetragWaehrung; } public void setGebuehrenbetragWaehrung(String gebuehrenbetragWaehrung) { this.gebuehrenbetragWaehrung = gebuehrenbetragWaehrung; } public String getMehrzweckfeld() { return mehrzweckfeld; } public void setMehrzweckfeld(String mehrzweckfeld) { this.mehrzweckfeld = mehrzweckfeld; } public BigInteger getGeschaeftsvorfallCode() { return geschaeftsvorfallCode; } public void setGeschaeftsvorfallCode(BigInteger geschaeftsvorfallCode) { this.geschaeftsvorfallCode = geschaeftsvorfallCode; } public String getBuchungstext() { return buchungstext; } public void setBuchungstext(String buchungstext) { this.buchungstext = buchungstext; } public String getPrimanotennummer() { return primanotennummer;
} public void setPrimanotennummer(String primanotennummer) { this.primanotennummer = primanotennummer; } public String getVerwendungszweck() { return verwendungszweck; } public void setVerwendungszweck(String verwendungszweck) { this.verwendungszweck = verwendungszweck; } public String getPartnerBlz() { return partnerBlz; } public void setPartnerBlz(String partnerBlz) { this.partnerBlz = partnerBlz; } public String getPartnerKtoNr() { return partnerKtoNr; } public void setPartnerKtoNr(String partnerKtoNr) { this.partnerKtoNr = partnerKtoNr; } public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } public String getTextschluessel() { return textschluessel; } public void setTextschluessel(String textschluessel) { this.textschluessel = textschluessel; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\BankstatementLine.java
1
请完成以下Java代码
public V remove(Object key) { throw new UnsupportedOperationException("双数组不支持删除"); } @Override public void putAll(Map<? extends String, ? extends V> m) { throw new UnsupportedOperationException("双数组不支持增量式插入"); } @Override public void clear() { throw new UnsupportedOperationException("双数组不支持"); } @Override public Set<String> keySet() {
throw new UnsupportedOperationException("双数组不支持"); } @Override public Collection<V> values() { return Arrays.asList(valueArray); } @Override public Set<Entry<String, V>> entrySet() { throw new UnsupportedOperationException("双数组不支持"); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DartMap.java
1
请完成以下Java代码
public class GenericEventListenerXmlConverter extends PlanItemDefinitionXmlConverter { @Override public boolean hasChildElements() { return true; } @Override public String getXMLElementName() { return CmmnXmlConstants.ELEMENT_GENERIC_EVENT_LISTENER; } @Override protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) { String listenerType = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_TYPE); if ("signal".equals(listenerType)) { SignalEventListener signalEventListener = new SignalEventListener(); signalEventListener.setSignalRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_SIGNAL_REF)); return convertCommonAttributes(xtr, signalEventListener); } else if ("variable".equals(listenerType)) { VariableEventListener variableEventListener = new VariableEventListener(); variableEventListener.setVariableName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_NAME)); variableEventListener.setVariableChangeType(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_VARIABLE_CHANGE_TYPE)); return convertCommonAttributes(xtr, variableEventListener); } else if ("intent".equals(listenerType)) {
IntentEventListener intentEventListener = new IntentEventListener(); return convertCommonAttributes(xtr, intentEventListener); } else if ("reactivate".equals(listenerType)) { ReactivateEventListener reactivateEventListener = new ReactivateEventListener(); return convertCommonAttributes(xtr, reactivateEventListener); } else { GenericEventListener genericEventListener = new GenericEventListener(); return convertCommonAttributes(xtr, genericEventListener); } } protected EventListener convertCommonAttributes(XMLStreamReader xtr, EventListener listener) { listener.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME)); listener.setAvailableConditionExpression(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_EVENT_LISTENER_AVAILABLE_CONDITION)); return listener; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\GenericEventListenerXmlConverter.java
1
请完成以下Java代码
public abstract class NeedsActiveTaskCmd<T> implements Command<T>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; public NeedsActiveTaskCmd(String taskId) { this.taskId = taskId; } @Override public T execute(CommandContext commandContext) { if (taskId == null) { throw new FlowableIllegalArgumentException("taskId is null"); } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("Cannot find task with id " + taskId, Task.class); }
if (task.isDeleted()) { throw new FlowableException(task + " is already deleted"); } if (task.isSuspended()) { throw new FlowableException(getSuspendedTaskExceptionPrefix() + " a suspended " + task); } return execute(commandContext, task); } /** * Subclasses must implement in this method their normal command logic. The provided task is ensured to be active. */ protected abstract T execute(CommandContext commandContext, TaskEntity task); /** * Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended. */ protected String getSuspendedTaskExceptionPrefix() { return "Cannot execute operation for"; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\NeedsActiveTaskCmd.java
1
请完成以下Java代码
protected void deleteChannelDefinitionsForDeployment(String deploymentId) { getChannelDefinitionEntityManager().deleteChannelDefinitionsByDeploymentId(deploymentId); } @Override public long findDeploymentCountByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentCountByQueryCriteria(deploymentQuery); } @Override public List<EventDeployment> findDeploymentsByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) { return dataManager.findDeploymentsByQueryCriteria(deploymentQuery); } @Override public List<String> getDeploymentResourceNames(String deploymentId) { return dataManager.getDeploymentResourceNames(deploymentId); } @Override public List<EventDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentsByNativeQuery(parameterMap); } @Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findDeploymentCountByNativeQuery(parameterMap); } protected EventResourceEntityManager getResourceEntityManager() { return engineConfiguration.getResourceEntityManager(); } protected EventDefinitionEntityManager getEventDefinitionEntityManager() { return engineConfiguration.getEventDefinitionEntityManager(); } protected ChannelDefinitionEntityManager getChannelDefinitionEntityManager() { return engineConfiguration.getChannelDefinitionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityManagerImpl.java
1
请完成以下Java代码
public void checkType(Object value) throws AdaptorException { if (value != null && !clazz.isAssignableFrom(value.getClass())) { String msgError = "Failed type check - " + clazz + " != " + ((value != null) ? value.getClass().toString() : "null"); log.debug(msgError); throw new AdaptorException(msgError); } } /** * Returns an integer representation of the data type. * * @return an integer representation of the data type. */ public int toIntValue() { return this.intValue; } /** * Converts the integer representation of the data type into a {@link MetricDataType} instance. * * @param i the integer representation of the data type. * @return a {@link MetricDataType} instance. */ public static MetricDataType fromInteger(int i) { switch (i) { case 1: return Int8; case 2: return Int16; case 3: return Int32; case 4: return Int64; case 5: return UInt8; case 6: return UInt16; case 7: return UInt32; case 8: return UInt64; case 9: return Float; case 10: return Double; case 11: return Boolean; case 12: return String; case 13: return DateTime; case 14: return Text; case 15: return UUID; case 16: return DataSet; case 17: return Bytes; case 18: return File; case 19: return Template; case 20: return PropertySet; case 21: return PropertySetList; case 22: return Int8Array; case 23: return Int16Array;
case 24: return Int32Array; case 25: return Int64Array; case 26: return UInt8Array; case 27: return UInt16Array; case 28: return UInt32Array; case 29: return UInt64Array; case 30: return FloatArray; case 31: return DoubleArray; case 32: return BooleanArray; case 33: return StringArray; case 34: return DateTimeArray; default: return Unknown; } } /** * @return the class type for this DataType */ public Class<?> getClazz() { return clazz; } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\MetricDataType.java
1
请完成以下Java代码
public class QualityBasedInvoicingBL implements IQualityBasedInvoicingBL { @Override public boolean isQualityInspection(final I_PP_Order ppOrder) { final IMaterialTrackingPPOrderBL materialTrackingPPOrderBL = Services.get(IMaterialTrackingPPOrderBL.class); return materialTrackingPPOrderBL.isQualityInspection(ppOrder); } @Override public void assumeQualityInspectionOrder(final I_PP_Order ppOrder) { Check.assumeNotNull(ppOrder, "ppOrder not null"); Check.assume(isQualityInspection(ppOrder), "Order shall be a quality inspection order: {}", ppOrder); } @Override public IInvoicingItem createPlainInvoicingItem(final I_M_Product product, final BigDecimal qty, final I_C_UOM uom) { return new InvoicingItem(product, qty, uom); } @Override public BigDecimal calculateProjectedQty(final BigDecimal fullRawQty, final BigDecimal sampleRawQty, final BigDecimal sampleProducedQty, final I_C_UOM sampleProducedQtyUOM) {
final BigDecimal factor; if (sampleRawQty.signum() == 0) { factor = BigDecimal.ZERO; } else { factor = fullRawQty.divide(sampleRawQty, 12, RoundingMode.HALF_UP); } final BigDecimal projectedProducedQty = sampleProducedQty .multiply(factor) .setScale(sampleProducedQtyUOM.getStdPrecision(), RoundingMode.HALF_UP); return projectedProducedQty; } @Override public boolean isLastInspection(final IQualityInspectionOrder qiOrder) { return qiOrder.getInspectionNumber() == qiOrder.getQualityBasedConfig().getOverallNumberOfInvoicings(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityBasedInvoicingBL.java
1
请完成以下Java代码
default Class<String> getValueClass() { return String.class; } default boolean requiresParameter(final String parameterName) { return getParameterNames().contains(parameterName); } @Override default boolean isNoResult(final Object result) { return result == null || Util.same(result, EMPTY_RESULT); } @Override default boolean isNullExpression() { return false; } /** * Resolves all variables which available and returns a new string expression. * * @param ctx * @return string expression with all available variables resolved. * @throws ExpressionEvaluationException */ default IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException { final String expressionStr = evaluate(ctx, OnVariableNotFound.Preserve); return StringExpressionCompiler.instance.compile(expressionStr); }
/** * Turns this expression in an expression which caches it's evaluation results. * If this expression implements {@link ICachedStringExpression} it will be returned directly without any wrapping. * * @return cached expression */ default ICachedStringExpression caching() { return CachedStringExpression.wrapIfPossible(this); } /** * @return same as {@link #toString()} but the whole string representation will be on one line (new lines are stripped) */ default String toOneLineString() { return toString() .replace("\r", "") .replace("\n", ""); } default CompositeStringExpression.Builder toComposer() { return composer().append(this); } @Override String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IStringExpression.java
1
请完成以下Java代码
public class CoapTransportContext extends TransportContext { @Value("${transport.sessions.report_timeout}") private long sessionReportTimeout; @Getter @Value("${transport.coap.timeout}") private Long timeout; @Getter @Value("${transport.coap.piggyback_timeout}") private Long piggybackTimeout; @Getter @Value("${transport.coap.psm_activity_timer:10000}") private long psmActivityTimer; @Getter @Value("${transport.coap.paging_transmission_window:10000}")
private long pagingTransmissionWindow; @Autowired private JsonCoapAdaptor jsonCoapAdaptor; @Autowired private ProtoCoapAdaptor protoCoapAdaptor; @Autowired private EfentoCoapAdaptor efentoCoapAdaptor; @Autowired private CoapClientContext clientContext; private final ConcurrentMap<Integer, TransportProtos.ToDeviceRpcRequestMsg> rpcAwaitingAck = new ConcurrentHashMap<>(); }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\CoapTransportContext.java
1
请在Spring Boot框架中完成以下Java代码
public class GatewayRoutersConfig { /** * 路由配置方式:database,yml,nacos */ public String dataType; public String serverAddr; public String namespace; public String dataId; public String routeGroup; public String username; public String password; @Value("${jeecg.route.config.data-type:#{null}}") public void setDataType(String dataType) { this.dataType = dataType; } @Value("${jeecg.route.config.data-id:#{null}}") public void setRouteDataId(String dataId) { this.dataId = dataId + ".json"; } @Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP:#{null}}") public void setRouteGroup(String routeGroup) { this.routeGroup = routeGroup; } @Value("${spring.cloud.nacos.discovery.server-addr}") public void setServerAddr(String serverAddr) { this.serverAddr = serverAddr; } @Value("${spring.cloud.nacos.config.namespace:#{null}}") public void setNamespace(String namespace) { this.namespace = namespace; } @Value("${spring.cloud.nacos.config.username:#{null}}") public void setUsername(String username) { this.username = username; } @Value("${spring.cloud.nacos.config.password:#{null}}") public void setPassword(String password) { this.password = password; } public String getDataType() {
return dataType; } public String getServerAddr() { return serverAddr; } public String getNamespace() { return namespace; } public String getDataId() { return dataId; } public String getRouteGroup() { return routeGroup; } public String getUsername() { return username; } public String getPassword() { return password; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\config\GatewayRoutersConfig.java
2
请完成以下Java代码
public String getName() { return this.name; } @Override public String getContextualName(ExecutionRequestObservationContext context) { return BASE_CONTEXTUAL_NAME + operationType(context).getValue(); } @Override public KeyValues getLowCardinalityKeyValues(ExecutionRequestObservationContext context) { return KeyValues.of(outcome(context), operationType(context)); } protected KeyValue outcome(ExecutionRequestObservationContext context) { if (context.getError() != null || context.getExecutionResult() == null) { return OUTCOME_INTERNAL_ERROR; } else if (!context.getExecutionResult().getErrors().isEmpty()) { if (context.getExecutionResult().getErrors().stream().anyMatch((error) -> ErrorType.INTERNAL_ERROR.equals(error.getErrorType()))) { return OUTCOME_INTERNAL_ERROR; } return OUTCOME_REQUEST_ERROR; } return OUTCOME_SUCCESS; } protected KeyValue operationType(ExecutionRequestObservationContext context) { if (context.getExecutionContext() != null) { OperationDefinition.Operation operation = context.getExecutionContext().getOperationDefinition().getOperation();
return KeyValue.of(ExecutionRequestLowCardinalityKeyNames.OPERATION_TYPE, operation.name().toLowerCase(Locale.ROOT)); } return OPERATION_TYPE_DEFAULT; } @Override public KeyValues getHighCardinalityKeyValues(ExecutionRequestObservationContext context) { return KeyValues.of(executionId(context), operationName(context)); } protected KeyValue executionId(ExecutionRequestObservationContext context) { return KeyValue.of(ExecutionRequestHighCardinalityKeyNames.EXECUTION_ID, context.getExecutionInput().getExecutionIdNonNull().toString()); } protected KeyValue operationName(ExecutionRequestObservationContext context) { String operationName = context.getExecutionInput().getOperationName(); if (operationName != null) { return KeyValue.of(ExecutionRequestHighCardinalityKeyNames.OPERATION_NAME, operationName); } return OPERATION_NAME_QUERY; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DefaultExecutionRequestObservationConvention.java
1
请在Spring Boot框架中完成以下Java代码
public class MultitenantConfiguration { @Value("${defaultTenant}") private String defaultTenant; @Bean @ConfigurationProperties(prefix = "tenants") public DataSource dataSource() { File[] files = Paths.get("allTenants").toFile().listFiles(); Map<Object, Object> resolvedDataSources = new HashMap<>(); for (File propertyFile : files) { Properties tenantProperties = new Properties(); DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); try { tenantProperties.load(new FileInputStream(propertyFile)); String tenantId = tenantProperties.getProperty("name"); dataSourceBuilder.driverClassName(tenantProperties.getProperty("datasource.driver-class-name")); dataSourceBuilder.username(tenantProperties.getProperty("datasource.username"));
dataSourceBuilder.password(tenantProperties.getProperty("datasource.password")); dataSourceBuilder.url(tenantProperties.getProperty("datasource.url")); resolvedDataSources.put(tenantId, dataSourceBuilder.build()); } catch (IOException exp) { throw new RuntimeException("Problem in tenant datasource:" + exp); } } AbstractRoutingDataSource dataSource = new MultitenantDataSource(); dataSource.setDefaultTargetDataSource(resolvedDataSources.get(defaultTenant)); dataSource.setTargetDataSources(resolvedDataSources); dataSource.afterPropertiesSet(); return dataSource; } }
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\config\MultitenantConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class DocOutboundConfigId implements RepoIdAware { int repoId; public static DocOutboundConfigId ofRepoId(final int repoId) { return new DocOutboundConfigId(repoId); } @Nullable public static DocOutboundConfigId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new DocOutboundConfigId(repoId) : null; } @Nullable public static DocOutboundConfigId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new DocOutboundConfigId(repoId) : null; } public static Optional<DocOutboundConfigId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } @JsonCreator public static DocOutboundConfigId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, DocOutboundConfigId.class, DocOutboundConfigId::ofRepoId); } public static int toRepoId(@Nullable final DocOutboundConfigId docOutboundConfigId) { return toRepoIdOr(docOutboundConfigId, -1); } public static int toRepoIdOr(@Nullable final DocOutboundConfigId docOutboundConfigId, final int defaultValue) { return docOutboundConfigId != null ? docOutboundConfigId.getRepoId() : defaultValue;
} private DocOutboundConfigId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_Doc_Outbound_Config_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final DocOutboundConfigId o1, @Nullable final DocOutboundConfigId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigId.java
2
请完成以下Java代码
public List<DataSpec> getDataInputs() { return dataInputs; } public void setDataInputs(List<DataSpec> dataInputs) { this.dataInputs = dataInputs; } public List<DataSpec> getDataOutputs() { return dataOutputs; } public void setDataOutputs(List<DataSpec> dataOutputs) { this.dataOutputs = dataOutputs; } public List<String> getDataInputRefs() { return dataInputRefs; } public void setDataInputRefs(List<String> dataInputRefs) { this.dataInputRefs = dataInputRefs; } public List<String> getDataOutputRefs() { return dataOutputRefs; } public void setDataOutputRefs(List<String> dataOutputRefs) { this.dataOutputRefs = dataOutputRefs; }
public IOSpecification clone() { IOSpecification clone = new IOSpecification(); clone.setValues(this); return clone; } public void setValues(IOSpecification otherSpec) { dataInputs = new ArrayList<DataSpec>(); if (otherSpec.getDataInputs() != null && !otherSpec.getDataInputs().isEmpty()) { for (DataSpec dataSpec : otherSpec.getDataInputs()) { dataInputs.add(dataSpec.clone()); } } dataOutputs = new ArrayList<DataSpec>(); if (otherSpec.getDataOutputs() != null && !otherSpec.getDataOutputs().isEmpty()) { for (DataSpec dataSpec : otherSpec.getDataOutputs()) { dataOutputs.add(dataSpec.clone()); } } dataInputRefs = new ArrayList<String>(otherSpec.getDataInputRefs()); dataOutputRefs = new ArrayList<String>(otherSpec.getDataOutputRefs()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\IOSpecification.java
1
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setConfig (final java.lang.String Config) { set_Value (COLUMNNAME_Config, Config); } @Override public java.lang.String getConfig() { return get_ValueAsString(COLUMNNAME_Config); } @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 setS_GithubConfig_ID (final int S_GithubConfig_ID) { if (S_GithubConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_S_GithubConfig_ID, S_GithubConfig_ID); } @Override public int getS_GithubConfig_ID() { return get_ValueAsInt(COLUMNNAME_S_GithubConfig_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_GithubConfig.java
2
请完成以下Java代码
public static void main(String[] args) { /* String[] testCaseArray = { "我一直很喜欢你", "你被我喜欢", "美丽又善良的你被卑微的我深深的喜欢着……", "只有自信的程序员才能把握未来", "主干识别可以提高检索系统的智能", "这个项目的作者是hankcs", "hankcs是一个无门无派的浪人", "搜索hankcs可以找到我的博客", "静安区体育局2013年部门决算情况说明", "这类算法在有限的一段时间内终止", }; for (String testCase : testCaseArray) { MainPart mp = MainPartExtractor.getMainPart(testCase); System.out.printf("%s\t%s\n", testCase, mp); }*/ mpTest(); } public static void mpTest(){ String[] testCaseArray = { "我一直很喜欢你", "你被我喜欢", "美丽又善良的你被卑微的我深深的喜欢着……", "小米公司主要生产智能手机",
"他送给了我一份礼物", "这类算法在有限的一段时间内终止", "如果大海能够带走我的哀愁", "天青色等烟雨,而我在等你", "我昨天看见了一个非常可爱的小孩" }; for (String testCase : testCaseArray) { MainPart mp = MainPartExtractor.getMainPart(testCase); System.out.printf("%s %s %s \n", GraphUtil.getNodeValue(mp.getSubject()), GraphUtil.getNodeValue(mp.getPredicate()), GraphUtil.getNodeValue(mp.getObject())); } } }
repos\springboot-demo-master\neo4j\src\main\java\com\et\neo4j\hanlp\MainPartExtractor.java
1
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\pricing\model\X_C_PricingRule.java
1
请完成以下Java代码
public List<String> resolveAll(DataSource dataSource, String... values) { Assert.notNull(dataSource, "'dataSource' must not be null"); return resolveAll(() -> determinePlatform(dataSource), values); } /** * Resolves the placeholders in the given {@code values}, replacing them with the * given platform. * @param platform the platform to use * @param values the values in which placeholders are resolved * @return the values with their placeholders resolved * @since 2.6.2 */ public List<String> resolveAll(String platform, String... values) { Assert.notNull(platform, "'platform' must not be null"); return resolveAll(() -> platform, values); } private List<String> resolveAll(Supplier<String> platformProvider, String... values) { if (ObjectUtils.isEmpty(values)) { return Collections.emptyList(); } List<String> resolved = new ArrayList<>(values.length); String platform = null; for (String value : values) { if (StringUtils.hasLength(value)) { if (value.contains(this.placeholder)) { platform = (platform != null) ? platform : platformProvider.get(); value = value.replace(this.placeholder, platform); } } resolved.add(value); }
return Collections.unmodifiableList(resolved); } private String determinePlatform(DataSource dataSource) { DatabaseDriver databaseDriver = getDatabaseDriver(dataSource); Assert.state(databaseDriver != DatabaseDriver.UNKNOWN, "Unable to detect database type"); return this.driverMappings.getOrDefault(databaseDriver, databaseDriver.getId()); } DatabaseDriver getDatabaseDriver(DataSource dataSource) { try { String productName = JdbcUtils.commonDatabaseName( JdbcUtils.extractDatabaseMetaData(dataSource, DatabaseMetaData::getDatabaseProductName)); return DatabaseDriver.fromProductName(productName); } catch (Exception ex) { throw new IllegalStateException("Failed to determine DatabaseDriver", ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\PlatformPlaceholderDatabaseDriverResolver.java
1
请完成以下Java代码
public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public Integer getProductCommentCount() { return productCommentCount; } public void setProductCommentCount(Integer productCommentCount) { this.productCommentCount = productCommentCount; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getBigPic() { return bigPic; } public void setBigPic(String bigPic) {
this.bigPic = bigPic; } public String getBrandStory() { return brandStory; } public void setBrandStory(String brandStory) { this.brandStory = brandStory; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", firstLetter=").append(firstLetter); sb.append(", sort=").append(sort); sb.append(", factoryStatus=").append(factoryStatus); sb.append(", showStatus=").append(showStatus); sb.append(", productCount=").append(productCount); sb.append(", productCommentCount=").append(productCommentCount); sb.append(", logo=").append(logo); sb.append(", bigPic=").append(bigPic); sb.append(", brandStory=").append(brandStory); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java
1
请完成以下Java代码
public class PortMapperImpl implements PortMapper { private final Map<Integer, Integer> httpsPortMappings; public PortMapperImpl() { this.httpsPortMappings = new HashMap<>(); this.httpsPortMappings.put(80, 443); this.httpsPortMappings.put(8080, 8443); } /** * Returns the translated (Integer -&gt; Integer) version of the original port mapping * specified via setHttpsPortMapping() */ public Map<Integer, Integer> getTranslatedPortMappings() { return this.httpsPortMappings; } @Override public @Nullable Integer lookupHttpPort(Integer httpsPort) { for (Integer httpPort : this.httpsPortMappings.keySet()) { if (this.httpsPortMappings.get(httpPort).equals(httpsPort)) { return httpPort; } } return null; } @Override public @Nullable Integer lookupHttpsPort(Integer httpPort) { return this.httpsPortMappings.get(httpPort); } /** * Set to override the default HTTP port to HTTPS port mappings of 80:443, and * 8080:8443. In a Spring XML ApplicationContext, a definition would look something * like this: * * <pre> * &lt;property name="portMappings"&gt; * &lt;map&gt; * &lt;entry key="80"&gt;&lt;value&gt;443&lt;/value&gt;&lt;/entry&gt; * &lt;entry key="8080"&gt;&lt;value&gt;8443&lt;/value&gt;&lt;/entry&gt; * &lt;/map&gt; * &lt;/property&gt; * </pre> * @param newMappings A Map consisting of String keys and String values, where for * each entry the key is the string representation of an integer HTTP port number, and * the value is the string representation of the corresponding integer HTTPS port
* number. * @throws IllegalArgumentException if input map does not consist of String keys and * values, each representing an integer port number in the range 1-65535 for that * mapping. */ public void setPortMappings(Map<String, String> newMappings) { Assert.notNull(newMappings, "A valid list of HTTPS port mappings must be provided"); this.httpsPortMappings.clear(); for (Map.Entry<String, String> entry : newMappings.entrySet()) { Integer httpPort = Integer.valueOf(entry.getKey()); Integer httpsPort = Integer.valueOf(entry.getValue()); Assert.isTrue(isInPortRange(httpPort) && isInPortRange(httpsPort), () -> "one or both ports out of legal range: " + httpPort + ", " + httpsPort); this.httpsPortMappings.put(httpPort, httpsPort); } Assert.isTrue(!this.httpsPortMappings.isEmpty(), "must map at least one port"); } private boolean isInPortRange(int port) { return port >= 1 && port <= 65535; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\PortMapperImpl.java
1
请在Spring Boot框架中完成以下Java代码
static class OpaqueTokenIntrospectionClientConfiguration { @Bean @ConditionalOnProperty(name = "spring.security.oauth2.resourceserver.opaquetoken.introspection-uri") SpringReactiveOpaqueTokenIntrospector opaqueTokenIntrospector(OAuth2ResourceServerProperties properties) { OAuth2ResourceServerProperties.Opaquetoken opaquetoken = properties.getOpaquetoken(); String clientId = opaquetoken.getClientId(); Assert.state(clientId != null, "'clientId' must not be null"); String clientSecret = opaquetoken.getClientSecret(); Assert.state(clientSecret != null, "'clientSecret' must not be null"); return SpringReactiveOpaqueTokenIntrospector.withIntrospectionUri(opaquetoken.getIntrospectionUri()) .clientId(clientId) .clientSecret(clientSecret) .build(); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(SecurityWebFilterChain.class) static class WebSecurityConfiguration { @Bean @ConditionalOnBean(ReactiveOpaqueTokenIntrospector.class) SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated()); http.oauth2ResourceServer((resourceServer) -> resourceServer.opaqueToken(withDefaults())); return http.build(); } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\reactive\ReactiveOAuth2ResourceServerOpaqueTokenConfiguration.java
2
请完成以下Java代码
public String getQuestion() { return question; } public void setQuestion(String question) { this.question = question; } public String getAllowedAnswers() { return allowedAnswers; } public void setAllowedAnswers(String allowedAnswers) { this.allowedAnswers = allowedAnswers; } public InformationItem getVariable() { return variable; } public void setVariable(InformationItem variable) { this.variable = variable; } public List<InformationRequirement> getRequiredDecisions() { return requiredDecisions; } public void setRequiredDecisions(List<InformationRequirement> requiredDecisions) { this.requiredDecisions = requiredDecisions; } public void addRequiredDecision(InformationRequirement requiredDecision) { this.requiredDecisions.add(requiredDecision); } public List<InformationRequirement> getRequiredInputs() { return requiredInputs; } public void setRequiredInputs(List<InformationRequirement> requiredInputs) { this.requiredInputs = requiredInputs; } public void addRequiredInput(InformationRequirement requiredInput) { this.requiredInputs.add(requiredInput); } public List<AuthorityRequirement> getAuthorityRequirements() { return authorityRequirements; }
public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) { this.authorityRequirements = authorityRequirements; } public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) { this.authorityRequirements.add(authorityRequirement); } public Expression getExpression() { return expression; } public void setExpression(Expression expression) { this.expression = expression; } public boolean isForceDMN11() { return forceDMN11; } public void setForceDMN11(boolean forceDMN11) { this.forceDMN11 = forceDMN11; } @JsonIgnore public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java
1
请在Spring Boot框架中完成以下Java代码
public class MscExecutorService implements Service<MscExecutorService>, ExecutorService { private static Logger log = Logger.getLogger(MscExecutorService.class.getName()); private final InjectedValue<ManagedQueueExecutorService> managedQueueInjector = new InjectedValue<ManagedQueueExecutorService>(); private long lastWarningLogged = System.currentTimeMillis(); public MscExecutorService getValue() throws IllegalStateException, IllegalArgumentException { return this; } public void start(StartContext context) throws StartException { // nothing to do } public void stop(StopContext context) { // nothing to do } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } public boolean schedule(Runnable runnable, boolean isLongRunning) { if(isLongRunning) { return scheduleLongRunningWork(runnable); } else { return scheduleShortRunningWork(runnable); } } protected boolean scheduleShortRunningWork(Runnable runnable) { ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); try { managedQueueExecutorService.executeBlocking(runnable); return true; } catch (InterruptedException e) { // the the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (Exception e) { // we must be able to schedule this log.log(Level.WARNING, "Cannot schedule long running work.", e); } return false; } protected boolean scheduleLongRunningWork(Runnable runnable) { final ManagedQueueExecutorService managedQueueExecutorService = managedQueueInjector.getValue(); boolean rejected = false; try {
// wait for 2 seconds for the job to be accepted by the pool. managedQueueExecutorService.executeBlocking(runnable, 2, TimeUnit.SECONDS); } catch (InterruptedException e) { // the acquisition thread is interrupted, this probably means the app server is turning the lights off -> ignore } catch (ExecutionTimedOutException e) { rejected = true; } catch (RejectedExecutionException e) { rejected = true; } catch (Exception e) { // if it fails for some other reason, log a warning message long now = System.currentTimeMillis(); // only log every 60 seconds to prevent log flooding if((now-lastWarningLogged) >= (60*1000)) { log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e); } else { log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e); } } return !rejected; } public InjectedValue<ManagedQueueExecutorService> getManagedQueueInjector() { return managedQueueInjector; } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
2
请完成以下Java代码
public class JsonBeanEncoder implements IBeanEnconder { private final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); @Override public <T> T decodeString(final String text, final Class<T> clazz) { try { return mapper.readValue(text, clazz); } catch (final Exception e) { throw new RuntimeException("Cannot parse text: " + text, e); } } @Override public <T> T decodeStream(final InputStream in, final Class<T> clazz) { if (in == null) { throw new IllegalArgumentException("'in' input stream is null"); } String str = null; try { str = IOStreamUtils.toString(in); return mapper.readValue(str, clazz); } catch (final Exception e) { throw new RuntimeException("Cannot parse input stream for class " + clazz + ": " + str, e); } } @Override public <T> T decodeBytes(final byte[] data, final Class<T> clazz) { try { return mapper.readValue(data, clazz);
} catch (final Exception e) { throw new RuntimeException("Cannot parse bytes: " + data, e); } } @Override public <T> byte[] encode(final T object) { try { return mapper.writeValueAsBytes(object); } catch (final Exception e) { throw new RuntimeException(e); } } @Override public String getContentType() { return "application/json"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\org\adempiere\util\beans\JsonBeanEncoder.java
1
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public void setC_Project_Repair_Consumption_Summary_ID (final int C_Project_Repair_Consumption_Summary_ID) { if (C_Project_Repair_Consumption_Summary_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_Repair_Consumption_Summary_ID, C_Project_Repair_Consumption_Summary_ID); } @Override public int getC_Project_Repair_Consumption_Summary_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Repair_Consumption_Summary_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_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); } @Override public void setQtyConsumed (final BigDecimal QtyConsumed) { set_Value (COLUMNNAME_QtyConsumed, QtyConsumed); } @Override public BigDecimal getQtyConsumed() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyConsumed); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyReserved (final BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Consumption_Summary.java
2
请完成以下Java代码
public RequestTypeId retrieveVendorRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_VendorComplaint); } @Override public RequestTypeId retrieveCustomerRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_CustomerComplaint); } @Override public RequestTypeId retrieveOrgChangeRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_OrgSwitch); } @Override public RequestTypeId retrieveBPartnerCreatedFromAnotherOrgRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_C_BPartner_CreatedFromAnotherOrg); } @Override public RequestTypeId retrieveRequestTypeIdByInternalName(final String internalName) { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_InternalName, internalName) .create() .firstIdOnly(RequestTypeId::ofRepoIdOrNull); // covered by unique index if (requestTypeId == null) { throw new AdempiereException("@NotFound@ @R_RequestType_ID@ (@InternalName@: " + internalName); } return requestTypeId; } @Override public RequestTypeId retrieveDefaultRequestTypeIdOrFirstActive() { return Optionals.firstPresentOfSuppliers( this::retrieveDefaultRequestTypeId, this::retrieveFirstActiveRequestTypeId) .orElseThrow(() -> new AdempiereException("@NotFound@ @R_RequestType_ID@").markAsUserValidationError()); } private Optional<RequestTypeId> retrieveDefaultRequestTypeId() {
final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_IsDefault, true) .create() .firstIdOnly(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } private Optional<RequestTypeId> retrieveFirstActiveRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .orderBy(I_R_RequestType.COLUMNNAME_R_RequestType_ID) .create() .firstId(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } @Override public I_R_RequestType getById(@NonNull final RequestTypeId requestTypeId) { return queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addEqualsFilter(I_R_RequestType.COLUMNNAME_R_RequestType_ID, requestTypeId) .create() .firstOnlyNotNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\api\impl\RequestTypeDAO.java
1
请在Spring Boot框架中完成以下Java代码
public Queue demo08Queue() { return QueueBuilder.durable(Demo08Message.QUEUE) // durable: 是否持久化 .exclusive() // exclusive: 是否排它 .autoDelete() // autoDelete: 是否自动删除 .ttl(10 * 1000) // 设置队列里的默认过期时间为 10 秒 .deadLetterExchange(Demo08Message.EXCHANGE) .deadLetterRoutingKey(Demo08Message.DELAY_ROUTING_KEY) .build(); } // 创建 Delay Queue @Bean public Queue demo08DelayQueue() { return new Queue(Demo08Message.DELAY_QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Direct Exchange @Bean public DirectExchange demo08Exchange() { return new DirectExchange(Demo08Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo08Message.EXCHANGE // Routing key:Demo08Message.ROUTING_KEY // Queue:Demo08Message.QUEUE @Bean public Binding demo08Binding() {
return BindingBuilder.bind(demo08Queue()).to(demo08Exchange()).with(Demo08Message.ROUTING_KEY); } // 创建 Delay Binding // Exchange:Demo08Message.EXCHANGE // Routing key:Demo08Message.DELAY_ROUTING_KEY // Queue:Demo08Message.DELAY_QUEUE @Bean public Binding demo08DelayBinding() { return BindingBuilder.bind(demo08DelayQueue()).to(demo08Exchange()).with(Demo08Message.DELAY_ROUTING_KEY); } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-delay\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class PPRoutingActivity { @NonNull PPRoutingActivityId id; @NonNull PPRoutingActivityType type; @NonNull String code; @NonNull String name; @NonNull @Default Range<Instant> validDates = Range.all(); @NonNull ResourceId resourceId; @NonNull WFDurationUnit durationUnit; @NonNull Duration queuingTime; @NonNull Duration setupTime; @NonNull Duration waitingTime; @NonNull Duration movingTime; @NonNull Duration durationPerOneUnit; int overlapUnits; /** * how many items can be manufactured on a production line in given duration unit. */ int unitsPerCycle; /** * how many units are produced in a batch */ @NonNull BigDecimal qtyPerBatch; /** * The Yield is the percentage of a lot that is expected to be of acceptable quality may fall below 100 percent */ @NonNull Percent yield; boolean subcontracting;
BPartnerId subcontractingVendorId; boolean milestone; @NonNull PPAlwaysAvailableToUser alwaysAvailableToUser; @Nullable UserInstructions userInstructions; @NonNull @Default ImmutableSet<PPRoutingActivityId> nextActivityIds = ImmutableSet.of(); @Nullable PPRoutingActivityTemplateId activityTemplateId; @Nullable RawMaterialsIssueStrategy rawMaterialsIssueStrategy; public boolean isValidAtDate(final Instant dateTime) { return validDates.contains(dateTime); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPRoutingActivity.java
2
请完成以下Java代码
public String getTitle() { return getTitle(email, firstName, lastName); } public static String getTitle(String email, String firstName, String lastName) { String title = ""; if (isNotEmpty(firstName)) { title += firstName; } if (isNotEmpty(lastName)) { if (!title.isEmpty()) { title += " "; } title += lastName; } if (title.isEmpty()) { title = email; } return title; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("User [tenantId="); builder.append(tenantId); builder.append(", customerId="); builder.append(customerId); builder.append(", email="); builder.append(email); builder.append(", authority="); builder.append(authority); builder.append(", firstName="); builder.append(firstName); builder.append(", lastName="); builder.append(lastName); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id=");
builder.append(id); builder.append("]"); return builder.toString(); } @JsonIgnore public boolean isSystemAdmin() { return tenantId == null || EntityId.NULL_UUID.equals(tenantId.getId()); } @JsonIgnore public boolean isTenantAdmin() { return !isSystemAdmin() && (customerId == null || EntityId.NULL_UUID.equals(customerId.getId())); } @JsonIgnore public boolean isCustomerUser() { return !isSystemAdmin() && !isTenantAdmin(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\User.java
1
请完成以下Java代码
public boolean isNumericKey() { return delegate.isNumericKey(); } @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return delegate.newContextForFetchingById(id); } @Override public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { return cache_retrieveLookupValueById.getOrLoad(evalCtx, () -> delegate.retrieveLookupValueById(evalCtx)); } @Override public LookupValuesList retrieveLookupValueByIdsInOrder(final @NonNull LookupDataSourceContext evalCtx) { cache_retrieveLookupValueById.getAllOrLoad( evalCtx.streamSingleIdContexts().collect(ImmutableSet.toImmutableSet()), singleIdCtxs -> { final LookupDataSourceContext multipleIdsCtx = LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs); return delegate.retrieveLookupValueByIdsInOrder(LookupDataSourceContext.mergeToMultipleIds(singleIdCtxs)) .getValues()
.stream() .collect(ImmutableMap.toImmutableMap( lookupValue -> multipleIdsCtx.withIdToFilter(IdsToFilter.ofSingleValue(lookupValue.getId())), lookupValue -> lookupValue)); } ); return LookupDataSourceFetcher.super.retrieveLookupValueByIdsInOrder(evalCtx); } @Override public Builder newContextForFetchingList() { return delegate.newContextForFetchingList(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { return cache_retrieveEntities.getOrLoad(evalCtx, delegate::retrieveEntities); } @Override public Optional<WindowId> getZoomIntoWindowId() { return delegate.getZoomIntoWindowId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\CachedLookupDataSourceFetcherAdapter.java
1
请完成以下Java代码
private ImmutableSet<HuId> resolveHuIdsByLocator(@NonNull final LocatorQRCode locatorQRCode, @NonNull final HUQRCodeAssignment targetQrCodeAssignment) { return handlingUnitsDAO.createHUQueryBuilder() .addOnlyHUIds(targetQrCodeAssignment.getHuIds()) .addOnlyInLocatorId(locatorQRCode.getLocatorId()) .setOnlyTopLevelHUs(false) .listIds(); } @NonNull private ImmutableSet<HuId> resolveHuIdsByParentHUQr(@NonNull final HUQRCode parentHUQrCode, @NonNull final HUQRCodeAssignment targetQrCodeAssignment) { final HUQRCodeAssignment parentQrCodeAssignment = huQRCodeService .getHUAssignmentByQRCode(parentHUQrCode) .orElseThrow(() -> new AdempiereException("No HU found for parent QR Code!") .appendParametersToMessage() .setParameter("parentHUQrCode", parentHUQrCode)); if (!parentQrCodeAssignment.isSingleHUAssigned()) { throw new AdempiereException("More than one HU assigned to parentHUQRCode!") .appendParametersToMessage() .setParameter("parentHUQrCode", parentHUQrCode) .setParameter("assignedHUs", parentQrCodeAssignment .getHuIds() .stream() .map(HuId::getRepoId) .map(String::valueOf) .collect(Collectors.joining(",", "[", "]"))); } return handlingUnitsDAO.retrieveIncludedHUs(parentQrCodeAssignment.getSingleHUId()) .stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .filter(targetQrCodeAssignment::isAssignedToHuId) .collect(ImmutableSet.toImmutableSet()); } @Nullable private String getEffectivePIName(@NonNull final I_M_HU hu) { return Optional.ofNullable(handlingUnitsBL.getEffectivePI(hu)) .map(I_M_HU_PI::getName) .orElse(null); }
@Nullable private String extractTopLevelParentHUIdValue(@NonNull final I_M_HU hu) { return Optional.ofNullable(handlingUnitsBL.getTopLevelParent(hu)) .map(I_M_HU::getM_HU_ID) .filter(parentHUId -> parentHUId != hu.getM_HU_ID()) .map(String::valueOf) .orElse(null); } private static @NonNull ResponseEntity<JsonGetSingleHUResponse> toBadRequestResponseEntity(final Exception e) { final String adLanguage = Env.getADLanguageOrBaseLanguage(); return ResponseEntity.badRequest() .body(JsonGetSingleHUResponse.builder() .error(JsonErrors.ofThrowable(e, adLanguage)) .multipleHUsFound(wereMultipleHUsFound(e)) .build()); } private static boolean wereMultipleHUsFound(final Exception e) { return Optional.of(e) .filter(error -> error instanceof AdempiereException) .map(error -> (AdempiereException)error) .map(adempiereEx -> adempiereEx.getParameter(MORE_THAN_ONE_HU_FOUND_ERROR_PARAM_NAME)) .filter(moreThanOneHUFoundParam -> moreThanOneHUFoundParam instanceof Boolean) .map(moreThanOneHUFoundParam -> (Boolean)moreThanOneHUFoundParam) .orElse(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HandlingUnitsService.java
1
请完成以下Java代码
public class UpdateProcessPayload implements Payload { private String id; private String processInstanceId; private String name; private String description; private String businessKey; public UpdateProcessPayload() { this.id = UUID.randomUUID().toString(); } public UpdateProcessPayload(String processInstanceId, String name, String description, String businessKey) { this(); this.processInstanceId = processInstanceId; this.name = name; this.description = description; this.businessKey = businessKey; } @Override public String getId() { return id; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId;
} public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\UpdateProcessPayload.java
1
请在Spring Boot框架中完成以下Java代码
public static class Correlation { /** * Whether to enable correlation of the baggage context with logging contexts. */ private boolean enabled = true; /** * List of fields that should be correlated with the logging context. That * means that these fields would end up as key-value pairs in e.g. MDC. */ private List<String> fields = new ArrayList<>(); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getFields() { return this.fields; } public void setFields(List<String> fields) { this.fields = fields; } } } public static class Propagation { /** * Tracing context propagation types produced and consumed by the application. * Setting this property overrides the more fine-grained propagation type * properties. */ private @Nullable List<PropagationType> type; /** * Tracing context propagation types produced by the application. */ private List<PropagationType> produce = List.of(PropagationType.W3C); /** * Tracing context propagation types consumed by the application. */ private List<PropagationType> consume = List.of(PropagationType.values()); public void setType(@Nullable List<PropagationType> type) { this.type = type;
} public void setProduce(List<PropagationType> produce) { this.produce = produce; } public void setConsume(List<PropagationType> consume) { this.consume = consume; } public @Nullable List<PropagationType> getType() { return this.type; } public List<PropagationType> getProduce() { return this.produce; } public List<PropagationType> getConsume() { return this.consume; } /** * Supported propagation types. The declared order of the values matter. */ public enum PropagationType { /** * <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation. */ W3C, /** * <a href="https://github.com/openzipkin/b3-propagation#single-header">B3 * single header</a> propagation. */ B3, /** * <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3 * multiple headers</a> propagation. */ B3_MULTI } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java
2
请完成以下Java代码
public java.math.BigDecimal getPricingSystemSurchargeAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricingSystemSurchargeAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Produktschlüssel.
@param ProductValue Schlüssel des Produktes */ @Override public void setProductValue (java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Produktschlüssel. @return Schlüssel des Produktes */ @Override public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_DiscountSchema.java
1
请完成以下Java代码
public void setElementIndexVariableName(String elementIndexVariableName) { this.elementIndexVariableName = elementIndexVariableName; } public boolean hasLimitedInstanceCount() { return maxInstanceCount != null && maxInstanceCount > 0; } public Integer getMaxInstanceCount() { return maxInstanceCount; } public void setMaxInstanceCount(Integer maxInstanceCount) { this.maxInstanceCount = maxInstanceCount; } public VariableAggregationDefinitions getAggregations() { return aggregations; } public void setAggregations(VariableAggregationDefinitions aggregations) { this.aggregations = aggregations; } public void addAggregation(VariableAggregationDefinition aggregation) { if (this.aggregations == null) { this.aggregations = new VariableAggregationDefinitions();
} this.aggregations.getAggregations().add(aggregation); } @Override public String toString() { return "RepetitionRule{" + " maxInstanceCount='" + (hasLimitedInstanceCount() ? maxInstanceCount : "unlimited") + "'" + " repetitionCounterVariableName='" + repetitionCounterVariableName + "'" + " collectionVariableName='" + collectionVariableName + "'" + " elementVariableName='" + elementVariableName + "'" + " elementIndexVariableName='" + elementIndexVariableName + "'" + " } " + super.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\RepetitionRule.java
1
请完成以下Java代码
static @Nullable PemSslStore load(@Nullable PemSslStoreDetails details) { return load(details, ApplicationResourceLoader.get()); } /** * Return a {@link PemSslStore} instance loaded using the given * {@link PemSslStoreDetails}. * @param details the PEM store details * @param resourceLoader the resource loader used to load content * @return a loaded {@link PemSslStore} or {@code null}. * @since 3.3.5 */ static @Nullable PemSslStore load(@Nullable PemSslStoreDetails details, ResourceLoader resourceLoader) { if (details == null || details.isEmpty()) { return null; } return new LoadedPemSslStore(details, resourceLoader); } /** * Factory method that can be used to create a new {@link PemSslStore} with the given * values. * @param type the key store type * @param certificates the certificates for this store * @param privateKey the private key * @return a new {@link PemSslStore} instance */ static PemSslStore of(@Nullable String type, List<X509Certificate> certificates, @Nullable PrivateKey privateKey) { return of(type, null, null, certificates, privateKey); } /** * Factory method that can be used to create a new {@link PemSslStore} with the given * values. * @param certificates the certificates for this store * @param privateKey the private key * @return a new {@link PemSslStore} instance */ static PemSslStore of(List<X509Certificate> certificates, @Nullable PrivateKey privateKey) { return of(null, null, null, certificates, privateKey); } /** * Factory method that can be used to create a new {@link PemSslStore} with the given * values. * @param type the key store type * @param alias the alias used when setting entries in the {@link KeyStore} * @param password the password used * {@link KeyStore#setKeyEntry(String, java.security.Key, char[], java.security.cert.Certificate[])
* setting key entries} in the {@link KeyStore} * @param certificates the certificates for this store * @param privateKey the private key * @return a new {@link PemSslStore} instance */ static PemSslStore of(@Nullable String type, @Nullable String alias, @Nullable String password, List<X509Certificate> certificates, @Nullable PrivateKey privateKey) { Assert.notEmpty(certificates, "'certificates' must not be empty"); return new PemSslStore() { @Override public @Nullable String type() { return type; } @Override public @Nullable String alias() { return alias; } @Override public @Nullable String password() { return password; } @Override public List<X509Certificate> certificates() { return certificates; } @Override public @Nullable PrivateKey privateKey() { return privateKey; } }; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemSslStore.java
1
请完成以下Java代码
public RfQReportType getRfQReportType(final RfQResponsePublisherRequest request) { final I_C_RfQResponse rfqResponse = request.getC_RfQResponse(); final PublishingType publishingType = request.getPublishingType(); if (publishingType == PublishingType.Invitation) { if (rfqDAO.hasQtyRequiered(rfqResponse)) { return RfQReportType.Invitation; } else { return RfQReportType.InvitationWithoutQtyRequired; } } else if (publishingType == PublishingType.Close) { if (rfqDAO.hasSelectedWinnerLines(rfqResponse)) { return RfQReportType.Won; } else { return RfQReportType.Lost; } } else { throw new AdempiereException("@Invalid@ @PublishingType@: " + publishingType); } } @Nullable private PrintFormatId getPrintFormatId(final I_C_RfQResponse rfqResponse, final RfQReportType rfqReportType) { final I_C_RfQ_Topic rfqTopic = rfqResponse.getC_RfQ().getC_RfQ_Topic(); if (rfqReportType == RfQReportType.Invitation) { return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Invitation_PrintFormat_ID()); } else if (rfqReportType == RfQReportType.InvitationWithoutQtyRequired) { return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_InvitationWithoutQty_PrintFormat_ID()); } else if (rfqReportType == RfQReportType.Won) { return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Win_PrintFormat_ID()); }
else if (rfqReportType == RfQReportType.Lost) { return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Lost_PrintFormat_ID()); } else { throw new AdempiereException("@Invalid@ @Type@: " + rfqReportType); } } private MailTextBuilder createMailTextBuilder(final I_C_RfQResponse rfqResponse, final RfQReportType rfqReportType) { final I_C_RfQ_Topic rfqTopic = rfqResponse.getC_RfQ().getC_RfQ_Topic(); final MailTextBuilder mailTextBuilder; if (rfqReportType == RfQReportType.Invitation) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Invitation_MailText_ID())); } else if (rfqReportType == RfQReportType.InvitationWithoutQtyRequired) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_InvitationWithoutQty_MailText_ID())); } else if (rfqReportType == RfQReportType.Won) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Win_MailText_ID())); } else if (rfqReportType == RfQReportType.Lost) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Lost_MailText_ID())); } else { throw new AdempiereException("@Invalid@ @Type@: " + rfqReportType); } mailTextBuilder.bpartner(rfqResponse.getC_BPartner()); mailTextBuilder.bpartnerContact(rfqResponse.getAD_User()); mailTextBuilder.record(rfqResponse); return mailTextBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\MailRfqResponsePublisherInstance.java
1
请完成以下Java代码
protected final String doIt() { final I_C_Flatrate_DataEntry entryRecord = ProcessUtil.extractEntryOrNull(getProcessInfo()); if (entryRecord == null) { addLog("Currently there is no C_Flatrate_DataEntry selected; nothing to do"); return MSG_OK; } if (entryRecord.isProcessed()) { // it would be nice to open the modal real-only and somehow indicate to the user why it is red-only throw new AdempiereException(AdMessageKey.of("de.metas.ui.web.contract.flatrate.process.WEBUI_C_Flatrate_DataEntry_Detail_Launcher.EntryAlreadyProcessed")).markAsUserValidationError(); } final TableRecordReference recordRef = TableRecordReference.of(entryRecord); final IView view = viewsRepo.createView(createViewRequest(recordRef));
final ViewId viewId = view.getViewId(); getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder() .viewId(viewId.toJson()) .target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay) .build()); return MSG_OK; } private CreateViewRequest createViewRequest(@NonNull final TableRecordReference recordRef) { return dataEntryDedailsViewFactory.createViewRequest(recordRef); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\contract\flatrate\process\WEBUI_C_Flatrate_DataEntry_Detail_Launcher.java
1
请在Spring Boot框架中完成以下Java代码
protected DataResponse<VariableInstanceResponse> getQueryResponse(VariableInstanceQueryRequest queryRequest, Map<String, String> allRequestParams) { VariableInstanceQuery query = runtimeService.createVariableInstanceQuery(); // Populate query based on request if (Boolean.TRUE.equals(queryRequest.getExcludeTaskVariables())) { query.excludeTaskVariables(); } if (Boolean.TRUE.equals(queryRequest.getExcludeLocalVariables())) { query.excludeLocalVariables(); } if (queryRequest.getTaskId() != null) { query.taskId(queryRequest.getTaskId()); } if (queryRequest.getExecutionId() != null) { query.executionId(queryRequest.getExecutionId()); } if (queryRequest.getProcessInstanceId() != null) { query.processInstanceId(queryRequest.getProcessInstanceId()); } if (queryRequest.getVariableName() != null) { query.variableName(queryRequest.getVariableName()); } if (queryRequest.getVariableNameLike() != null) { query.variableNameLike(queryRequest.getVariableNameLike()); } if (queryRequest.getVariables() != null) { addVariables(query, queryRequest.getVariables()); } if (restApiInterceptor != null) { restApiInterceptor.accessVariableInfoWithQuery(query, queryRequest); } return paginateList(allRequestParams, queryRequest, query, "variableName", allowedSortProperties,
restResponseFactory::createVariableInstanceResponseList); } protected void addVariables(VariableInstanceQuery variableInstanceQuery, List<QueryVariable> variables) { for (QueryVariable variable : variables) { if (variable.getVariableOperation() == null) { throw new FlowableIllegalArgumentException("Variable operation is missing for variable: " + variable.getName()); } if (variable.getValue() == null) { throw new FlowableIllegalArgumentException("Variable value is missing for variable: " + variable.getName()); } boolean nameLess = variable.getName() == null; Object actualValue = restResponseFactory.getVariableValue(variable); // A value-only query is only possible using equals-operator if (nameLess) { throw new FlowableIllegalArgumentException("Value-only query (without a variable-name) is not supported"); } switch (variable.getVariableOperation()) { case EQUALS: variableInstanceQuery.variableValueEquals(variable.getName(), actualValue); break; default: throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + variable.getVariableOperation()); } } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\VariableInstanceBaseResource.java
2
请完成以下Java代码
private void initDisjointSets(int totalNodes) { nodes = new ArrayList<>(totalNodes); for (int i = 0; i < totalNodes; i++) { nodes.add(new DisjointSetInfo(i)); } } private Integer find(Integer node) { Integer parent = nodes.get(node).getParentNode(); if (parent.equals(node)) { return node; } else { return find(parent); } } private Integer pathCompressionFind(Integer node) { DisjointSetInfo setInfo = nodes.get(node); Integer parent = setInfo.getParentNode(); if (parent.equals(node)) { return node; } else { Integer parentNode = find(parent); setInfo.setParentNode(parentNode); return parentNode; } } private void union(Integer rootU, Integer rootV) { DisjointSetInfo setInfoU = nodes.get(rootU); setInfoU.setParentNode(rootV); } private void unionByRank(int rootU, int rootV) {
DisjointSetInfo setInfoU = nodes.get(rootU); DisjointSetInfo setInfoV = nodes.get(rootV); int rankU = setInfoU.getRank(); int rankV = setInfoV.getRank(); if (rankU < rankV) { setInfoU.setParentNode(rootV); } else { setInfoV.setParentNode(rootU); if (rankU == rankV) { setInfoU.setRank(rankU + 1); } } } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\kruskal\CycleDetector.java
1
请在Spring Boot框架中完成以下Java代码
public class MarketDataRestController { private final Random random = new Random(); private final RSocketRequester rSocketRequester; public MarketDataRestController(RSocketRequester rSocketRequester) { this.rSocketRequester = rSocketRequester; } @GetMapping(value = "/current/{stock}") public Publisher<MarketData> current(@PathVariable("stock") String stock) { return rSocketRequester.route("currentMarketData") .data(new MarketDataRequest(stock)) .retrieveMono(MarketData.class); } @GetMapping(value = "/feed/{stock}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Publisher<MarketData> feed(@PathVariable("stock") String stock) {
return rSocketRequester.route("feedMarketData") .data(new MarketDataRequest(stock)) .retrieveFlux(MarketData.class); } @GetMapping(value = "/collect") public Publisher<Void> collect() { return rSocketRequester.route("collectMarketData") .data(getMarketData()) .send(); } private MarketData getMarketData() { return new MarketData("X", random.nextInt(10)); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\rsocket\client\MarketDataRestController.java
2
请完成以下Java代码
public int getThreadNum_() { return threadNum_; } public void setThreadNum_(int threadNum_) { this.threadNum_ = threadNum_; } public List<String> getUnigramTempls_() { return unigramTempls_; } public void setUnigramTempls_(List<String> unigramTempls_) { this.unigramTempls_ = unigramTempls_; } public List<String> getBigramTempls_() { return bigramTempls_; } public void setBigramTempls_(List<String> bigramTempls_) { this.bigramTempls_ = bigramTempls_; } public List<String> getY_() { return y_; }
public void setY_(List<String> y_) { this.y_ = y_; } public List<List<Path>> getPathList_() { return pathList_; } public void setPathList_(List<List<Path>> pathList_) { this.pathList_ = pathList_; } public List<List<Node>> getNodeList_() { return nodeList_; } public void setNodeList_(List<List<Node>> nodeList_) { this.nodeList_ = nodeList_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
1
请完成以下Java代码
public ClientSoftwareId getClientSoftwareId() { return config.getClientSoftwareId(); } /** * @param expectedResponseClass if the response is not an instance of this class, the method throws an exception. */ public <T> T sendAndReceive( @NonNull final JAXBElement<?> messagePayload, @NonNull final Class<? extends T> expectedResponseClass) { final String uri = config.getBaseUrl() + urlPrefix; final JAXBElement<?> responseElement = (JAXBElement<?>)webServiceTemplate.marshalSendAndReceive(uri, messagePayload); final Object responseValue = responseElement.getValue(); if (expectedResponseClass.isInstance(responseValue)) { return expectedResponseClass.cast(responseValue); } final FaultInfo faultInfo = faultInfoExtractor.extractFaultInfoOrNull(responseValue); if (faultInfo != null) { throw Msv3ClientException.builder() .msv3FaultInfo(faultInfo) .build() .setParameter("uri", uri) .setParameter("config", config); } else { throw new AdempiereException("Webservice returned unexpected response") .appendParametersToMessage() .setParameter("uri", uri)
.setParameter("config", config) .setParameter("response", responseValue); } } @VisibleForTesting public WebServiceTemplate getWebServiceTemplate() { return webServiceTemplate; } @FunctionalInterface public static interface FaultInfoExtractor { FaultInfo extractFaultInfoOrNull(Object value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3Client.java
1
请完成以下Java代码
public Boolean isTransient(Object entity) { // TODO Auto-generated method stub return null; } @Override public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { // TODO Auto-generated method stub return null; } @Override public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException { // TODO Auto-generated method stub return null; } @Override public String getEntityName(Object object) throws CallbackException { // TODO Auto-generated method stub return null; } @Override public Object getEntity(String entityName, Serializable id) throws CallbackException { // TODO Auto-generated method stub return null; } @Override public void afterTransactionBegin(Transaction tx) {
// TODO Auto-generated method stub } @Override public void beforeTransactionCompletion(Transaction tx) { // TODO Auto-generated method stub } @Override public void afterTransactionCompletion(Transaction tx) { // TODO Auto-generated method stub } @Override public String onPrepareStatement(String sql) { // TODO Auto-generated method stub return null; } }
repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\CustomInterceptorImpl.java
1
请完成以下Java代码
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.delegate.writeHttpHeaders(exchange); } /** * Set the policy to be used in the response header. * @param policy the policy * @throws IllegalArgumentException if policy is {@code null} */ public void setPolicy(ReferrerPolicy policy) { Assert.notNull(policy, "policy must not be null"); this.delegate = createDelegate(policy); } private static ServerHttpHeadersWriter createDelegate(ReferrerPolicy policy) { Builder builder = StaticServerHttpHeadersWriter.builder(); builder.header(REFERRER_POLICY, policy.getPolicy()); return builder.build(); } public enum ReferrerPolicy { NO_REFERRER("no-referrer"), NO_REFERRER_WHEN_DOWNGRADE("no-referrer-when-downgrade"), SAME_ORIGIN("same-origin"), ORIGIN("origin"), STRICT_ORIGIN("strict-origin"),
ORIGIN_WHEN_CROSS_ORIGIN("origin-when-cross-origin"), STRICT_ORIGIN_WHEN_CROSS_ORIGIN("strict-origin-when-cross-origin"), UNSAFE_URL("unsafe-url"); private static final Map<String, ReferrerPolicy> REFERRER_POLICIES; static { Map<String, ReferrerPolicy> referrerPolicies = new HashMap<>(); for (ReferrerPolicy referrerPolicy : values()) { referrerPolicies.put(referrerPolicy.getPolicy(), referrerPolicy); } REFERRER_POLICIES = Collections.unmodifiableMap(referrerPolicies); } private final String policy; ReferrerPolicy(String policy) { this.policy = policy; } public String getPolicy() { return this.policy; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ReferrerPolicyServerHttpHeadersWriter.java
1